@iwas/mcp 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +303 -73
- package/dist/auth/index.d.ts +5 -1
- package/dist/auth/index.js +16 -16
- package/dist/bin.js +18 -18
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -12
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var iy=Object.create;var vn=Object.defineProperty;var ay=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,ly=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},wn=(t,e)=>{for(var r in e)vn(t,r,{get:e[r],enumerable:!0})},Wu=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of cy(e))!ly.call(t,n)&&n!==r&&vn(t,n,{get:()=>e[n],enumerable:!(o=ay(e,n))||o.enumerable});return t};var De=(t,e,r)=>(r=t!=null?iy(uy(t)):{},Wu(e||!t||!t.__esModule?vn(r,"default",{value:t,enumerable:!0}):r,t)),dy=t=>Wu(vn({},"__esModule",{value:!0}),t);var Qu=k(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.MCP_OAUTH_SCOPES=B.OFFLINE_ACCESS_SCOPE=B.MCP_ELIGIBLE_PERMISSION_SET=B.MCP_ELIGIBLE_PERMISSIONS=B.SENSITIVE_MCP_RESOURCES=B.PERMISSION_SET=B.ALL_PERMISSIONS=B.CATALOG_DEFINITIONS=void 0;B.isPermissionString=Ku;B.parsePermissionString=Gu;B.isSensitiveMcpResource=Yu;B.isMcpEligiblePermission=Xu;B.partitionMcpScopes=py;B.CATALOG_DEFINITIONS={organization:{tier:"T",actions:["update","delete"],description:"Organization tenant profile and settings",models:["Organization","OrganizationSetting","OrganizationSubscription"],mcpEligible:!0},member:{tier:"T",actions:["create","update","delete"],description:"Organization member management",models:["Member"],mcpEligible:!0},invitation:{tier:"T",actions:["create","cancel"],description:"Organization membership invitations",models:["Invitation"],mcpEligible:!0},location:{tier:"T",actions:["read","write","delete"],description:"Physical hotspot location management",models:["Location"],mcpEligible:!0},router:{tier:"T",actions:["read","write","delete","control"],description:"Gateway router inventory, provisioning and control",models:["Router","ZtpToken","CoaQueue","IpamAllocationCursor"],mcpEligible:!0},package:{tier:"S",actions:["read","write","delete","publish"],description:"WiFi access package catalog (tenant + shared)",models:["Package","VoucherPackage"],mcpEligible:!0},voucher:{tier:"S",actions:["read","write","publish","issue","revoke"],description:"Prepaid voucher codes and issuance (tenant + shared)",models:["Voucher","VoucherIssuance","VoucherUser"],mcpEligible:!0},session:{tier:"T",actions:["read","control"],description:"Active and historical WiFi guest sessions",models:["WifiSession","RadiusAccounting","DeviceToken"],mcpEligible:!0},wallet:{tier:"T",actions:["read","topup","charge","refund","freeze"],description:"Prepaid wallet balances, topups and ledger transactions (SENSITIVE - MCP EXCLUDED)",models:["Wallet","WalletTransaction","TopupRequest"],hasOwnQualifier:!0,mcpEligible:!1},payment:{tier:"T",actions:["read","approve","refund"],description:"Inbound payment transactions and gateway integrations (SENSITIVE - MCP EXCLUDED)",models:["PaymentTransaction","PaymentGatewayIntegration"],hasOwnQualifier:!0,mcpEligible:!1},subscription:{tier:"T",actions:["read","manage"],description:"SaaS organization plan subscription and entitlements",models:["OrganizationSubscription"],mcpEligible:!0},partner:{tier:"T",actions:["read","manage","payout:approve"],description:"Affiliate/partner programs and payout requests",models:["Partner","PartnerPayoutRequest"],mcpEligible:!0},campaign:{tier:"T",actions:["read","write"],description:"Captive portal ad campaigns and lead capture",models:["AdCampaign","LeadCapture"],mcpEligible:!0},notification:{tier:"T",actions:["read","send","template:write"],description:"Multi-channel notifications, templates and logs",models:["NotificationItem","NotificationTemplate","DeliveryLog"],hasOwnQualifier:!0,mcpEligible:!0},store:{tier:"P",actions:["read","write"],description:"Public hardware/affiliate store catalog",models:["StoreProduct","AffiliateClick"],mcpEligible:!0},blog:{tier:"P",actions:["read","write","publish"],description:"Company-wide editorial articles and CDN media",models:["BlogPost","Media"],hasOwnQualifier:!0,mcpEligible:!0},analytics:{tier:"D",actions:["read"],description:"Aggregated usage, session and revenue metrics",models:["WifiSession","Package","PaymentTransaction"],mcpEligible:!0},diagnostics:{tier:"P",actions:["read","write"],description:"System error events, MCP tool execution spans, flow events, issue triage and audit logs",models:["ErrorEvent","McpToolSpan","AuditLog","SystemSetting","FlowEvent","IssueState"],mcpEligible:!0}};B.ALL_PERMISSIONS=["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","location:read","location:write","location:delete","router:read","router:write","router:delete","router:control","package:read","package:write","package:delete","package:publish","voucher:read","voucher:write","voucher:publish","voucher:issue","voucher:revoke","session:read","session:control","wallet:read","wallet:topup","wallet:charge","wallet:refund","wallet:freeze","payment:read","payment:approve","payment:refund","subscription:read","subscription:manage","partner:read","partner:manage","partner:payout:approve","campaign:read","campaign:write","notification:read","notification:send","notification:template:write","store:read","store:write","blog:read","blog:write","blog:publish","analytics:read","diagnostics:read","diagnostics:write"];B.PERMISSION_SET=new Set(B.ALL_PERMISSIONS);function Ku(t){return typeof t=="string"&&B.PERMISSION_SET.has(t)}function Gu(t){if(!Ku(t))return null;let e=t.indexOf(":"),r=t.slice(0,e),o=t.slice(e+1);return{resource:r,action:o}}B.SENSITIVE_MCP_RESOURCES=["payment","wallet"];function Yu(t){return t==="payment"||t==="wallet"}function Xu(t){let e=Gu(t);return e?!Yu(e.resource):!1}B.MCP_ELIGIBLE_PERMISSIONS=B.ALL_PERMISSIONS.filter(Xu);B.MCP_ELIGIBLE_PERMISSION_SET=new Set(B.MCP_ELIGIBLE_PERMISSIONS);B.OFFLINE_ACCESS_SCOPE="offline_access";B.MCP_OAUTH_SCOPES=[...B.MCP_ELIGIBLE_PERMISSIONS,B.OFFLINE_ACCESS_SCOPE];function py(t){return{permissionScopes:t.filter(e=>e!==B.OFFLINE_ACCESS_SCOPE),offlineAccessRequested:t.includes(B.OFFLINE_ACCESS_SCOPE)}}});var Ro=k(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var Eo=class{};J._CodeOrName=Eo;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var tr=class extends Eo{constructor(e){if(super(),!J.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}}};J.Name=tr;var Je=class extends Eo{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,o)=>`${r}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,o)=>(o instanceof tr&&(r[o.str]=(r[o.str]||0)+1),r),{})}};J._Code=Je;J.nil=new Je("");function jh(t,...e){let r=[t[0]],o=0;for(;o<e.length;)qa(r,e[o]),r.push(t[++o]);return new Je(r)}J._=jh;var Da=new Je("+");function Zh(t,...e){let r=[To(t[0])],o=0;for(;o<e.length;)r.push(Da),qa(r,e[o]),r.push(Da,To(t[++o]));return Pb(r),new Je(r)}J.str=Zh;function qa(t,e){e instanceof Je?t.push(...e._items):e instanceof tr?t.push(e):t.push(Rb(e))}J.addCodeArg=qa;function Pb(t){let e=1;for(;e<t.length-1;){if(t[e]===Da){let r=Eb(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Eb(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof tr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof tr))return`"${t}${e.slice(1)}`}function Tb(t,e){return e.emptyStr()?t:t.emptyStr()?e:Zh`${t}${e}`}J.strConcat=Tb;function Rb(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:To(Array.isArray(t)?t.join(","):t)}function Ib(t){return new Je(To(t))}J.stringify=Ib;function To(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=To;function Cb(t){return typeof t=="string"&&J.IDENTIFIER.test(t)?new Je(`.${t}`):jh`[${t}]`}J.getProperty=Cb;function Ob(t){if(typeof t=="string"&&J.IDENTIFIER.test(t))return new Je(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}J.getEsmExportName=Ob;function Ab(t){return new Je(t.toString())}J.regexpCode=Ab});var Fa=k(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.ValueScope=Ne.ValueScopeName=Ne.Scope=Ne.varKinds=Ne.UsedValueState=void 0;var Ae=Ro(),La=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},os;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(os||(Ne.UsedValueState=os={}));Ne.varKinds={const:new Ae.Name("const"),let:new Ae.Name("let"),var:new Ae.Name("var")};var ns=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ae.Name?e:this.name(e)}name(e){return new Ae.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,o;if(!((o=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||o===void 0)&&o.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}}};Ne.Scope=ns;var ss=class extends Ae.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:o}){this.value=e,this.scopePath=(0,Ae._)`.${new Ae.Name(r)}[${o}]`}};Ne.ValueScopeName=ss;var Nb=(0,Ae._)`\n`,Ua=class extends ns{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Nb:Ae.nil}}get(){return this._scope}name(e){return new ss(e,this._newName(e))}value(e,r){var o;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,i=(o=r.key)!==null&&o!==void 0?o:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,n);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,n.setValue(r,{property:s,itemIndex:u}),n}getValue(e,r){let o=this._values[e];if(o)return o.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,Ae._)`${e}${o.scopePath}`})}scopeCode(e=this._values,r,o){return this._reduceValues(e,n=>{if(n.value===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return n.value.code},r,o)}_reduceValues(e,r,o={},n){let s=Ae.nil;for(let i in e){let a=e[i];if(!a)continue;let c=o[i]=o[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,os.Started);let l=r(u);if(l){let d=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const;s=(0,Ae._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=n?.(u))s=(0,Ae._)`${s}${l}${this.opts._n}`;else throw new La(u);c.set(u,os.Completed)})}return s}};Ne.ValueScope=Ua});var Z=k(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var U=Ro(),Xe=Fa(),qt=Ro();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return qt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return qt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return qt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return qt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return qt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return qt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return qt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return qt.Name}});var us=Fa();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return us.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return us.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return us.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return us.varKinds}});D.operators={GT:new U._Code(">"),GTE:new U._Code(">="),LT:new U._Code("<"),LTE:new U._Code("<="),EQ:new U._Code("==="),NEQ:new U._Code("!=="),NOT:new U._Code("!"),OR:new U._Code("||"),AND:new U._Code("&&"),ADD:new U._Code("+")};var bt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Va=class extends bt{constructor(e,r,o){super(),this.varKind=e,this.name=r,this.rhs=o}render({es5:e,_n:r}){let o=e?Xe.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${n};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Nr(this.rhs,e,r)),this}get names(){return this.rhs instanceof U._CodeOrName?this.rhs.names:{}}},is=class extends bt{constructor(e,r,o){super(),this.lhs=e,this.rhs=r,this.sideEffects=o}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof U.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Nr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof U.Name?{}:{...this.lhs.names};return cs(e,this.rhs)}},Ha=class extends is{constructor(e,r,o,n){super(e,o,n),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ja=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ba=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Wa=class extends bt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ka=class extends bt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Nr(this.code,e,r),this}get names(){return this.code instanceof U._CodeOrName?this.code.names:{}}},Io=class extends bt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,o)=>r+o.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let o=e[r].optimizeNodes();Array.isArray(o)?e.splice(r,1,...o):o?e[r]=o:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:o}=this,n=o.length;for(;n--;){let s=o[n];s.optimizeNames(e,r)||(Mb(e,s.names),o.splice(n,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>nr(e,r.names),{})}},$t=class extends Io{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ga=class extends Io{},Ar=class extends $t{};Ar.kind="else";var rr=class t extends $t{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let o=r.optimizeNodes();r=this.else=Array.isArray(o)?new Ar(o):o}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Dh(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Nr(this.condition,e,r),this}get names(){let e=super.names;return cs(e,this.condition),this.else&&nr(e,this.else.names),e}};rr.kind="if";var or=class extends $t{};or.kind="for";var Ya=class extends or{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Nr(this.iteration,e,r),this}get names(){return nr(super.names,this.iteration.names)}},Xa=class extends or{constructor(e,r,o,n){super(),this.varKind=e,this.name=r,this.from=o,this.to=n}render(e){let r=e.es5?Xe.varKinds.var:this.varKind,{name:o,from:n,to:s}=this;return`for(${r} ${o}=${n}; ${o}<${s}; ${o}++)`+super.render(e)}get names(){let e=cs(super.names,this.from);return cs(e,this.to)}},as=class extends or{constructor(e,r,o,n){super(),this.loop=e,this.varKind=r,this.name=o,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Nr(this.iterable,e,r),this}get names(){return nr(super.names,this.iterable.names)}},Co=class extends $t{constructor(e,r,o){super(),this.name=e,this.args=r,this.async=o}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Co.kind="func";var Oo=class extends Io{render(e){return"return "+super.render(e)}};Oo.kind="return";var Qa=class extends $t{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var o,n;return super.optimizeNames(e,r),(o=this.catch)===null||o===void 0||o.optimizeNames(e,r),(n=this.finally)===null||n===void 0||n.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&nr(e,this.catch.names),this.finally&&nr(e,this.finally.names),e}},Ao=class extends $t{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ao.kind="catch";var No=class extends $t{render(e){return"finally"+super.render(e)}};No.kind="finally";var ec=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
3
|
-
`:""},this._extScope=e,this._scope=new Xe.Scope({parent:e}),this._nodes=[new Ga]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let o=this._extScope.value(e,r);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,o,n){let s=this._scope.toName(r);return o!==void 0&&n&&(this._constants[s.str]=o),this._leafNode(new Va(e,s,o)),s}const(e,r,o){return this._def(Xe.varKinds.const,e,r,o)}let(e,r,o){return this._def(Xe.varKinds.let,e,r,o)}var(e,r,o){return this._def(Xe.varKinds.var,e,r,o)}assign(e,r,o){return this._leafNode(new is(e,r,o))}add(e,r){return this._leafNode(new Ha(e,D.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==U.nil&&this._leafNode(new Ka(e)),this}object(...e){let r=["{"];for(let[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,U.addCodeArg)(r,n));return r.push("}"),new U._Code(r)}if(e,r,o){if(this._blockNode(new rr(e)),r&&o)this.code(r).else().code(o).endIf();else if(r)this.code(r).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new rr(e))}else(){return this._elseNode(new Ar)}endIf(){return this._endBlockNode(rr,Ar)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ya(e),r)}forRange(e,r,o,n,s=this.opts.es5?Xe.varKinds.var:Xe.varKinds.let){let i=this._scope.toName(e);return this._for(new Xa(s,i,r,o),()=>n(i))}forOf(e,r,o,n=Xe.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof U.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,U._)`${i}.length`,a=>{this.var(s,(0,U._)`${i}[${a}]`),o(s)})}return this._for(new as("of",n,s,r),()=>o(s))}forIn(e,r,o,n=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,U._)`Object.keys(${r})`,o);let s=this._scope.toName(e);return this._for(new as("in",n,s,r),()=>o(s))}endFor(){return this._endBlockNode(or)}label(e){return this._leafNode(new Ja(e))}break(e){return this._leafNode(new Ba(e))}return(e){let r=new Oo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Oo)}try(e,r,o){if(!r&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let n=new Qa;if(this._blockNode(n),this.code(e),r){let s=this.name("e");this._currNode=n.catch=new Ao(s),r(s)}return o&&(this._currNode=n.finally=new No,this.code(o)),this._endBlockNode(Ao,No)}throw(e){return this._leafNode(new Wa(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-r;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=U.nil,o,n){return this._blockNode(new Co(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(Co)}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,r){let o=this._currNode;if(o instanceof e||r&&o instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof rr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};D.CodeGen=ec;function nr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function cs(t,e){return e instanceof U._CodeOrName?nr(t,e.names):t}function Nr(t,e,r){if(t instanceof U.Name)return o(t);if(!n(t))return t;return new U._Code(t._items.reduce((s,i)=>(i instanceof U.Name&&(i=o(i)),i instanceof U._Code?s.push(...i._items):s.push(i),s),[]));function o(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function n(s){return s instanceof U._Code&&s._items.some(i=>i instanceof U.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Mb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Dh(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,U._)`!${tc(t)}`}D.not=Dh;var jb=qh(D.operators.AND);function Zb(...t){return t.reduce(jb)}D.and=Zb;var Db=qh(D.operators.OR);function qb(...t){return t.reduce(Db)}D.or=qb;function qh(t){return(e,r)=>e===U.nil?r:r===U.nil?e:(0,U._)`${tc(e)} ${t} ${tc(r)}`}function tc(t){return t instanceof U.Name?t:(0,U._)`(${t})`}});var F=k(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var ee=Z(),Lb=Ro();function Ub(t){let e={};for(let r of t)e[r]=!0;return e}q.toHash=Ub;function Fb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Fh(t,e),!Vh(e,t.self.RULES.all))}q.alwaysValidSchema=Fb;function Fh(t,e=t.schema){let{opts:r,self:o}=t;if(!r.strictSchema||typeof e=="boolean")return;let n=o.RULES.keywords;for(let s in e)n[s]||Bh(t,`unknown keyword: "${s}"`)}q.checkUnknownRules=Fh;function Vh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}q.schemaHasRules=Vh;function Vb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}q.schemaHasRulesButRef=Vb;function Hb({topSchemaRef:t,schemaPath:e},r,o,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ee._)`${r}`}return(0,ee._)`${t}${e}${(0,ee.getProperty)(o)}`}q.schemaRefOrVal=Hb;function Jb(t){return Hh(decodeURIComponent(t))}q.unescapeFragment=Jb;function Bb(t){return encodeURIComponent(oc(t))}q.escapeFragment=Bb;function oc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=oc;function Hh(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=Hh;function Wb(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}q.eachItem=Wb;function Lh({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:o}){return(n,s,i,a)=>{let c=i===void 0?s:i instanceof ee.Name?(s instanceof ee.Name?t(n,s,i):e(n,s,i),i):s instanceof ee.Name?(e(n,i,s),s):r(s,i);return a===ee.Name&&!(c instanceof ee.Name)?o(n,c):c}}q.mergeEvaluated={props:Lh({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ee._)`${r} || {}`).code((0,ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ee._)`${r} || {}`),nc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jh}),items:Lh({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jh(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ee._)`{}`);return e!==void 0&&nc(t,r,e),r}q.evaluatedPropsToName=Jh;function nc(t,e,r){Object.keys(r).forEach(o=>t.assign((0,ee._)`${e}${(0,ee.getProperty)(o)}`,!0))}q.setEvaluated=nc;var Uh={};function Kb(t,e){return t.scopeValue("func",{ref:e,code:Uh[e.code]||(Uh[e.code]=new Lb._Code(e.code))})}q.useFunc=Kb;var rc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(rc||(q.Type=rc={}));function Gb(t,e,r){if(t instanceof ee.Name){let o=e===rc.Num;return r?o?(0,ee._)`"[" + ${t} + "]"`:(0,ee._)`"['" + ${t} + "']"`:o?(0,ee._)`"/" + ${t}`:(0,ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ee.getProperty)(t).toString():"/"+oc(t)}q.getErrorPath=Gb;function Bh(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}q.checkStrictMode=Bh});var St=k(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var xe=Z(),Yb={data:new xe.Name("data"),valCxt:new xe.Name("valCxt"),instancePath:new xe.Name("instancePath"),parentData:new xe.Name("parentData"),parentDataProperty:new xe.Name("parentDataProperty"),rootData:new xe.Name("rootData"),dynamicAnchors:new xe.Name("dynamicAnchors"),vErrors:new xe.Name("vErrors"),errors:new xe.Name("errors"),this:new xe.Name("this"),self:new xe.Name("self"),scope:new xe.Name("scope"),json:new xe.Name("json"),jsonPos:new xe.Name("jsonPos"),jsonLen:new xe.Name("jsonLen"),jsonPart:new xe.Name("jsonPart")};sc.default=Yb});var Mo=k(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.extendErrors=ke.resetErrorsCount=ke.reportExtraError=ke.reportError=ke.keyword$DataError=ke.keywordError=void 0;var V=Z(),ls=F(),Te=St();ke.keywordError={message:({keyword:t})=>(0,V.str)`must pass "${t}" keyword validation`};ke.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,V.str)`"${t}" keyword must be ${e} ($data)`:(0,V.str)`"${t}" keyword is invalid ($data)`};function Xb(t,e=ke.keywordError,r,o){let{it:n}=t,{gen:s,compositeRule:i,allErrors:a}=n,c=Gh(t,e,r);o??(i||a)?Wh(s,c):Kh(n,(0,V._)`[${c}]`)}ke.reportError=Xb;function Qb(t,e=ke.keywordError,r){let{it:o}=t,{gen:n,compositeRule:s,allErrors:i}=o,a=Gh(t,e,r);Wh(n,a),s||i||Kh(o,Te.default.vErrors)}ke.reportExtraError=Qb;function e$(t,e){t.assign(Te.default.errors,e),t.if((0,V._)`${Te.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,V._)`${Te.default.vErrors}.length`,e),()=>t.assign(Te.default.vErrors,null)))}ke.resetErrorsCount=e$;function t$({gen:t,keyword:e,schemaValue:r,data:o,errsCount:n,it:s}){if(n===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",n,Te.default.errors,a=>{t.const(i,(0,V._)`${Te.default.vErrors}[${a}]`),t.if((0,V._)`${i}.instancePath === undefined`,()=>t.assign((0,V._)`${i}.instancePath`,(0,V.strConcat)(Te.default.instancePath,s.errorPath))),t.assign((0,V._)`${i}.schemaPath`,(0,V.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,V._)`${i}.schema`,r),t.assign((0,V._)`${i}.data`,o))})}ke.extendErrors=t$;function Wh(t,e){let r=t.const("err",e);t.if((0,V._)`${Te.default.vErrors} === null`,()=>t.assign(Te.default.vErrors,(0,V._)`[${r}]`),(0,V._)`${Te.default.vErrors}.push(${r})`),t.code((0,V._)`${Te.default.errors}++`)}function Kh(t,e){let{gen:r,validateName:o,schemaEnv:n}=t;n.$async?r.throw((0,V._)`new ${t.ValidationError}(${e})`):(r.assign((0,V._)`${o}.errors`,e),r.return(!1))}var sr={keyword:new V.Name("keyword"),schemaPath:new V.Name("schemaPath"),params:new V.Name("params"),propertyName:new V.Name("propertyName"),message:new V.Name("message"),schema:new V.Name("schema"),parentSchema:new V.Name("parentSchema")};function Gh(t,e,r){let{createErrors:o}=t.it;return o===!1?(0,V._)`{}`:r$(t,e,r)}function r$(t,e,r={}){let{gen:o,it:n}=t,s=[o$(n,r),n$(t,r)];return s$(t,e,s),o.object(...s)}function o$({errorPath:t},{instancePath:e}){let r=e?(0,V.str)`${t}${(0,ls.getErrorPath)(e,ls.Type.Str)}`:t;return[Te.default.instancePath,(0,V.strConcat)(Te.default.instancePath,r)]}function n$({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:o}){let n=o?e:(0,V.str)`${e}/${t}`;return r&&(n=(0,V.str)`${n}${(0,ls.getErrorPath)(r,ls.Type.Str)}`),[sr.schemaPath,n]}function s$(t,{params:e,message:r},o){let{keyword:n,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;o.push([sr.keyword,n],[sr.params,typeof e=="function"?e(t):e||(0,V._)`{}`]),c.messages&&o.push([sr.message,typeof r=="function"?r(t):r]),c.verbose&&o.push([sr.schema,i],[sr.parentSchema,(0,V._)`${l}${d}`],[Te.default.data,s]),u&&o.push([sr.propertyName,u])}});var Xh=k(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.boolOrEmptySchema=Mr.topBoolOrEmptySchema=void 0;var i$=Mo(),a$=Z(),c$=St(),u$={message:"boolean schema is false"};function l$(t){let{gen:e,schema:r,validateName:o}=t;r===!1?Yh(t,!1):typeof r=="object"&&r.$async===!0?e.return(c$.default.data):(e.assign((0,a$._)`${o}.errors`,null),e.return(!0))}Mr.topBoolOrEmptySchema=l$;function d$(t,e){let{gen:r,schema:o}=t;o===!1?(r.var(e,!1),Yh(t)):r.var(e,!0)}Mr.boolOrEmptySchema=d$;function Yh(t,e){let{gen:r,data:o}=t,n={gen:r,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,i$.reportError)(n,u$,void 0,e)}});var ic=k(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.getRules=jr.isJSONType=void 0;var p$=["string","number","integer","boolean","null","object","array"],f$=new Set(p$);function h$(t){return typeof t=="string"&&f$.has(t)}jr.isJSONType=h$;function m$(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}jr.getRules=m$});var ac=k(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.shouldUseRule=Lt.shouldUseGroup=Lt.schemaHasRulesForType=void 0;function g$({schema:t,self:e},r){let o=e.RULES.types[r];return o&&o!==!0&&Qh(t,o)}Lt.schemaHasRulesForType=g$;function Qh(t,e){return e.rules.some(r=>em(t,r))}Lt.shouldUseGroup=Qh;function em(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(o=>t[o]!==void 0))}Lt.shouldUseRule=em});var jo=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var _$=ic(),y$=ac(),v$=Mo(),M=Z(),tm=F(),Zr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Zr||(ze.DataType=Zr={}));function w$(t){let e=rm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ze.getSchemaTypes=w$;function rm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(_$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=rm;function b$(t,e){let{gen:r,data:o,opts:n}=t,s=$$(e,n.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,y$.schemaHasRulesForType)(t,e[0]));if(i){let a=uc(e,o,n.strictNumbers,Zr.Wrong);r.if(a,()=>{s.length?S$(t,e,s):lc(t)})}return i}ze.coerceAndCheckDataType=b$;var om=new Set(["string","number","integer","boolean","null"]);function $$(t,e){return e?t.filter(r=>om.has(r)||e==="array"&&r==="array"):[]}function S$(t,e,r){let{gen:o,data:n,opts:s}=t,i=o.let("dataType",(0,M._)`typeof ${n}`),a=o.let("coerced",(0,M._)`undefined`);s.coerceTypes==="array"&&o.if((0,M._)`${i} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,M._)`${n}[0]`).assign(i,(0,M._)`typeof ${n}`).if(uc(e,n,s.strictNumbers),()=>o.assign(a,n))),o.if((0,M._)`${a} !== undefined`);for(let u of r)(om.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);o.else(),lc(t),o.endIf(),o.if((0,M._)`${a} !== undefined`,()=>{o.assign(n,a),x$(t,a)});function c(u){switch(u){case"string":o.elseIf((0,M._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,M._)`"" + ${n}`).elseIf((0,M._)`${n} === null`).assign(a,(0,M._)`""`);return;case"number":o.elseIf((0,M._)`${i} == "boolean" || ${n} === null
|
|
2
|
+
"use strict";var iy=Object.create;var vn=Object.defineProperty;var ay=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,ly=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},wn=(t,e)=>{for(var r in e)vn(t,r,{get:e[r],enumerable:!0})},Wu=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of cy(e))!ly.call(t,n)&&n!==r&&vn(t,n,{get:()=>e[n],enumerable:!(o=ay(e,n))||o.enumerable});return t};var De=(t,e,r)=>(r=t!=null?iy(uy(t)):{},Wu(e||!t||!t.__esModule?vn(r,"default",{value:t,enumerable:!0}):r,t)),dy=t=>Wu(vn({},"__esModule",{value:!0}),t);var Qu=k(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.MCP_OAUTH_SCOPES=B.OFFLINE_ACCESS_SCOPE=B.MCP_ELIGIBLE_PERMISSION_SET=B.MCP_ELIGIBLE_PERMISSIONS=B.SENSITIVE_MCP_RESOURCES=B.PERMISSION_SET=B.ALL_PERMISSIONS=B.CATALOG_DEFINITIONS=void 0;B.isPermissionString=Ku;B.parsePermissionString=Gu;B.isSensitiveMcpResource=Yu;B.isMcpEligiblePermission=Xu;B.partitionMcpScopes=py;B.CATALOG_DEFINITIONS={organization:{tier:"T",actions:["update","delete"],description:"Organization tenant profile and settings",models:["Organization","OrganizationSetting","OrganizationSubscription"],mcpEligible:!0},member:{tier:"T",actions:["create","update","delete"],description:"Organization member management",models:["Member"],mcpEligible:!0},invitation:{tier:"T",actions:["create","cancel"],description:"Organization membership invitations",models:["Invitation"],mcpEligible:!0},location:{tier:"T",actions:["read","write","delete"],description:"Physical hotspot location management",models:["Location"],mcpEligible:!0},router:{tier:"T",actions:["read","write","delete","control"],description:"Gateway router inventory, provisioning and control",models:["Router","ZtpToken","CoaQueue","IpamAllocationCursor"],mcpEligible:!0},package:{tier:"S",actions:["read","write","delete","publish"],description:"WiFi access package catalog (tenant + shared)",models:["Package","VoucherPackage"],mcpEligible:!0},voucher:{tier:"S",actions:["read","write","publish","issue","revoke"],description:"Prepaid voucher codes and issuance (tenant + shared)",models:["Voucher","VoucherIssuance","VoucherUser"],mcpEligible:!0},session:{tier:"T",actions:["read","control"],description:"Active and historical WiFi guest sessions",models:["WifiSession","RadiusAccounting","DeviceToken"],mcpEligible:!0},wallet:{tier:"T",actions:["read","topup","charge","refund","freeze"],description:"Prepaid wallet balances, topups and ledger transactions (SENSITIVE - MCP EXCLUDED)",models:["Wallet","WalletTransaction","TopupRequest"],hasOwnQualifier:!0,mcpEligible:!1},payment:{tier:"T",actions:["read","approve","refund"],description:"Inbound payment transactions and gateway integrations (SENSITIVE - MCP EXCLUDED)",models:["PaymentTransaction","PaymentGatewayIntegration"],hasOwnQualifier:!0,mcpEligible:!1},subscription:{tier:"T",actions:["read","manage"],description:"SaaS organization plan subscription and entitlements",models:["OrganizationSubscription"],mcpEligible:!0},partner:{tier:"T",actions:["read","manage","payout:approve"],description:"Affiliate/partner programs and payout requests",models:["Partner","PartnerPayoutRequest"],mcpEligible:!0},campaign:{tier:"T",actions:["read","write"],description:"Captive portal ad campaigns and lead capture",models:["AdCampaign","LeadCapture"],mcpEligible:!0},notification:{tier:"T",actions:["read","send","template:write"],description:"Multi-channel notifications, templates and logs",models:["NotificationItem","NotificationTemplate","DeliveryLog"],hasOwnQualifier:!0,mcpEligible:!0},store:{tier:"P",actions:["read","write"],description:"Public hardware/affiliate store catalog",models:["StoreProduct","AffiliateClick"],mcpEligible:!0},blog:{tier:"P",actions:["read","write","publish"],description:"Company-wide editorial articles and CDN media",models:["BlogPost","Media"],hasOwnQualifier:!0,mcpEligible:!0},analytics:{tier:"D",actions:["read"],description:"Aggregated usage, session and revenue metrics",models:["WifiSession","Package","PaymentTransaction"],mcpEligible:!0},diagnostics:{tier:"P",actions:["read","write"],description:"System error events, MCP tool execution spans, flow events, issue triage and audit logs",models:["ErrorEvent","McpToolSpan","AuditLog","SystemSetting","FlowEvent","IssueState"],mcpEligible:!0}};B.ALL_PERMISSIONS=["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","location:read","location:write","location:delete","router:read","router:write","router:delete","router:control","package:read","package:write","package:delete","package:publish","voucher:read","voucher:write","voucher:publish","voucher:issue","voucher:revoke","session:read","session:control","wallet:read","wallet:topup","wallet:charge","wallet:refund","wallet:freeze","payment:read","payment:approve","payment:refund","subscription:read","subscription:manage","partner:read","partner:manage","partner:payout:approve","campaign:read","campaign:write","notification:read","notification:send","notification:template:write","store:read","store:write","blog:read","blog:write","blog:publish","analytics:read","diagnostics:read","diagnostics:write"];B.PERMISSION_SET=new Set(B.ALL_PERMISSIONS);function Ku(t){return typeof t=="string"&&B.PERMISSION_SET.has(t)}function Gu(t){if(!Ku(t))return null;let e=t.indexOf(":"),r=t.slice(0,e),o=t.slice(e+1);return{resource:r,action:o}}B.SENSITIVE_MCP_RESOURCES=["payment","wallet"];function Yu(t){return t==="payment"||t==="wallet"}function Xu(t){let e=Gu(t);return e?!Yu(e.resource):!1}B.MCP_ELIGIBLE_PERMISSIONS=B.ALL_PERMISSIONS.filter(Xu);B.MCP_ELIGIBLE_PERMISSION_SET=new Set(B.MCP_ELIGIBLE_PERMISSIONS);B.OFFLINE_ACCESS_SCOPE="offline_access";B.MCP_OAUTH_SCOPES=[...B.MCP_ELIGIBLE_PERMISSIONS,B.OFFLINE_ACCESS_SCOPE];function py(t){return{permissionScopes:t.filter(e=>e!==B.OFFLINE_ACCESS_SCOPE),offlineAccessRequested:t.includes(B.OFFLINE_ACCESS_SCOPE)}}});var Ro=k(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var Eo=class{};J._CodeOrName=Eo;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var tr=class extends Eo{constructor(e){if(super(),!J.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}}};J.Name=tr;var Je=class extends Eo{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,o)=>`${r}${o}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,o)=>(o instanceof tr&&(r[o.str]=(r[o.str]||0)+1),r),{})}};J._Code=Je;J.nil=new Je("");function jh(t,...e){let r=[t[0]],o=0;for(;o<e.length;)qa(r,e[o]),r.push(t[++o]);return new Je(r)}J._=jh;var Da=new Je("+");function Zh(t,...e){let r=[To(t[0])],o=0;for(;o<e.length;)r.push(Da),qa(r,e[o]),r.push(Da,To(t[++o]));return Eb(r),new Je(r)}J.str=Zh;function qa(t,e){e instanceof Je?t.push(...e._items):e instanceof tr?t.push(e):t.push(Ib(e))}J.addCodeArg=qa;function Eb(t){let e=1;for(;e<t.length-1;){if(t[e]===Da){let r=Tb(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Tb(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof tr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof tr))return`"${t}${e.slice(1)}`}function Rb(t,e){return e.emptyStr()?t:t.emptyStr()?e:Zh`${t}${e}`}J.strConcat=Rb;function Ib(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:To(Array.isArray(t)?t.join(","):t)}function Cb(t){return new Je(To(t))}J.stringify=Cb;function To(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=To;function Ob(t){return typeof t=="string"&&J.IDENTIFIER.test(t)?new Je(`.${t}`):jh`[${t}]`}J.getProperty=Ob;function Ab(t){if(typeof t=="string"&&J.IDENTIFIER.test(t))return new Je(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}J.getEsmExportName=Ab;function Nb(t){return new Je(t.toString())}J.regexpCode=Nb});var Fa=k(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.ValueScope=Ne.ValueScopeName=Ne.Scope=Ne.varKinds=Ne.UsedValueState=void 0;var Ae=Ro(),La=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},os;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(os||(Ne.UsedValueState=os={}));Ne.varKinds={const:new Ae.Name("const"),let:new Ae.Name("let"),var:new Ae.Name("var")};var ns=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ae.Name?e:this.name(e)}name(e){return new Ae.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,o;if(!((o=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||o===void 0)&&o.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}}};Ne.Scope=ns;var ss=class extends Ae.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:o}){this.value=e,this.scopePath=(0,Ae._)`.${new Ae.Name(r)}[${o}]`}};Ne.ValueScopeName=ss;var Mb=(0,Ae._)`\n`,Ua=class extends ns{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Mb:Ae.nil}}get(){return this._scope}name(e){return new ss(e,this._newName(e))}value(e,r){var o;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,i=(o=r.key)!==null&&o!==void 0?o:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,n);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,n.setValue(r,{property:s,itemIndex:u}),n}getValue(e,r){let o=this._values[e];if(o)return o.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,Ae._)`${e}${o.scopePath}`})}scopeCode(e=this._values,r,o){return this._reduceValues(e,n=>{if(n.value===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return n.value.code},r,o)}_reduceValues(e,r,o={},n){let s=Ae.nil;for(let i in e){let a=e[i];if(!a)continue;let c=o[i]=o[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,os.Started);let l=r(u);if(l){let d=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const;s=(0,Ae._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=n?.(u))s=(0,Ae._)`${s}${l}${this.opts._n}`;else throw new La(u);c.set(u,os.Completed)})}return s}};Ne.ValueScope=Ua});var Z=k(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var U=Ro(),Xe=Fa(),qt=Ro();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return qt._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return qt.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return qt.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return qt.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return qt.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return qt.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return qt.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return qt.Name}});var us=Fa();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return us.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return us.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return us.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return us.varKinds}});D.operators={GT:new U._Code(">"),GTE:new U._Code(">="),LT:new U._Code("<"),LTE:new U._Code("<="),EQ:new U._Code("==="),NEQ:new U._Code("!=="),NOT:new U._Code("!"),OR:new U._Code("||"),AND:new U._Code("&&"),ADD:new U._Code("+")};var bt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Va=class extends bt{constructor(e,r,o){super(),this.varKind=e,this.name=r,this.rhs=o}render({es5:e,_n:r}){let o=e?Xe.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${n};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Nr(this.rhs,e,r)),this}get names(){return this.rhs instanceof U._CodeOrName?this.rhs.names:{}}},is=class extends bt{constructor(e,r,o){super(),this.lhs=e,this.rhs=r,this.sideEffects=o}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof U.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Nr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof U.Name?{}:{...this.lhs.names};return cs(e,this.rhs)}},Ha=class extends is{constructor(e,r,o,n){super(e,o,n),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ja=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ba=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Wa=class extends bt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ka=class extends bt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Nr(this.code,e,r),this}get names(){return this.code instanceof U._CodeOrName?this.code.names:{}}},Io=class extends bt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,o)=>r+o.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let o=e[r].optimizeNodes();Array.isArray(o)?e.splice(r,1,...o):o?e[r]=o:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:o}=this,n=o.length;for(;n--;){let s=o[n];s.optimizeNames(e,r)||(jb(e,s.names),o.splice(n,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>nr(e,r.names),{})}},$t=class extends Io{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ga=class extends Io{},Ar=class extends $t{};Ar.kind="else";var rr=class t extends $t{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let o=r.optimizeNodes();r=this.else=Array.isArray(o)?new Ar(o):o}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Dh(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Nr(this.condition,e,r),this}get names(){let e=super.names;return cs(e,this.condition),this.else&&nr(e,this.else.names),e}};rr.kind="if";var or=class extends $t{};or.kind="for";var Ya=class extends or{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Nr(this.iteration,e,r),this}get names(){return nr(super.names,this.iteration.names)}},Xa=class extends or{constructor(e,r,o,n){super(),this.varKind=e,this.name=r,this.from=o,this.to=n}render(e){let r=e.es5?Xe.varKinds.var:this.varKind,{name:o,from:n,to:s}=this;return`for(${r} ${o}=${n}; ${o}<${s}; ${o}++)`+super.render(e)}get names(){let e=cs(super.names,this.from);return cs(e,this.to)}},as=class extends or{constructor(e,r,o,n){super(),this.loop=e,this.varKind=r,this.name=o,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Nr(this.iterable,e,r),this}get names(){return nr(super.names,this.iterable.names)}},Co=class extends $t{constructor(e,r,o){super(),this.name=e,this.args=r,this.async=o}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Co.kind="func";var Oo=class extends Io{render(e){return"return "+super.render(e)}};Oo.kind="return";var Qa=class extends $t{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var o,n;return super.optimizeNames(e,r),(o=this.catch)===null||o===void 0||o.optimizeNames(e,r),(n=this.finally)===null||n===void 0||n.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&nr(e,this.catch.names),this.finally&&nr(e,this.finally.names),e}},Ao=class extends $t{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ao.kind="catch";var No=class extends $t{render(e){return"finally"+super.render(e)}};No.kind="finally";var ec=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
3
|
+
`:""},this._extScope=e,this._scope=new Xe.Scope({parent:e}),this._nodes=[new Ga]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let o=this._extScope.value(e,r);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,o,n){let s=this._scope.toName(r);return o!==void 0&&n&&(this._constants[s.str]=o),this._leafNode(new Va(e,s,o)),s}const(e,r,o){return this._def(Xe.varKinds.const,e,r,o)}let(e,r,o){return this._def(Xe.varKinds.let,e,r,o)}var(e,r,o){return this._def(Xe.varKinds.var,e,r,o)}assign(e,r,o){return this._leafNode(new is(e,r,o))}add(e,r){return this._leafNode(new Ha(e,D.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==U.nil&&this._leafNode(new Ka(e)),this}object(...e){let r=["{"];for(let[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,U.addCodeArg)(r,n));return r.push("}"),new U._Code(r)}if(e,r,o){if(this._blockNode(new rr(e)),r&&o)this.code(r).else().code(o).endIf();else if(r)this.code(r).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new rr(e))}else(){return this._elseNode(new Ar)}endIf(){return this._endBlockNode(rr,Ar)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ya(e),r)}forRange(e,r,o,n,s=this.opts.es5?Xe.varKinds.var:Xe.varKinds.let){let i=this._scope.toName(e);return this._for(new Xa(s,i,r,o),()=>n(i))}forOf(e,r,o,n=Xe.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof U.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,U._)`${i}.length`,a=>{this.var(s,(0,U._)`${i}[${a}]`),o(s)})}return this._for(new as("of",n,s,r),()=>o(s))}forIn(e,r,o,n=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,U._)`Object.keys(${r})`,o);let s=this._scope.toName(e);return this._for(new as("in",n,s,r),()=>o(s))}endFor(){return this._endBlockNode(or)}label(e){return this._leafNode(new Ja(e))}break(e){return this._leafNode(new Ba(e))}return(e){let r=new Oo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Oo)}try(e,r,o){if(!r&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let n=new Qa;if(this._blockNode(n),this.code(e),r){let s=this.name("e");this._currNode=n.catch=new Ao(s),r(s)}return o&&(this._currNode=n.finally=new No,this.code(o)),this._endBlockNode(Ao,No)}throw(e){return this._leafNode(new Wa(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-r;if(o<0||e!==void 0&&o!==e)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=U.nil,o,n){return this._blockNode(new Co(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(Co)}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,r){let o=this._currNode;if(o instanceof e||r&&o instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof rr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};D.CodeGen=ec;function nr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function cs(t,e){return e instanceof U._CodeOrName?nr(t,e.names):t}function Nr(t,e,r){if(t instanceof U.Name)return o(t);if(!n(t))return t;return new U._Code(t._items.reduce((s,i)=>(i instanceof U.Name&&(i=o(i)),i instanceof U._Code?s.push(...i._items):s.push(i),s),[]));function o(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function n(s){return s instanceof U._Code&&s._items.some(i=>i instanceof U.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function jb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Dh(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,U._)`!${tc(t)}`}D.not=Dh;var Zb=qh(D.operators.AND);function Db(...t){return t.reduce(Zb)}D.and=Db;var qb=qh(D.operators.OR);function Lb(...t){return t.reduce(qb)}D.or=Lb;function qh(t){return(e,r)=>e===U.nil?r:r===U.nil?e:(0,U._)`${tc(e)} ${t} ${tc(r)}`}function tc(t){return t instanceof U.Name?t:(0,U._)`(${t})`}});var F=k(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var ee=Z(),Ub=Ro();function Fb(t){let e={};for(let r of t)e[r]=!0;return e}q.toHash=Fb;function Vb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Fh(t,e),!Vh(e,t.self.RULES.all))}q.alwaysValidSchema=Vb;function Fh(t,e=t.schema){let{opts:r,self:o}=t;if(!r.strictSchema||typeof e=="boolean")return;let n=o.RULES.keywords;for(let s in e)n[s]||Bh(t,`unknown keyword: "${s}"`)}q.checkUnknownRules=Fh;function Vh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}q.schemaHasRules=Vh;function Hb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}q.schemaHasRulesButRef=Hb;function Jb({topSchemaRef:t,schemaPath:e},r,o,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ee._)`${r}`}return(0,ee._)`${t}${e}${(0,ee.getProperty)(o)}`}q.schemaRefOrVal=Jb;function Bb(t){return Hh(decodeURIComponent(t))}q.unescapeFragment=Bb;function Wb(t){return encodeURIComponent(oc(t))}q.escapeFragment=Wb;function oc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=oc;function Hh(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=Hh;function Kb(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}q.eachItem=Kb;function Lh({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:o}){return(n,s,i,a)=>{let c=i===void 0?s:i instanceof ee.Name?(s instanceof ee.Name?t(n,s,i):e(n,s,i),i):s instanceof ee.Name?(e(n,i,s),s):r(s,i);return a===ee.Name&&!(c instanceof ee.Name)?o(n,c):c}}q.mergeEvaluated={props:Lh({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ee._)`${r} || {}`).code((0,ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ee._)`${r} || {}`),nc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jh}),items:Lh({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jh(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ee._)`{}`);return e!==void 0&&nc(t,r,e),r}q.evaluatedPropsToName=Jh;function nc(t,e,r){Object.keys(r).forEach(o=>t.assign((0,ee._)`${e}${(0,ee.getProperty)(o)}`,!0))}q.setEvaluated=nc;var Uh={};function Gb(t,e){return t.scopeValue("func",{ref:e,code:Uh[e.code]||(Uh[e.code]=new Ub._Code(e.code))})}q.useFunc=Gb;var rc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(rc||(q.Type=rc={}));function Yb(t,e,r){if(t instanceof ee.Name){let o=e===rc.Num;return r?o?(0,ee._)`"[" + ${t} + "]"`:(0,ee._)`"['" + ${t} + "']"`:o?(0,ee._)`"/" + ${t}`:(0,ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ee.getProperty)(t).toString():"/"+oc(t)}q.getErrorPath=Yb;function Bh(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}q.checkStrictMode=Bh});var St=k(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var xe=Z(),Xb={data:new xe.Name("data"),valCxt:new xe.Name("valCxt"),instancePath:new xe.Name("instancePath"),parentData:new xe.Name("parentData"),parentDataProperty:new xe.Name("parentDataProperty"),rootData:new xe.Name("rootData"),dynamicAnchors:new xe.Name("dynamicAnchors"),vErrors:new xe.Name("vErrors"),errors:new xe.Name("errors"),this:new xe.Name("this"),self:new xe.Name("self"),scope:new xe.Name("scope"),json:new xe.Name("json"),jsonPos:new xe.Name("jsonPos"),jsonLen:new xe.Name("jsonLen"),jsonPart:new xe.Name("jsonPart")};sc.default=Xb});var Mo=k(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.extendErrors=ke.resetErrorsCount=ke.reportExtraError=ke.reportError=ke.keyword$DataError=ke.keywordError=void 0;var V=Z(),ls=F(),Te=St();ke.keywordError={message:({keyword:t})=>(0,V.str)`must pass "${t}" keyword validation`};ke.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,V.str)`"${t}" keyword must be ${e} ($data)`:(0,V.str)`"${t}" keyword is invalid ($data)`};function Qb(t,e=ke.keywordError,r,o){let{it:n}=t,{gen:s,compositeRule:i,allErrors:a}=n,c=Gh(t,e,r);o??(i||a)?Wh(s,c):Kh(n,(0,V._)`[${c}]`)}ke.reportError=Qb;function e0(t,e=ke.keywordError,r){let{it:o}=t,{gen:n,compositeRule:s,allErrors:i}=o,a=Gh(t,e,r);Wh(n,a),s||i||Kh(o,Te.default.vErrors)}ke.reportExtraError=e0;function t0(t,e){t.assign(Te.default.errors,e),t.if((0,V._)`${Te.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,V._)`${Te.default.vErrors}.length`,e),()=>t.assign(Te.default.vErrors,null)))}ke.resetErrorsCount=t0;function r0({gen:t,keyword:e,schemaValue:r,data:o,errsCount:n,it:s}){if(n===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",n,Te.default.errors,a=>{t.const(i,(0,V._)`${Te.default.vErrors}[${a}]`),t.if((0,V._)`${i}.instancePath === undefined`,()=>t.assign((0,V._)`${i}.instancePath`,(0,V.strConcat)(Te.default.instancePath,s.errorPath))),t.assign((0,V._)`${i}.schemaPath`,(0,V.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,V._)`${i}.schema`,r),t.assign((0,V._)`${i}.data`,o))})}ke.extendErrors=r0;function Wh(t,e){let r=t.const("err",e);t.if((0,V._)`${Te.default.vErrors} === null`,()=>t.assign(Te.default.vErrors,(0,V._)`[${r}]`),(0,V._)`${Te.default.vErrors}.push(${r})`),t.code((0,V._)`${Te.default.errors}++`)}function Kh(t,e){let{gen:r,validateName:o,schemaEnv:n}=t;n.$async?r.throw((0,V._)`new ${t.ValidationError}(${e})`):(r.assign((0,V._)`${o}.errors`,e),r.return(!1))}var sr={keyword:new V.Name("keyword"),schemaPath:new V.Name("schemaPath"),params:new V.Name("params"),propertyName:new V.Name("propertyName"),message:new V.Name("message"),schema:new V.Name("schema"),parentSchema:new V.Name("parentSchema")};function Gh(t,e,r){let{createErrors:o}=t.it;return o===!1?(0,V._)`{}`:o0(t,e,r)}function o0(t,e,r={}){let{gen:o,it:n}=t,s=[n0(n,r),s0(t,r)];return i0(t,e,s),o.object(...s)}function n0({errorPath:t},{instancePath:e}){let r=e?(0,V.str)`${t}${(0,ls.getErrorPath)(e,ls.Type.Str)}`:t;return[Te.default.instancePath,(0,V.strConcat)(Te.default.instancePath,r)]}function s0({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:o}){let n=o?e:(0,V.str)`${e}/${t}`;return r&&(n=(0,V.str)`${n}${(0,ls.getErrorPath)(r,ls.Type.Str)}`),[sr.schemaPath,n]}function i0(t,{params:e,message:r},o){let{keyword:n,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;o.push([sr.keyword,n],[sr.params,typeof e=="function"?e(t):e||(0,V._)`{}`]),c.messages&&o.push([sr.message,typeof r=="function"?r(t):r]),c.verbose&&o.push([sr.schema,i],[sr.parentSchema,(0,V._)`${l}${d}`],[Te.default.data,s]),u&&o.push([sr.propertyName,u])}});var Xh=k(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.boolOrEmptySchema=Mr.topBoolOrEmptySchema=void 0;var a0=Mo(),c0=Z(),u0=St(),l0={message:"boolean schema is false"};function d0(t){let{gen:e,schema:r,validateName:o}=t;r===!1?Yh(t,!1):typeof r=="object"&&r.$async===!0?e.return(u0.default.data):(e.assign((0,c0._)`${o}.errors`,null),e.return(!0))}Mr.topBoolOrEmptySchema=d0;function p0(t,e){let{gen:r,schema:o}=t;o===!1?(r.var(e,!1),Yh(t)):r.var(e,!0)}Mr.boolOrEmptySchema=p0;function Yh(t,e){let{gen:r,data:o}=t,n={gen:r,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,a0.reportError)(n,l0,void 0,e)}});var ic=k(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.getRules=jr.isJSONType=void 0;var f0=["string","number","integer","boolean","null","object","array"],h0=new Set(f0);function m0(t){return typeof t=="string"&&h0.has(t)}jr.isJSONType=m0;function g0(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}jr.getRules=g0});var ac=k(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.shouldUseRule=Lt.shouldUseGroup=Lt.schemaHasRulesForType=void 0;function _0({schema:t,self:e},r){let o=e.RULES.types[r];return o&&o!==!0&&Qh(t,o)}Lt.schemaHasRulesForType=_0;function Qh(t,e){return e.rules.some(r=>em(t,r))}Lt.shouldUseGroup=Qh;function em(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(o=>t[o]!==void 0))}Lt.shouldUseRule=em});var jo=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var y0=ic(),v0=ac(),w0=Mo(),M=Z(),tm=F(),Zr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Zr||(ze.DataType=Zr={}));function b0(t){let e=rm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ze.getSchemaTypes=b0;function rm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(y0.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=rm;function $0(t,e){let{gen:r,data:o,opts:n}=t,s=S0(e,n.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,v0.schemaHasRulesForType)(t,e[0]));if(i){let a=uc(e,o,n.strictNumbers,Zr.Wrong);r.if(a,()=>{s.length?x0(t,e,s):lc(t)})}return i}ze.coerceAndCheckDataType=$0;var om=new Set(["string","number","integer","boolean","null"]);function S0(t,e){return e?t.filter(r=>om.has(r)||e==="array"&&r==="array"):[]}function x0(t,e,r){let{gen:o,data:n,opts:s}=t,i=o.let("dataType",(0,M._)`typeof ${n}`),a=o.let("coerced",(0,M._)`undefined`);s.coerceTypes==="array"&&o.if((0,M._)`${i} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,M._)`${n}[0]`).assign(i,(0,M._)`typeof ${n}`).if(uc(e,n,s.strictNumbers),()=>o.assign(a,n))),o.if((0,M._)`${a} !== undefined`);for(let u of r)(om.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);o.else(),lc(t),o.endIf(),o.if((0,M._)`${a} !== undefined`,()=>{o.assign(n,a),k0(t,a)});function c(u){switch(u){case"string":o.elseIf((0,M._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,M._)`"" + ${n}`).elseIf((0,M._)`${n} === null`).assign(a,(0,M._)`""`);return;case"number":o.elseIf((0,M._)`${i} == "boolean" || ${n} === null
|
|
4
4
|
|| (${i} == "string" && ${n} && ${n} == +${n})`).assign(a,(0,M._)`+${n}`);return;case"integer":o.elseIf((0,M._)`${i} === "boolean" || ${n} === null
|
|
5
5
|
|| (${i} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,(0,M._)`+${n}`);return;case"boolean":o.elseIf((0,M._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf((0,M._)`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":o.elseIf((0,M._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(a,null);return;case"array":o.elseIf((0,M._)`${i} === "string" || ${i} === "number"
|
|
6
|
-
|| ${i} === "boolean" || ${n} === null`).assign(a,(0,M._)`[${n}]`)}}}function x$({gen:t,parentData:e,parentDataProperty:r},o){t.if((0,M._)`${e} !== undefined`,()=>t.assign((0,M._)`${e}[${r}]`,o))}function cc(t,e,r,o=Zr.Correct){let n=o===Zr.Correct?M.operators.EQ:M.operators.NEQ,s;switch(t){case"null":return(0,M._)`${e} ${n} null`;case"array":s=(0,M._)`Array.isArray(${e})`;break;case"object":s=(0,M._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,M._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,M._)`typeof ${e} ${n} ${t}`}return o===Zr.Correct?s:(0,M.not)(s);function i(a=M.nil){return(0,M.and)((0,M._)`typeof ${e} == "number"`,a,r?(0,M._)`isFinite(${e})`:M.nil)}}ze.checkDataType=cc;function uc(t,e,r,o){if(t.length===1)return cc(t[0],e,r,o);let n,s=(0,tm.toHash)(t);if(s.array&&s.object){let i=(0,M._)`typeof ${e} != "object"`;n=s.null?i:(0,M._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else n=M.nil;s.number&&delete s.integer;for(let i in s)n=(0,M.and)(n,cc(i,e,r,o));return n}ze.checkDataTypes=uc;var k$={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,M._)`{type: ${t}}`:(0,M._)`{type: ${e}}`};function lc(t){let e=z$(t);(0,v$.reportError)(e,k$)}ze.reportTypeError=lc;function z$(t){let{gen:e,data:r,schema:o}=t,n=(0,tm.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:t}}});var sm=k(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.assignDefaults=void 0;var Dr=Z(),P$=F();function E$(t,e){let{properties:r,items:o}=t.schema;if(e==="object"&&r)for(let n in r)nm(t,n,r[n].default);else e==="array"&&Array.isArray(o)&&o.forEach((n,s)=>nm(t,s,n.default))}ds.assignDefaults=E$;function nm(t,e,r){let{gen:o,compositeRule:n,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Dr._)`${s}${(0,Dr.getProperty)(e)}`;if(n){(0,P$.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Dr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Dr._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,Dr._)`${a} = ${(0,Dr.stringify)(r)}`)}});var Be=k(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.validateUnion=Y.validateArray=Y.usePattern=Y.callValidateCode=Y.schemaProperties=Y.allSchemaProperties=Y.noPropertyInData=Y.propertyInData=Y.isOwnProperty=Y.hasPropFunc=Y.reportMissingProp=Y.checkMissingProp=Y.checkReportMissingProp=void 0;var ne=Z(),dc=F(),Ut=St(),T$=F();function R$(t,e){let{gen:r,data:o,it:n}=t;r.if(fc(r,o,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ne._)`${e}`},!0),t.error()})}Y.checkReportMissingProp=R$;function I$({gen:t,data:e,it:{opts:r}},o,n){return(0,ne.or)(...o.map(s=>(0,ne.and)(fc(t,e,s,r.ownProperties),(0,ne._)`${n} = ${s}`)))}Y.checkMissingProp=I$;function C$(t,e){t.setParams({missingProperty:e},!0),t.error()}Y.reportMissingProp=C$;function im(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ne._)`Object.prototype.hasOwnProperty`})}Y.hasPropFunc=im;function pc(t,e,r){return(0,ne._)`${im(t)}.call(${e}, ${r})`}Y.isOwnProperty=pc;function O$(t,e,r,o){let n=(0,ne._)`${e}${(0,ne.getProperty)(r)} !== undefined`;return o?(0,ne._)`${n} && ${pc(t,e,r)}`:n}Y.propertyInData=O$;function fc(t,e,r,o){let n=(0,ne._)`${e}${(0,ne.getProperty)(r)} === undefined`;return o?(0,ne.or)(n,(0,ne.not)(pc(t,e,r))):n}Y.noPropertyInData=fc;function am(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Y.allSchemaProperties=am;function A$(t,e){return am(e).filter(r=>!(0,dc.alwaysValidSchema)(t,e[r]))}Y.schemaProperties=A$;function N$({schemaCode:t,data:e,it:{gen:r,topSchemaRef:o,schemaPath:n,errorPath:s},it:i},a,c,u){let l=u?(0,ne._)`${t}, ${e}, ${o}${n}`:e,d=[[Ut.default.instancePath,(0,ne.strConcat)(Ut.default.instancePath,s)],[Ut.default.parentData,i.parentData],[Ut.default.parentDataProperty,i.parentDataProperty],[Ut.default.rootData,Ut.default.rootData]];i.opts.dynamicRef&&d.push([Ut.default.dynamicAnchors,Ut.default.dynamicAnchors]);let p=(0,ne._)`${l}, ${r.object(...d)}`;return c!==ne.nil?(0,ne._)`${a}.call(${c}, ${p})`:(0,ne._)`${a}(${p})`}Y.callValidateCode=N$;var M$=(0,ne._)`new RegExp`;function j$({gen:t,it:{opts:e}},r){let o=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,o);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ne._)`${n.code==="new RegExp"?M$:(0,T$.useFunc)(t,n)}(${r}, ${o})`})}Y.usePattern=j$;function Z$(t){let{gen:e,data:r,keyword:o,it:n}=t,s=e.name("valid");if(n.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ne._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:dc.Type.Num},s),e.if((0,ne.not)(s),a)})}}Y.validateArray=Z$;function D$(t){let{gen:e,schema:r,keyword:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,dc.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:o,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ne._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ne.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Y.validateUnion=D$});var lm=k(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateKeywordUsage=st.validSchemaType=st.funcKeywordCode=st.macroKeywordCode=void 0;var Re=Z(),ir=St(),q$=Be(),L$=Mo();function U$(t,e){let{gen:r,keyword:o,schema:n,parentSchema:s,it:i}=t,a=e.macro.call(i.self,n,s,i),c=um(r,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Re.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}st.macroKeywordCode=U$;function F$(t,e){var r;let{gen:o,keyword:n,schema:s,parentSchema:i,$data:a,it:c}=t;H$(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=um(o,n,u),d=o.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&cm(t),_(()=>t.error());else{let w=e.async?f():h();e.modifying&&cm(t),_(()=>V$(t,w))}}function f(){let w=o.let("ruleErrs",null);return o.try(()=>g((0,Re._)`await `),b=>o.assign(d,!1).if((0,Re._)`${b} instanceof ${c.ValidationError}`,()=>o.assign(w,(0,Re._)`${b}.errors`),()=>o.throw(b))),w}function h(){let w=(0,Re._)`${l}.errors`;return o.assign(w,null),g(Re.nil),w}function g(w=e.async?(0,Re._)`await `:Re.nil){let b=c.opts.passContext?ir.default.this:ir.default.self,z=!("compile"in e&&!a||e.schema===!1);o.assign(d,(0,Re._)`${w}${(0,q$.callValidateCode)(t,l,b,z)}`,e.modifying)}function _(w){var b;o.if((0,Re.not)((b=e.valid)!==null&&b!==void 0?b:d),w)}}st.funcKeywordCode=F$;function cm(t){let{gen:e,data:r,it:o}=t;e.if(o.parentData,()=>e.assign(r,(0,Re._)`${o.parentData}[${o.parentDataProperty}]`))}function V$(t,e){let{gen:r}=t;r.if((0,Re._)`Array.isArray(${e})`,()=>{r.assign(ir.default.vErrors,(0,Re._)`${ir.default.vErrors} === null ? ${e} : ${ir.default.vErrors}.concat(${e})`).assign(ir.default.errors,(0,Re._)`${ir.default.vErrors}.length`),(0,L$.extendErrors)(t)},()=>t.error())}function H$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function um(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Re.stringify)(r)})}function J$(t,e,r=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||r&&typeof t>"u")}st.validSchemaType=J$;function B$({schema:t,opts:e,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");let i=n.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}st.validateKeywordUsage=B$});var pm=k(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.extendSubschemaMode=Ft.extendSubschemaData=Ft.getSubschema=void 0;var it=Z(),dm=F();function W$(t,{keyword:e,schemaProp:r,schema:o,schemaPath:n,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,it._)`${t.schemaPath}${(0,it.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,it._)`${t.schemaPath}${(0,it.getProperty)(e)}${(0,it.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,dm.escapeFragment)(r)}`}}if(o!==void 0){if(n===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:n,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ft.getSubschema=W$;function K$(t,e,{dataProp:r,dataPropType:o,data:n,dataTypes:s,propertyName:i}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,it._)`${e.data}${(0,it.getProperty)(r)}`,!0);c(p),t.errorPath=(0,it.str)`${u}${(0,dm.getErrorPath)(r,o,d.jsPropertySyntax)}`,t.parentDataProperty=(0,it._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(n!==void 0){let u=n instanceof it.Name?n:a.let("data",n,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Ft.extendSubschemaData=K$;function G$(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){o!==void 0&&(t.compositeRule=o),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Ft.extendSubschemaMode=G$});var hc=k((tA,fm)=>{"use strict";fm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var mm=k((rA,hm)=>{"use strict";var Vt=hm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var o=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};ps(e,o,n,t,"",t)};Vt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vt.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};function ps(t,e,r,o,n,s,i,a,c,u){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,n,s,i,a,c,u);for(var l in o){var d=o[l];if(Array.isArray(d)){if(l in Vt.arrayKeywords)for(var p=0;p<d.length;p++)ps(t,e,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Vt.propsKeywords){if(d&&typeof d=="object")for(var f in d)ps(t,e,r,d[f],n+"/"+l+"/"+Y$(f),s,n,l,o,f)}else(l in Vt.keywords||t.allKeys&&!(l in Vt.skipKeywords))&&ps(t,e,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,i,a,c,u)}}function Y$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zo=k(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var X$=F(),Q$=hc(),e0=mm(),t0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function r0(t,e=!0){return typeof t=="boolean"?!0:e===!0?!mc(t):e?gm(t)<=e:!1}Me.inlineRef=r0;var o0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mc(t){for(let e in t){if(o0.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(mc)||typeof r=="object"&&mc(r))return!0}return!1}function gm(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!t0.has(r)&&(typeof t[r]=="object"&&(0,X$.eachItem)(t[r],o=>e+=gm(o)),e===1/0))return 1/0}return e}function _m(t,e="",r){r!==!1&&(e=qr(e));let o=t.parse(e);return ym(t,o)}Me.getFullPath=_m;function ym(t,e){return t.serialize(e).split("#")[0]+"#"}Me._getFullPath=ym;var n0=/#\/?$/;function qr(t){return t?t.replace(n0,""):""}Me.normalizeId=qr;function s0(t,e,r){return r=qr(r),t.resolve(e,r)}Me.resolveUrl=s0;var i0=/^[a-z_][-a-z0-9._]*$/i;function a0(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:o}=this.opts,n=qr(t[r]||e),s={"":n},i=_m(o,n,!1),a={},c=new Set;return e0(t,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let g=i+p,_=s[h];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[p]=_;function w(z){let E=this.opts.uriResolver.resolve;if(z=qr(_?E(_,z):z),c.has(z))throw l(z);c.add(z);let v=this.refs[z];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,z):z!==qr(g)&&(z[0]==="#"?(u(d,a[z],z),a[z]=d):this.refs[z]=g),z}function b(z){if(typeof z=="string"){if(!i0.test(z))throw new Error(`invalid anchor "${z}"`);w.call(this,`#${z}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Q$(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Me.getSchemaRefs=a0});var Lo=k(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.getData=Ht.KeywordCxt=Ht.validateFunctionCode=void 0;var Sm=Xh(),vm=jo(),_c=ac(),fs=jo(),c0=sm(),qo=lm(),gc=pm(),R=Z(),A=St(),u0=Zo(),xt=F(),Do=Mo();function l0(t){if(zm(t)&&(Pm(t),km(t))){f0(t);return}xm(t,()=>(0,Sm.topBoolOrEmptySchema)(t))}Ht.validateFunctionCode=l0;function xm({gen:t,validateName:e,schema:r,schemaEnv:o,opts:n},s){n.code.es5?t.func(e,(0,R._)`${A.default.data}, ${A.default.valCxt}`,o.$async,()=>{t.code((0,R._)`"use strict"; ${wm(r,n)}`),p0(t,n),t.code(s)}):t.func(e,(0,R._)`${A.default.data}, ${d0(n)}`,o.$async,()=>t.code(wm(r,n)).code(s))}function d0(t){return(0,R._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${t.dynamicRef?(0,R._)`, ${A.default.dynamicAnchors}={}`:R.nil}}={}`}function p0(t,e){t.if(A.default.valCxt,()=>{t.var(A.default.instancePath,(0,R._)`${A.default.valCxt}.${A.default.instancePath}`),t.var(A.default.parentData,(0,R._)`${A.default.valCxt}.${A.default.parentData}`),t.var(A.default.parentDataProperty,(0,R._)`${A.default.valCxt}.${A.default.parentDataProperty}`),t.var(A.default.rootData,(0,R._)`${A.default.valCxt}.${A.default.rootData}`),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,R._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{t.var(A.default.instancePath,(0,R._)`""`),t.var(A.default.parentData,(0,R._)`undefined`),t.var(A.default.parentDataProperty,(0,R._)`undefined`),t.var(A.default.rootData,A.default.data),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,R._)`{}`)})}function f0(t){let{schema:e,opts:r,gen:o}=t;xm(t,()=>{r.$comment&&e.$comment&&Tm(t),y0(t),o.let(A.default.vErrors,null),o.let(A.default.errors,0),r.unevaluated&&h0(t),Em(t),b0(t)})}function h0(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,R._)`${r}.evaluated`),e.if((0,R._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,R._)`${t.evaluated}.props`,(0,R._)`undefined`)),e.if((0,R._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,R._)`${t.evaluated}.items`,(0,R._)`undefined`))}function wm(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,R._)`/*# sourceURL=${r} */`:R.nil}function m0(t,e){if(zm(t)&&(Pm(t),km(t))){g0(t,e);return}(0,Sm.boolOrEmptySchema)(t,e)}function km({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function zm(t){return typeof t.schema!="boolean"}function g0(t,e){let{schema:r,gen:o,opts:n}=t;n.$comment&&r.$comment&&Tm(t),v0(t),w0(t);let s=o.const("_errs",A.default.errors);Em(t,s),o.var(e,(0,R._)`${s} === ${A.default.errors}`)}function Pm(t){(0,xt.checkUnknownRules)(t),_0(t)}function Em(t,e){if(t.opts.jtd)return bm(t,[],!1,e);let r=(0,vm.getSchemaTypes)(t.schema),o=(0,vm.coerceAndCheckDataType)(t,r);bm(t,r,!o,e)}function _0(t){let{schema:e,errSchemaPath:r,opts:o,self:n}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,xt.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function y0(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,xt.checkStrictMode)(t,"default is ignored in the schema root")}function v0(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,u0.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function w0(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Tm({gen:t,schemaEnv:e,schema:r,errSchemaPath:o,opts:n}){let s=r.$comment;if(n.$comment===!0)t.code((0,R._)`${A.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let i=(0,R.str)`${o}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,R._)`${A.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function b0(t){let{gen:e,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=t;r.$async?e.if((0,R._)`${A.default.errors} === 0`,()=>e.return(A.default.data),()=>e.throw((0,R._)`new ${n}(${A.default.vErrors})`)):(e.assign((0,R._)`${o}.errors`,A.default.vErrors),s.unevaluated&&$0(t),e.return((0,R._)`${A.default.errors} === 0`))}function $0({gen:t,evaluated:e,props:r,items:o}){r instanceof R.Name&&t.assign((0,R._)`${e}.props`,r),o instanceof R.Name&&t.assign((0,R._)`${e}.items`,o)}function bm(t,e,r,o){let{gen:n,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,xt.schemaHasRulesButRef)(s,l))){n.block(()=>Im(t,"$ref",l.all.$ref.definition));return}c.jtd||S0(t,e),n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,_c.shouldUseGroup)(s,p)&&(p.type?(n.if((0,fs.checkDataType)(p.type,i,c.strictNumbers)),$m(t,p),e.length===1&&e[0]===p.type&&r&&(n.else(),(0,fs.reportTypeError)(t)),n.endIf()):$m(t,p),a||n.if((0,R._)`${A.default.errors} === ${o||0}`))}}function $m(t,e){let{gen:r,schema:o,opts:{useDefaults:n}}=t;n&&(0,c0.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,_c.shouldUseRule)(o,s)&&Im(t,s.keyword,s.definition,e.type)})}function S0(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(x0(t,e),t.opts.allowUnionTypes||k0(t,e),z0(t,t.dataTypes))}function x0(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Rm(t.dataTypes,r)||yc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),E0(t,e)}}function k0(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yc(t,"use allowUnionTypes to allow union type keyword")}function z0(t,e){let r=t.self.RULES.all;for(let o in r){let n=r[o];if(typeof n=="object"&&(0,_c.shouldUseRule)(t.schema,n)){let{type:s}=n.definition;s.length&&!s.some(i=>P0(e,i))&&yc(t,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function P0(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Rm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function E0(t,e){let r=[];for(let o of t.dataTypes)Rm(e,o)?r.push(o):e.includes("integer")&&o==="number"&&r.push("integer");t.dataTypes=r}function yc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,xt.checkStrictMode)(t,e,t.opts.strictTypes)}var hs=class{constructor(e,r,o){if((0,qo.validateKeywordUsage)(e,r,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,xt.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Cm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,qo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",A.default.errors))}result(e,r,o){this.failResult((0,R.not)(e),r,o)}failResult(e,r,o){this.gen.if(e),o?o():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,R.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,R._)`${r} !== undefined && (${(0,R.or)(this.invalid$data(),e)})`)}error(e,r,o){if(r){this.setParams(r),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,r){(e?Do.reportExtraError:Do.reportError)(this,this.def.error,r)}$dataError(){(0,Do.reportError)(this,this.def.$dataError||Do.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Do.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,o=R.nil){this.gen.block(()=>{this.check$data(e,o),r()})}check$data(e=R.nil,r=R.nil){if(!this.$data)return;let{gen:o,schemaCode:n,schemaType:s,def:i}=this;o.if((0,R.or)((0,R._)`${n} === undefined`,r)),e!==R.nil&&o.assign(e,!0),(s.length||i.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==R.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:o,def:n,it:s}=this;return(0,R.or)(i(),a());function i(){if(o.length){if(!(r instanceof R.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,R._)`${(0,fs.checkDataTypes)(c,r,s.opts.strictNumbers,fs.DataType.Wrong)}`}return R.nil}function a(){if(n.validateSchema){let c=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,R._)`!${c}(${r})`}return R.nil}}subschema(e,r){let o=(0,gc.getSubschema)(this.it,e);(0,gc.extendSubschemaData)(o,this.it,e),(0,gc.extendSubschemaMode)(o,e);let n={...this.it,...o,items:void 0,props:void 0};return m0(n,r),n}mergeEvaluated(e,r){let{it:o,gen:n}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=xt.mergeEvaluated.props(n,e.props,o.props,r)),o.items!==!0&&e.items!==void 0&&(o.items=xt.mergeEvaluated.items(n,e.items,o.items,r)))}mergeValidEvaluated(e,r){let{it:o,gen:n}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,R.Name)),!0}};Ht.KeywordCxt=hs;function Im(t,e,r,o){let n=new hs(t,r,e);"code"in r?r.code(n,o):n.$data&&r.validate?(0,qo.funcKeywordCode)(n,r):"macro"in r?(0,qo.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,qo.funcKeywordCode)(n,r)}var T0=/^\/(?:[^~]|~0|~1)*$/,R0=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Cm(t,{dataLevel:e,dataNames:r,dataPathArr:o}){let n,s;if(t==="")return A.default.rootData;if(t[0]==="/"){if(!T0.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=A.default.rootData}else{let u=R0.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=e)throw new Error(c("property/index",l));return o[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!n)return s}let i=s,a=n.split("/");for(let u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,xt.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Ht.getData=Cm});var ms=k(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var vc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};wc.default=vc});var Uo=k(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var bc=Zo(),$c=class extends Error{constructor(e,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,bc.resolveUrl)(e,r,o),this.missingSchema=(0,bc.normalizeId)((0,bc.getFullPath)(e,this.missingRef))}};Sc.default=$c});var _s=k(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.resolveSchema=We.getCompilingSchema=We.resolveRef=We.compileSchema=We.SchemaEnv=void 0;var Qe=Z(),I0=ms(),ar=St(),et=Zo(),Om=F(),C0=Lo(),Lr=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,et.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};We.SchemaEnv=Lr;function kc(t){let e=Am.call(this,t);if(e)return e;let r=(0,et.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,i=new Qe.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:I0.default,code:(0,Qe._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ar.default.data,parentData:ar.default.parentData,parentDataProperty:ar.default.parentDataProperty,dataNames:[ar.default.data],dataPathArr:[Qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Qe.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Qe.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qe._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,C0.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ar.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ar.default.self}`,`${ar.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;f.evaluated={props:h instanceof Qe.Name?void 0:h,items:g instanceof Qe.Name?void 0:g,dynamicProps:h instanceof Qe.Name,dynamicItems:g instanceof Qe.Name},f.source&&(f.source.evaluated=(0,Qe.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}We.compileSchema=kc;function O0(t,e,r){var o;r=(0,et.resolveUrl)(this.opts.uriResolver,e,r);let n=t.refs[r];if(n)return n;let s=M0.call(this,t,r);if(s===void 0){let i=(o=t.localRefs)===null||o===void 0?void 0:o[r],{schemaId:a}=this.opts;i&&(s=new Lr({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=A0.call(this,s)}We.resolveRef=O0;function A0(t){return(0,et.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:kc.call(this,t)}function Am(t){for(let e of this._compilations)if(N0(e,t))return e}We.getCompilingSchema=Am;function N0(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function M0(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||gs.call(this,t,e)}function gs(t,e){let r=this.opts.uriResolver.parse(e),o=(0,et._getFullPath)(this.opts.uriResolver,r),n=(0,et.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===n)return xc.call(this,r,t);let s=(0,et.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=gs.call(this,t,i);return typeof a?.schema!="object"?void 0:xc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||kc.call(this,i),s===(0,et.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(n=(0,et.resolveUrl)(this.opts.uriResolver,n,u)),new Lr({schema:a,schemaId:c,root:t,baseId:n})}return xc.call(this,r,i)}}We.resolveSchema=gs;var j0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xc(t,{baseId:e,schema:r,root:o}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Om.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!j0.has(a)&&u&&(e=(0,et.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Om.schemaHasRulesButRef)(r,this.RULES)){let a=(0,et.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=gs.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new Lr({schema:r,schemaId:i,root:o,baseId:e}),s.schema!==s.root.schema)return s}});var Nm=k((cA,Z0)=>{Z0.exports={$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:!1}});var Pc=k((uA,Dm)=>{"use strict";var D0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jm=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 zc(t){let e="",r=0,o=0;for(o=0;o<t.length;o++)if(r=t[o].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o];break}for(o+=1;o<t.length;o++){if(r=t[o].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o]}return e}var q0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mm(t){return t.length=0,!0}function L0(t,e,r){if(t.length){let o=zc(t);if(o!=="")e.push(o);else return r.error=!0,!1;t.length=0}return!0}function U0(t){let e=0,r={error:!1,address:"",zone:""},o=[],n=[],s=!1,i=!1,a=L0;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(n,o,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),o.push(":");continue}else if(u==="%"){if(!a(n,o,r))break;a=Mm}else{n.push(u);continue}}return n.length&&(a===Mm?r.zone=n.join(""):i?o.push(n.join("")):o.push(zc(n))),r.address=o.join(""),r}function Zm(t){if(F0(t,":")<2)return{host:t,isIPV6:!1};let e=U0(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,o=e.address;return e.zone&&(r+="%"+e.zone,o+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:o}}}function F0(t,e){let r=0;for(let o=0;o<t.length;o++)t[o]===e&&r++;return r}function V0(t){let e=t,r=[],o=-1,n=0;for(;n=e.length;){if(n===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(n===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(n===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((o=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,o)),e=e.slice(o)}return r.join("")}function H0(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function J0(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!jm(r)){let o=Zm(r);o.isIPV6===!0?r=`[${o.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Dm.exports={nonSimpleDomain:q0,recomposeAuthority:J0,normalizeComponentEncoding:H0,removeDotSegments:V0,isIPv4:jm,isUUID:D0,normalizeIPv6:Zm,stringArrayToHexStripped:zc}});var Vm=k((lA,Fm)=>{"use strict";var{isUUID:B0}=Pc(),W0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,K0=["http","https","ws","wss","urn","urn:uuid"];function G0(t){return K0.indexOf(t)!==-1}function Ec(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function qm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Lm(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Y0(t){return t.secure=Ec(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function X0(t){if((t.port===(Ec(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Q0(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(W0);if(r){let o=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let n=`${o}:${e.nid||t.nid}`,s=Tc(n);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function eS(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),n=`${r}:${e.nid||o}`,s=Tc(n);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${o||e.nid}:${a}`,e.skipEscape=!0,i}function tS(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!B0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function rS(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Um={scheme:"http",domainHost:!0,parse:qm,serialize:Lm},oS={scheme:"https",domainHost:Um.domainHost,parse:qm,serialize:Lm},ys={scheme:"ws",domainHost:!0,parse:Y0,serialize:X0},nS={scheme:"wss",domainHost:ys.domainHost,parse:ys.parse,serialize:ys.serialize},sS={scheme:"urn",parse:Q0,serialize:eS,skipNormalize:!0},iS={scheme:"urn:uuid",parse:tS,serialize:rS,skipNormalize:!0},vs={http:Um,https:oS,ws:ys,wss:nS,urn:sS,"urn:uuid":iS};Object.setPrototypeOf(vs,null);function Tc(t){return t&&(vs[t]||vs[t.toLowerCase()])||void 0}Fm.exports={wsIsSecure:Ec,SCHEMES:vs,isValidSchemeName:G0,getSchemeHandler:Tc}});var Bm=k((dA,bs)=>{"use strict";var{normalizeIPv6:aS,removeDotSegments:Fo,recomposeAuthority:cS,normalizeComponentEncoding:ws,isIPv4:uS,nonSimpleDomain:lS}=Pc(),{SCHEMES:dS,getSchemeHandler:Hm}=Vm();function pS(t,e){return typeof t=="string"?t=at(kt(t,e),e):typeof t=="object"&&(t=kt(at(t,e),e)),t}function fS(t,e,r){let o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Jm(kt(t,o),kt(e,o),o,!0);return o.skipEscape=!0,at(n,o)}function Jm(t,e,r,o){let n={};return o||(t=kt(at(t,r),r),e=kt(at(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Fo(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Fo(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=Fo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=Fo(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function hS(t,e,r){return typeof t=="string"?(t=unescape(t),t=at(ws(kt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=at(ws(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=at(ws(kt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=at(ws(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function at(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),n=[],s=Hm(o.scheme||r.scheme);s&&s.serialize&&s.serialize(r,o),r.path!==void 0&&(o.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),o.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");let i=cS(r);if(i!==void 0&&(o.reference!=="suffix"&&n.push("//"),n.push(i),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let a=r.path;!o.absolutePath&&(!s||!s.absolutePath)&&(a=Fo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),n.push(a)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}var mS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kt(t,e){let r=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(mS);if(s){if(o.scheme=s[1],o.userinfo=s[3],o.host=s[4],o.port=parseInt(s[5],10),o.path=s[6]||"",o.query=s[7],o.fragment=s[8],isNaN(o.port)&&(o.port=s[5]),o.host)if(uS(o.host)===!1){let c=aS(o.host);o.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");let i=Hm(r.scheme||o.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&o.host&&(r.domainHost||i&&i.domainHost)&&n===!1&&lS(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(a){o.error=o.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=unescape(o.host))),o.path&&(o.path=escape(unescape(o.path))),o.fragment&&(o.fragment=encodeURI(decodeURIComponent(o.fragment)))),i&&i.parse&&i.parse(o,r)}else o.error=o.error||"URI can not be parsed.";return o}var Rc={SCHEMES:dS,normalize:pS,resolve:fS,resolveComponent:Jm,equal:hS,serialize:at,parse:kt};bs.exports=Rc;bs.exports.default=Rc;bs.exports.fastUri=Rc});var Km=k(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Wm=Bm();Wm.code='require("ajv/dist/runtime/uri").default';Ic.default=Wm});var og=k(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=void 0;var gS=Lo();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return gS.KeywordCxt}});var Ur=Z();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Ur._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Ur.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Ur.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Ur.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Ur.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return Ur.CodeGen}});var _S=ms(),eg=Uo(),yS=ic(),Vo=_s(),vS=Z(),Ho=Zo(),$s=jo(),Oc=F(),Gm=Nm(),wS=Km(),tg=(t,e)=>new RegExp(t,e);tg.code="new RegExp";var bS=["removeAdditional","useDefaults","coerceTypes"],$S=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),SS={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."},xS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ym=200;function kS(t){var e,r,o,n,s,i,a,c,u,l,d,p,f,h,g,_,w,b,z,E,v,$,O,K,j;let ie=t.strict,dt=(e=t.code)===null||e===void 0?void 0:e.optimize,ae=dt===!0||dt===void 0?1:dt||0,Gt=(o=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&o!==void 0?o:tg,Et=(n=t.uriResolver)!==null&&n!==void 0?n:wS.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ie)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ie)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ie)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:ie)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:ie)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:ae,regExp:Gt}:{optimize:ae,regExp:Gt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Ym,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Ym,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:($=t.validateSchema)!==null&&$!==void 0?$:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(K=t.unicodeRegExp)!==null&&K!==void 0?K:!0,int32range:(j=t.int32range)!==null&&j!==void 0?j:!0,uriResolver:Et}}var Jo=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...kS(e)};let{es5:r,lines:o}=this.opts.code;this.scope=new vS.ValueScope({scope:{},prefixes:$S,es5:r,lines:o}),this.logger=IS(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yS.getRules)(),Xm.call(this,SS,e,"NOT SUPPORTED"),Xm.call(this,xS,e,"DEPRECATED","warn"),this._metaOpts=TS.call(this),e.formats&&PS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ES.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),zS.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:o}=this.opts,n=Gm;o==="id"&&(n={...Gm},n.id=n.$id,delete n.$id),r&&e&&this.addMetaSchema(n,n[o],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let n=o(r);return"$async"in o||(this.errors=o.errors),n}compile(e,r){let o=this._addSchema(e,r);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return n.call(this,e,r);async function n(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await n.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof eg.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=o(l))}finally{delete this._loading[l]}}}addSchema(e,r,o,n=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,o,n);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ho.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,o,r,n,!0),this}addMetaSchema(e,r,o=this.opts.validateSchema){return this.addSchema(e,r,!0,o),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(o,e);if(!n&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return n}getSchema(e){let r;for(;typeof(r=Qm.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:o}=this.opts,n=new Vo.SchemaEnv({schema:{},schemaId:o});if(r=Vo.resolveSchema.call(this,n,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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":{let r=Qm.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let o=e[this.opts.schemaId];return o&&(o=(0,Ho.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let o;if(typeof e=="string")o=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=o);else if(typeof e=="object"&&r===void 0){if(r=e,o=r.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(OS.call(this,o,r),!r)return(0,Oc.eachItem)(o,s=>Cc.call(this,s)),this;NS.call(this,r);let n={...r,type:(0,$s.getJSONTypes)(r.type),schemaType:(0,$s.getJSONTypes)(r.schemaType)};return(0,Oc.eachItem)(o,n.type.length===0?s=>Cc.call(this,s,n):s=>n.type.forEach(i=>Cc.call(this,s,n,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let o of r.rules){let n=o.rules.findIndex(s=>s.keyword===e);n>=0&&o.rules.splice(n,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(n=>`${o}${n.instancePath} ${n.message}`).reduce((n,s)=>n+r+s)}$dataMetaSchema(e,r){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of r){let s=n.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=rg(l))}}return e}_removeAllSchemas(e,r){for(let o in e){let n=e[o];(!r||r.test(o))&&(typeof n=="string"?delete e[o]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[o]))}}_addSchema(e,r,o,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;o=(0,Ho.normalizeId)(i||o);let u=Ho.getSchemaRefs.call(this,e,o);return c=new Vo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:o,localRefs:u}),this._cache.set(c.schema,c),s&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),n&&this.validateSchema(e,!0),c}_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):Vo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Vo.compileSchema.call(this,e)}finally{this.opts=r}}};Jo.ValidationError=_S.default;Jo.MissingRefError=eg.default;be.default=Jo;function Xm(t,e,r,o="error"){for(let n in t){let s=n;s in e&&this.logger[o](`${r}: option ${n}. ${t[s]}`)}}function Qm(t){return t=(0,Ho.normalizeId)(t),this.schemas[t]||this.refs[t]}function zS(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function PS(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function ES(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function TS(){let t={...this.opts};for(let e of bS)delete t[e];return t}var RS={log(){},warn(){},error(){}};function IS(t){if(t===!1)return RS;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var CS=/^[a-z_$][a-z0-9_$:-]*$/i;function OS(t,e){let{RULES:r}=this;if((0,Oc.eachItem)(t,o=>{if(r.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!CS.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Cc(t,e,r){var o;let n=e?.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=n?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,$s.getJSONTypes)(e.type),schemaType:(0,$s.getJSONTypes)(e.schemaType)}};e.before?AS.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(o=e.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function AS(t,e,r){let o=t.rules.findIndex(n=>n.keyword===r);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function NS(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rg(e)),t.validateSchema=this.compile(e,!0))}var MS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rg(t){return{anyOf:[t,MS]}}});var ng=k(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var jS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ac.default=jS});var cg=k(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.callRef=cr.getValidate=void 0;var ZS=Uo(),sg=Be(),je=Z(),Fr=St(),ig=_s(),Ss=F(),DS={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:o}=t,{baseId:n,schemaEnv:s,validateName:i,opts:a,self:c}=o,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=ig.resolveRef.call(c,u,n,r);if(l===void 0)throw new ZS.default(o.opts.uriResolver,n,r);if(l instanceof ig.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return xs(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return xs(t,(0,je._)`${h}.validate`,u,u.$async)}function p(h){let g=ag(t,h);xs(t,g,h,h.$async)}function f(h){let g=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,je.stringify)(h)}:{ref:h}),_=e.name("valid"),w=t.subschema({schema:h,dataTypes:[],schemaPath:je.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(w),t.ok(_)}}};function ag(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,je._)`${r.scopeValue("wrapper",{ref:e})}.validate`}cr.getValidate=ag;function xs(t,e,r,o){let{gen:n,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Fr.default.this:je.nil;o?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=n.let("valid");n.try(()=>{n.code((0,je._)`await ${(0,sg.callValidateCode)(t,e,u)}`),f(e),i||n.assign(h,!0)},g=>{n.if((0,je._)`!(${g} instanceof ${s.ValidationError})`,()=>n.throw(g)),p(g),i||n.assign(h,!1)}),t.ok(h)}function d(){t.result((0,sg.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let g=(0,je._)`${h}.errors`;n.assign(Fr.default.vErrors,(0,je._)`${Fr.default.vErrors} === null ? ${g} : ${Fr.default.vErrors}.concat(${g})`),n.assign(Fr.default.errors,(0,je._)`${Fr.default.vErrors}.length`)}function f(h){var g;if(!s.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(s.props=Ss.mergeEvaluated.props(n,_.props,s.props));else{let w=n.var("props",(0,je._)`${h}.evaluated.props`);s.props=Ss.mergeEvaluated.props(n,w,s.props,je.Name)}if(s.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(s.items=Ss.mergeEvaluated.items(n,_.items,s.items));else{let w=n.var("items",(0,je._)`${h}.evaluated.items`);s.items=Ss.mergeEvaluated.items(n,w,s.items,je.Name)}}}cr.callRef=xs;cr.default=DS});var ug=k(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var qS=ng(),LS=cg(),US=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qS.default,LS.default];Nc.default=US});var lg=k(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var ks=Z(),Jt=ks.operators,zs={maximum:{okStr:"<=",ok:Jt.LTE,fail:Jt.GT},minimum:{okStr:">=",ok:Jt.GTE,fail:Jt.LT},exclusiveMaximum:{okStr:"<",ok:Jt.LT,fail:Jt.GTE},exclusiveMinimum:{okStr:">",ok:Jt.GT,fail:Jt.LTE}},FS={message:({keyword:t,schemaCode:e})=>(0,ks.str)`must be ${zs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ks._)`{comparison: ${zs[t].okStr}, limit: ${e}}`},VS={keyword:Object.keys(zs),type:"number",schemaType:"number",$data:!0,error:FS,code(t){let{keyword:e,data:r,schemaCode:o}=t;t.fail$data((0,ks._)`${r} ${zs[e].fail} ${o} || isNaN(${r})`)}};Mc.default=VS});var dg=k(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Bo=Z(),HS={message:({schemaCode:t})=>(0,Bo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Bo._)`{multipleOf: ${t}}`},JS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:HS,code(t){let{gen:e,data:r,schemaCode:o,it:n}=t,s=n.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Bo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Bo._)`${i} !== parseInt(${i})`;t.fail$data((0,Bo._)`(${o} === 0 || (${i} = ${r}/${o}, ${a}))`)}};jc.default=JS});var fg=k(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});function pg(t){let e=t.length,r=0,o=0,n;for(;o<e;)r++,n=t.charCodeAt(o++),n>=55296&&n<=56319&&o<e&&(n=t.charCodeAt(o),(n&64512)===56320&&o++);return r}Zc.default=pg;pg.code='require("ajv/dist/runtime/ucs2length").default'});var hg=k(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ur=Z(),BS=F(),WS=fg(),KS={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ur.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ur._)`{limit: ${t}}`},GS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:KS,code(t){let{keyword:e,data:r,schemaCode:o,it:n}=t,s=e==="maxLength"?ur.operators.GT:ur.operators.LT,i=n.opts.unicode===!1?(0,ur._)`${r}.length`:(0,ur._)`${(0,BS.useFunc)(t.gen,WS.default)}(${r})`;t.fail$data((0,ur._)`${i} ${s} ${o}`)}};Dc.default=GS});var mg=k(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var YS=Be(),XS=F(),Vr=Z(),QS={message:({schemaCode:t})=>(0,Vr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Vr._)`{pattern: ${t}}`},ex={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:QS,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Vr._)`new RegExp`:(0,XS.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Vr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Vr._)`!${l}`)}else{let c=(0,YS.usePattern)(t,n);t.fail$data((0,Vr._)`!${c}.test(${r})`)}}};qc.default=ex});var gg=k(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var Wo=Z(),tx={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Wo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Wo._)`{limit: ${t}}`},rx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:tx,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxProperties"?Wo.operators.GT:Wo.operators.LT;t.fail$data((0,Wo._)`Object.keys(${r}).length ${n} ${o}`)}};Lc.default=rx});var _g=k(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Ko=Be(),Go=Z(),ox=F(),nx={message:({params:{missingProperty:t}})=>(0,Go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Go._)`{missingProperty: ${t}}`},sx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:nx,code(t){let{gen:e,schema:r,schemaCode:o,data:n,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(f?.[g]===void 0&&!h.has(g)){let _=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,ox.checkStrictMode)(i,w,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Go.nil,d);else for(let f of r)(0,Ko.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Ko.checkMissingProp)(t,r,f)),(0,Ko.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",o,f=>{t.setParams({missingProperty:f}),e.if((0,Ko.noPropertyInData)(e,n,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,o,()=>{e.assign(h,(0,Ko.propertyInData)(e,n,f,a.ownProperties)),e.if((0,Go.not)(h),()=>{t.error(),e.break()})},Go.nil)}}};Uc.default=sx});var yg=k(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Yo=Z(),ix={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Yo._)`{limit: ${t}}`},ax={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ix,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxItems"?Yo.operators.GT:Yo.operators.LT;t.fail$data((0,Yo._)`${r}.length ${n} ${o}`)}};Fc.default=ax});var Ps=k(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var vg=hc();vg.code='require("ajv/dist/runtime/equal").default';Vc.default=vg});var wg=k(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Hc=jo(),$e=Z(),cx=F(),ux=Ps(),lx={message:({params:{i:t,j:e}})=>(0,$e.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,$e._)`{i: ${t}, j: ${e}}`},dx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:lx,code(t){let{gen:e,data:r,$data:o,schema:n,parentSchema:s,schemaCode:i,it:a}=t;if(!o&&!n)return;let c=e.let("valid"),u=s.items?(0,Hc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,$e._)`${i} === false`),t.ok(c);function l(){let h=e.let("i",(0,$e._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(c,!0),e.if((0,$e._)`${h} > 1`,()=>(d()?p:f)(h,g))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let _=e.name("item"),w=(0,Hc.checkDataTypes)(u,_,a.opts.strictNumbers,Hc.DataType.Wrong),b=e.const("indices",(0,$e._)`{}`);e.for((0,$e._)`;${h}--;`,()=>{e.let(_,(0,$e._)`${r}[${h}]`),e.if(w,(0,$e._)`continue`),u.length>1&&e.if((0,$e._)`typeof ${_} == "string"`,(0,$e._)`${_} += "_"`),e.if((0,$e._)`typeof ${b}[${_}] == "number"`,()=>{e.assign(g,(0,$e._)`${b}[${_}]`),t.error(),e.assign(c,!1).break()}).code((0,$e._)`${b}[${_}] = ${h}`)})}function f(h,g){let _=(0,cx.useFunc)(e,ux.default),w=e.name("outer");e.label(w).for((0,$e._)`;${h}--;`,()=>e.for((0,$e._)`${g} = ${h}; ${g}--;`,()=>e.if((0,$e._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(w)})))}}};Jc.default=dx});var bg=k(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Bc=Z(),px=F(),fx=Ps(),hx={message:"must be equal to constant",params:({schemaCode:t})=>(0,Bc._)`{allowedValue: ${t}}`},mx={keyword:"const",$data:!0,error:hx,code(t){let{gen:e,data:r,$data:o,schemaCode:n,schema:s}=t;o||s&&typeof s=="object"?t.fail$data((0,Bc._)`!${(0,px.useFunc)(e,fx.default)}(${r}, ${n})`):t.fail((0,Bc._)`${s} !== ${r}`)}};Wc.default=mx});var $g=k(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Xo=Z(),gx=F(),_x=Ps(),yx={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Xo._)`{allowedValues: ${t}}`},vx={keyword:"enum",schemaType:"array",$data:!0,error:yx,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t;if(!o&&n.length===0)throw new Error("enum must have non-empty array");let a=n.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,gx.useFunc)(e,_x.default)),l;if(a||o)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(n))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Xo.or)(...n.map((h,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Xo._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,h){let g=n[h];return typeof g=="object"&&g!==null?(0,Xo._)`${u()}(${r}, ${f}[${h}])`:(0,Xo._)`${r} === ${g}`}}};Kc.default=vx});var Sg=k(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var wx=lg(),bx=dg(),$x=hg(),Sx=mg(),xx=gg(),kx=_g(),zx=yg(),Px=wg(),Ex=bg(),Tx=$g(),Rx=[wx.default,bx.default,$x.default,Sx.default,xx.default,kx.default,zx.default,Px.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ex.default,Tx.default];Gc.default=Rx});var Xc=k(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.validateAdditionalItems=void 0;var lr=Z(),Yc=F(),Ix={message:({params:{len:t}})=>(0,lr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,lr._)`{limit: ${t}}`},Cx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ix,code(t){let{parentSchema:e,it:r}=t,{items:o}=e;if(!Array.isArray(o)){(0,Yc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xg(t,o)}};function xg(t,e){let{gen:r,schema:o,data:n,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,lr._)`${n}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,lr._)`${a} <= ${e.length}`);else if(typeof o=="object"&&!(0,Yc.alwaysValidSchema)(i,o)){let u=r.var("valid",(0,lr._)`${a} <= ${e.length}`);r.if((0,lr.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Yc.Type.Num},u),i.allErrors||r.if((0,lr.not)(u),()=>r.break())})}}Qo.validateAdditionalItems=xg;Qo.default=Cx});var Qc=k(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.validateTuple=void 0;var kg=Z(),Es=F(),Ox=Be(),Ax={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return zg(t,"additionalItems",e);r.items=!0,!(0,Es.alwaysValidSchema)(r,e)&&t.ok((0,Ox.validateArray)(t))}};function zg(t,e,r=t.schema){let{gen:o,parentSchema:n,data:s,keyword:i,it:a}=t;l(n),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Es.mergeEvaluated.items(o,r.length,a.items));let c=o.name("valid"),u=o.const("len",(0,kg._)`${s}.length`);r.forEach((d,p)=>{(0,Es.alwaysValidSchema)(a,d)||(o.if((0,kg._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let _=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Es.checkStrictMode)(a,_,p.strictTuples)}}}en.validateTuple=zg;en.default=Ax});var Pg=k(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Nx=Qc(),Mx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Nx.validateTuple)(t,"items")};eu.default=Mx});var Tg=k(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var Eg=Z(),jx=F(),Zx=Be(),Dx=Xc(),qx={message:({params:{len:t}})=>(0,Eg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Eg._)`{limit: ${t}}`},Lx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qx,code(t){let{schema:e,parentSchema:r,it:o}=t,{prefixItems:n}=r;o.items=!0,!(0,jx.alwaysValidSchema)(o,e)&&(n?(0,Dx.validateAdditionalItems)(t,n):t.ok((0,Zx.validateArray)(t)))}};tu.default=Lx});var Rg=k(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var Ke=Z(),Ts=F(),Ux={message:({params:{min:t,max:e}})=>e===void 0?(0,Ke.str)`must contain at least ${t} valid item(s)`:(0,Ke.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ke._)`{minContains: ${t}}`:(0,Ke._)`{minContains: ${t}, maxContains: ${e}}`},Fx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Ux,code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t,i,a,{minContains:c,maxContains:u}=o;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Ke._)`${n}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ts.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ts.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ts.alwaysValidSchema)(s,r)){let g=(0,Ke._)`${l} >= ${i}`;a!==void 0&&(g=(0,Ke._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ke._)`${n}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),_=e.let("count",0);f(g,()=>e.if(g,()=>h(_)))}function f(g,_){e.forRange("i",0,l,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:Ts.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,Ke._)`${g}++`),a===void 0?e.if((0,Ke._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ke._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ke._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};ru.default=Fx});var Og=k(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.validateSchemaDeps=ct.validatePropertyDeps=ct.error=void 0;var ou=Z(),Vx=F(),tn=Be();ct.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let o=e===1?"property":"properties";return(0,ou.str)`must have ${o} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:o}})=>(0,ou._)`{property: ${t},
|
|
6
|
+
|| ${i} === "boolean" || ${n} === null`).assign(a,(0,M._)`[${n}]`)}}}function k0({gen:t,parentData:e,parentDataProperty:r},o){t.if((0,M._)`${e} !== undefined`,()=>t.assign((0,M._)`${e}[${r}]`,o))}function cc(t,e,r,o=Zr.Correct){let n=o===Zr.Correct?M.operators.EQ:M.operators.NEQ,s;switch(t){case"null":return(0,M._)`${e} ${n} null`;case"array":s=(0,M._)`Array.isArray(${e})`;break;case"object":s=(0,M._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,M._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,M._)`typeof ${e} ${n} ${t}`}return o===Zr.Correct?s:(0,M.not)(s);function i(a=M.nil){return(0,M.and)((0,M._)`typeof ${e} == "number"`,a,r?(0,M._)`isFinite(${e})`:M.nil)}}ze.checkDataType=cc;function uc(t,e,r,o){if(t.length===1)return cc(t[0],e,r,o);let n,s=(0,tm.toHash)(t);if(s.array&&s.object){let i=(0,M._)`typeof ${e} != "object"`;n=s.null?i:(0,M._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else n=M.nil;s.number&&delete s.integer;for(let i in s)n=(0,M.and)(n,cc(i,e,r,o));return n}ze.checkDataTypes=uc;var z0={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,M._)`{type: ${t}}`:(0,M._)`{type: ${e}}`};function lc(t){let e=P0(t);(0,w0.reportError)(e,z0)}ze.reportTypeError=lc;function P0(t){let{gen:e,data:r,schema:o}=t,n=(0,tm.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:t}}});var sm=k(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.assignDefaults=void 0;var Dr=Z(),E0=F();function T0(t,e){let{properties:r,items:o}=t.schema;if(e==="object"&&r)for(let n in r)nm(t,n,r[n].default);else e==="array"&&Array.isArray(o)&&o.forEach((n,s)=>nm(t,s,n.default))}ds.assignDefaults=T0;function nm(t,e,r){let{gen:o,compositeRule:n,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Dr._)`${s}${(0,Dr.getProperty)(e)}`;if(n){(0,E0.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Dr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Dr._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,Dr._)`${a} = ${(0,Dr.stringify)(r)}`)}});var Be=k(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.validateUnion=Y.validateArray=Y.usePattern=Y.callValidateCode=Y.schemaProperties=Y.allSchemaProperties=Y.noPropertyInData=Y.propertyInData=Y.isOwnProperty=Y.hasPropFunc=Y.reportMissingProp=Y.checkMissingProp=Y.checkReportMissingProp=void 0;var ne=Z(),dc=F(),Ut=St(),R0=F();function I0(t,e){let{gen:r,data:o,it:n}=t;r.if(fc(r,o,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ne._)`${e}`},!0),t.error()})}Y.checkReportMissingProp=I0;function C0({gen:t,data:e,it:{opts:r}},o,n){return(0,ne.or)(...o.map(s=>(0,ne.and)(fc(t,e,s,r.ownProperties),(0,ne._)`${n} = ${s}`)))}Y.checkMissingProp=C0;function O0(t,e){t.setParams({missingProperty:e},!0),t.error()}Y.reportMissingProp=O0;function im(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ne._)`Object.prototype.hasOwnProperty`})}Y.hasPropFunc=im;function pc(t,e,r){return(0,ne._)`${im(t)}.call(${e}, ${r})`}Y.isOwnProperty=pc;function A0(t,e,r,o){let n=(0,ne._)`${e}${(0,ne.getProperty)(r)} !== undefined`;return o?(0,ne._)`${n} && ${pc(t,e,r)}`:n}Y.propertyInData=A0;function fc(t,e,r,o){let n=(0,ne._)`${e}${(0,ne.getProperty)(r)} === undefined`;return o?(0,ne.or)(n,(0,ne.not)(pc(t,e,r))):n}Y.noPropertyInData=fc;function am(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Y.allSchemaProperties=am;function N0(t,e){return am(e).filter(r=>!(0,dc.alwaysValidSchema)(t,e[r]))}Y.schemaProperties=N0;function M0({schemaCode:t,data:e,it:{gen:r,topSchemaRef:o,schemaPath:n,errorPath:s},it:i},a,c,u){let l=u?(0,ne._)`${t}, ${e}, ${o}${n}`:e,d=[[Ut.default.instancePath,(0,ne.strConcat)(Ut.default.instancePath,s)],[Ut.default.parentData,i.parentData],[Ut.default.parentDataProperty,i.parentDataProperty],[Ut.default.rootData,Ut.default.rootData]];i.opts.dynamicRef&&d.push([Ut.default.dynamicAnchors,Ut.default.dynamicAnchors]);let p=(0,ne._)`${l}, ${r.object(...d)}`;return c!==ne.nil?(0,ne._)`${a}.call(${c}, ${p})`:(0,ne._)`${a}(${p})`}Y.callValidateCode=M0;var j0=(0,ne._)`new RegExp`;function Z0({gen:t,it:{opts:e}},r){let o=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,o);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ne._)`${n.code==="new RegExp"?j0:(0,R0.useFunc)(t,n)}(${r}, ${o})`})}Y.usePattern=Z0;function D0(t){let{gen:e,data:r,keyword:o,it:n}=t,s=e.name("valid");if(n.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ne._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:dc.Type.Num},s),e.if((0,ne.not)(s),a)})}}Y.validateArray=D0;function q0(t){let{gen:e,schema:r,keyword:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,dc.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:o,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ne._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ne.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Y.validateUnion=q0});var lm=k(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateKeywordUsage=st.validSchemaType=st.funcKeywordCode=st.macroKeywordCode=void 0;var Re=Z(),ir=St(),L0=Be(),U0=Mo();function F0(t,e){let{gen:r,keyword:o,schema:n,parentSchema:s,it:i}=t,a=e.macro.call(i.self,n,s,i),c=um(r,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Re.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}st.macroKeywordCode=F0;function V0(t,e){var r;let{gen:o,keyword:n,schema:s,parentSchema:i,$data:a,it:c}=t;J0(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=um(o,n,u),d=o.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&cm(t),_(()=>t.error());else{let w=e.async?f():h();e.modifying&&cm(t),_(()=>H0(t,w))}}function f(){let w=o.let("ruleErrs",null);return o.try(()=>g((0,Re._)`await `),b=>o.assign(d,!1).if((0,Re._)`${b} instanceof ${c.ValidationError}`,()=>o.assign(w,(0,Re._)`${b}.errors`),()=>o.throw(b))),w}function h(){let w=(0,Re._)`${l}.errors`;return o.assign(w,null),g(Re.nil),w}function g(w=e.async?(0,Re._)`await `:Re.nil){let b=c.opts.passContext?ir.default.this:ir.default.self,z=!("compile"in e&&!a||e.schema===!1);o.assign(d,(0,Re._)`${w}${(0,L0.callValidateCode)(t,l,b,z)}`,e.modifying)}function _(w){var b;o.if((0,Re.not)((b=e.valid)!==null&&b!==void 0?b:d),w)}}st.funcKeywordCode=V0;function cm(t){let{gen:e,data:r,it:o}=t;e.if(o.parentData,()=>e.assign(r,(0,Re._)`${o.parentData}[${o.parentDataProperty}]`))}function H0(t,e){let{gen:r}=t;r.if((0,Re._)`Array.isArray(${e})`,()=>{r.assign(ir.default.vErrors,(0,Re._)`${ir.default.vErrors} === null ? ${e} : ${ir.default.vErrors}.concat(${e})`).assign(ir.default.errors,(0,Re._)`${ir.default.vErrors}.length`),(0,U0.extendErrors)(t)},()=>t.error())}function J0({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function um(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Re.stringify)(r)})}function B0(t,e,r=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||r&&typeof t>"u")}st.validSchemaType=B0;function W0({schema:t,opts:e,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");let i=n.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}st.validateKeywordUsage=W0});var pm=k(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.extendSubschemaMode=Ft.extendSubschemaData=Ft.getSubschema=void 0;var it=Z(),dm=F();function K0(t,{keyword:e,schemaProp:r,schema:o,schemaPath:n,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,it._)`${t.schemaPath}${(0,it.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,it._)`${t.schemaPath}${(0,it.getProperty)(e)}${(0,it.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,dm.escapeFragment)(r)}`}}if(o!==void 0){if(n===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:n,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ft.getSubschema=K0;function G0(t,e,{dataProp:r,dataPropType:o,data:n,dataTypes:s,propertyName:i}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,it._)`${e.data}${(0,it.getProperty)(r)}`,!0);c(p),t.errorPath=(0,it.str)`${u}${(0,dm.getErrorPath)(r,o,d.jsPropertySyntax)}`,t.parentDataProperty=(0,it._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(n!==void 0){let u=n instanceof it.Name?n:a.let("data",n,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Ft.extendSubschemaData=G0;function Y0(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){o!==void 0&&(t.compositeRule=o),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Ft.extendSubschemaMode=Y0});var hc=k((rA,fm)=>{"use strict";fm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var mm=k((oA,hm)=>{"use strict";var Vt=hm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var o=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};ps(e,o,n,t,"",t)};Vt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vt.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};function ps(t,e,r,o,n,s,i,a,c,u){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,n,s,i,a,c,u);for(var l in o){var d=o[l];if(Array.isArray(d)){if(l in Vt.arrayKeywords)for(var p=0;p<d.length;p++)ps(t,e,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Vt.propsKeywords){if(d&&typeof d=="object")for(var f in d)ps(t,e,r,d[f],n+"/"+l+"/"+X0(f),s,n,l,o,f)}else(l in Vt.keywords||t.allKeys&&!(l in Vt.skipKeywords))&&ps(t,e,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,i,a,c,u)}}function X0(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zo=k(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var Q0=F(),e$=hc(),t$=mm(),r$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!mc(t):e?gm(t)<=e:!1}Me.inlineRef=o$;var n$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mc(t){for(let e in t){if(n$.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(mc)||typeof r=="object"&&mc(r))return!0}return!1}function gm(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!r$.has(r)&&(typeof t[r]=="object"&&(0,Q0.eachItem)(t[r],o=>e+=gm(o)),e===1/0))return 1/0}return e}function _m(t,e="",r){r!==!1&&(e=qr(e));let o=t.parse(e);return ym(t,o)}Me.getFullPath=_m;function ym(t,e){return t.serialize(e).split("#")[0]+"#"}Me._getFullPath=ym;var s$=/#\/?$/;function qr(t){return t?t.replace(s$,""):""}Me.normalizeId=qr;function i$(t,e,r){return r=qr(r),t.resolve(e,r)}Me.resolveUrl=i$;var a$=/^[a-z_][-a-z0-9._]*$/i;function c$(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:o}=this.opts,n=qr(t[r]||e),s={"":n},i=_m(o,n,!1),a={},c=new Set;return t$(t,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let g=i+p,_=s[h];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[p]=_;function w(z){let E=this.opts.uriResolver.resolve;if(z=qr(_?E(_,z):z),c.has(z))throw l(z);c.add(z);let v=this.refs[z];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,z):z!==qr(g)&&(z[0]==="#"?(u(d,a[z],z),a[z]=d):this.refs[z]=g),z}function b(z){if(typeof z=="string"){if(!a$.test(z))throw new Error(`invalid anchor "${z}"`);w.call(this,`#${z}`)}}}),a;function u(d,p,f){if(p!==void 0&&!e$(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Me.getSchemaRefs=c$});var Lo=k(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.getData=Ht.KeywordCxt=Ht.validateFunctionCode=void 0;var Sm=Xh(),vm=jo(),_c=ac(),fs=jo(),u$=sm(),qo=lm(),gc=pm(),R=Z(),A=St(),l$=Zo(),xt=F(),Do=Mo();function d$(t){if(zm(t)&&(Pm(t),km(t))){h$(t);return}xm(t,()=>(0,Sm.topBoolOrEmptySchema)(t))}Ht.validateFunctionCode=d$;function xm({gen:t,validateName:e,schema:r,schemaEnv:o,opts:n},s){n.code.es5?t.func(e,(0,R._)`${A.default.data}, ${A.default.valCxt}`,o.$async,()=>{t.code((0,R._)`"use strict"; ${wm(r,n)}`),f$(t,n),t.code(s)}):t.func(e,(0,R._)`${A.default.data}, ${p$(n)}`,o.$async,()=>t.code(wm(r,n)).code(s))}function p$(t){return(0,R._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${t.dynamicRef?(0,R._)`, ${A.default.dynamicAnchors}={}`:R.nil}}={}`}function f$(t,e){t.if(A.default.valCxt,()=>{t.var(A.default.instancePath,(0,R._)`${A.default.valCxt}.${A.default.instancePath}`),t.var(A.default.parentData,(0,R._)`${A.default.valCxt}.${A.default.parentData}`),t.var(A.default.parentDataProperty,(0,R._)`${A.default.valCxt}.${A.default.parentDataProperty}`),t.var(A.default.rootData,(0,R._)`${A.default.valCxt}.${A.default.rootData}`),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,R._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{t.var(A.default.instancePath,(0,R._)`""`),t.var(A.default.parentData,(0,R._)`undefined`),t.var(A.default.parentDataProperty,(0,R._)`undefined`),t.var(A.default.rootData,A.default.data),e.dynamicRef&&t.var(A.default.dynamicAnchors,(0,R._)`{}`)})}function h$(t){let{schema:e,opts:r,gen:o}=t;xm(t,()=>{r.$comment&&e.$comment&&Tm(t),v$(t),o.let(A.default.vErrors,null),o.let(A.default.errors,0),r.unevaluated&&m$(t),Em(t),$$(t)})}function m$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,R._)`${r}.evaluated`),e.if((0,R._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,R._)`${t.evaluated}.props`,(0,R._)`undefined`)),e.if((0,R._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,R._)`${t.evaluated}.items`,(0,R._)`undefined`))}function wm(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,R._)`/*# sourceURL=${r} */`:R.nil}function g$(t,e){if(zm(t)&&(Pm(t),km(t))){_$(t,e);return}(0,Sm.boolOrEmptySchema)(t,e)}function km({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function zm(t){return typeof t.schema!="boolean"}function _$(t,e){let{schema:r,gen:o,opts:n}=t;n.$comment&&r.$comment&&Tm(t),w$(t),b$(t);let s=o.const("_errs",A.default.errors);Em(t,s),o.var(e,(0,R._)`${s} === ${A.default.errors}`)}function Pm(t){(0,xt.checkUnknownRules)(t),y$(t)}function Em(t,e){if(t.opts.jtd)return bm(t,[],!1,e);let r=(0,vm.getSchemaTypes)(t.schema),o=(0,vm.coerceAndCheckDataType)(t,r);bm(t,r,!o,e)}function y$(t){let{schema:e,errSchemaPath:r,opts:o,self:n}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,xt.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function v$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,xt.checkStrictMode)(t,"default is ignored in the schema root")}function w$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,l$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function b$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Tm({gen:t,schemaEnv:e,schema:r,errSchemaPath:o,opts:n}){let s=r.$comment;if(n.$comment===!0)t.code((0,R._)`${A.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let i=(0,R.str)`${o}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,R._)`${A.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function $$(t){let{gen:e,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=t;r.$async?e.if((0,R._)`${A.default.errors} === 0`,()=>e.return(A.default.data),()=>e.throw((0,R._)`new ${n}(${A.default.vErrors})`)):(e.assign((0,R._)`${o}.errors`,A.default.vErrors),s.unevaluated&&S$(t),e.return((0,R._)`${A.default.errors} === 0`))}function S$({gen:t,evaluated:e,props:r,items:o}){r instanceof R.Name&&t.assign((0,R._)`${e}.props`,r),o instanceof R.Name&&t.assign((0,R._)`${e}.items`,o)}function bm(t,e,r,o){let{gen:n,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,xt.schemaHasRulesButRef)(s,l))){n.block(()=>Im(t,"$ref",l.all.$ref.definition));return}c.jtd||x$(t,e),n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,_c.shouldUseGroup)(s,p)&&(p.type?(n.if((0,fs.checkDataType)(p.type,i,c.strictNumbers)),$m(t,p),e.length===1&&e[0]===p.type&&r&&(n.else(),(0,fs.reportTypeError)(t)),n.endIf()):$m(t,p),a||n.if((0,R._)`${A.default.errors} === ${o||0}`))}}function $m(t,e){let{gen:r,schema:o,opts:{useDefaults:n}}=t;n&&(0,u$.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,_c.shouldUseRule)(o,s)&&Im(t,s.keyword,s.definition,e.type)})}function x$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(k$(t,e),t.opts.allowUnionTypes||z$(t,e),P$(t,t.dataTypes))}function k$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Rm(t.dataTypes,r)||yc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),T$(t,e)}}function z$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yc(t,"use allowUnionTypes to allow union type keyword")}function P$(t,e){let r=t.self.RULES.all;for(let o in r){let n=r[o];if(typeof n=="object"&&(0,_c.shouldUseRule)(t.schema,n)){let{type:s}=n.definition;s.length&&!s.some(i=>E$(e,i))&&yc(t,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function E$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Rm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function T$(t,e){let r=[];for(let o of t.dataTypes)Rm(e,o)?r.push(o):e.includes("integer")&&o==="number"&&r.push("integer");t.dataTypes=r}function yc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,xt.checkStrictMode)(t,e,t.opts.strictTypes)}var hs=class{constructor(e,r,o){if((0,qo.validateKeywordUsage)(e,r,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,xt.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Cm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,qo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",A.default.errors))}result(e,r,o){this.failResult((0,R.not)(e),r,o)}failResult(e,r,o){this.gen.if(e),o?o():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,R.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,R._)`${r} !== undefined && (${(0,R.or)(this.invalid$data(),e)})`)}error(e,r,o){if(r){this.setParams(r),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,r){(e?Do.reportExtraError:Do.reportError)(this,this.def.error,r)}$dataError(){(0,Do.reportError)(this,this.def.$dataError||Do.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Do.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,o=R.nil){this.gen.block(()=>{this.check$data(e,o),r()})}check$data(e=R.nil,r=R.nil){if(!this.$data)return;let{gen:o,schemaCode:n,schemaType:s,def:i}=this;o.if((0,R.or)((0,R._)`${n} === undefined`,r)),e!==R.nil&&o.assign(e,!0),(s.length||i.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==R.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:o,def:n,it:s}=this;return(0,R.or)(i(),a());function i(){if(o.length){if(!(r instanceof R.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,R._)`${(0,fs.checkDataTypes)(c,r,s.opts.strictNumbers,fs.DataType.Wrong)}`}return R.nil}function a(){if(n.validateSchema){let c=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,R._)`!${c}(${r})`}return R.nil}}subschema(e,r){let o=(0,gc.getSubschema)(this.it,e);(0,gc.extendSubschemaData)(o,this.it,e),(0,gc.extendSubschemaMode)(o,e);let n={...this.it,...o,items:void 0,props:void 0};return g$(n,r),n}mergeEvaluated(e,r){let{it:o,gen:n}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=xt.mergeEvaluated.props(n,e.props,o.props,r)),o.items!==!0&&e.items!==void 0&&(o.items=xt.mergeEvaluated.items(n,e.items,o.items,r)))}mergeValidEvaluated(e,r){let{it:o,gen:n}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,R.Name)),!0}};Ht.KeywordCxt=hs;function Im(t,e,r,o){let n=new hs(t,r,e);"code"in r?r.code(n,o):n.$data&&r.validate?(0,qo.funcKeywordCode)(n,r):"macro"in r?(0,qo.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,qo.funcKeywordCode)(n,r)}var R$=/^\/(?:[^~]|~0|~1)*$/,I$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Cm(t,{dataLevel:e,dataNames:r,dataPathArr:o}){let n,s;if(t==="")return A.default.rootData;if(t[0]==="/"){if(!R$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=A.default.rootData}else{let u=I$.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=e)throw new Error(c("property/index",l));return o[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!n)return s}let i=s,a=n.split("/");for(let u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,xt.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Ht.getData=Cm});var ms=k(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var vc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};wc.default=vc});var Uo=k(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var bc=Zo(),$c=class extends Error{constructor(e,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,bc.resolveUrl)(e,r,o),this.missingSchema=(0,bc.normalizeId)((0,bc.getFullPath)(e,this.missingRef))}};Sc.default=$c});var _s=k(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.resolveSchema=We.getCompilingSchema=We.resolveRef=We.compileSchema=We.SchemaEnv=void 0;var Qe=Z(),C$=ms(),ar=St(),et=Zo(),Om=F(),O$=Lo(),Lr=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,et.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};We.SchemaEnv=Lr;function kc(t){let e=Am.call(this,t);if(e)return e;let r=(0,et.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,i=new Qe.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:C$.default,code:(0,Qe._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ar.default.data,parentData:ar.default.parentData,parentDataProperty:ar.default.parentDataProperty,dataNames:[ar.default.data],dataPathArr:[Qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Qe.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Qe.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qe._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,O$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ar.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ar.default.self}`,`${ar.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;f.evaluated={props:h instanceof Qe.Name?void 0:h,items:g instanceof Qe.Name?void 0:g,dynamicProps:h instanceof Qe.Name,dynamicItems:g instanceof Qe.Name},f.source&&(f.source.evaluated=(0,Qe.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}We.compileSchema=kc;function A$(t,e,r){var o;r=(0,et.resolveUrl)(this.opts.uriResolver,e,r);let n=t.refs[r];if(n)return n;let s=j$.call(this,t,r);if(s===void 0){let i=(o=t.localRefs)===null||o===void 0?void 0:o[r],{schemaId:a}=this.opts;i&&(s=new Lr({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=N$.call(this,s)}We.resolveRef=A$;function N$(t){return(0,et.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:kc.call(this,t)}function Am(t){for(let e of this._compilations)if(M$(e,t))return e}We.getCompilingSchema=Am;function M$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function j$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||gs.call(this,t,e)}function gs(t,e){let r=this.opts.uriResolver.parse(e),o=(0,et._getFullPath)(this.opts.uriResolver,r),n=(0,et.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===n)return xc.call(this,r,t);let s=(0,et.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=gs.call(this,t,i);return typeof a?.schema!="object"?void 0:xc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||kc.call(this,i),s===(0,et.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(n=(0,et.resolveUrl)(this.opts.uriResolver,n,u)),new Lr({schema:a,schemaId:c,root:t,baseId:n})}return xc.call(this,r,i)}}We.resolveSchema=gs;var Z$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xc(t,{baseId:e,schema:r,root:o}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Om.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Z$.has(a)&&u&&(e=(0,et.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Om.schemaHasRulesButRef)(r,this.RULES)){let a=(0,et.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=gs.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new Lr({schema:r,schemaId:i,root:o,baseId:e}),s.schema!==s.root.schema)return s}});var Nm=k((uA,D$)=>{D$.exports={$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:!1}});var Pc=k((lA,Dm)=>{"use strict";var q$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jm=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 zc(t){let e="",r=0,o=0;for(o=0;o<t.length;o++)if(r=t[o].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o];break}for(o+=1;o<t.length;o++){if(r=t[o].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o]}return e}var L$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mm(t){return t.length=0,!0}function U$(t,e,r){if(t.length){let o=zc(t);if(o!=="")e.push(o);else return r.error=!0,!1;t.length=0}return!0}function F$(t){let e=0,r={error:!1,address:"",zone:""},o=[],n=[],s=!1,i=!1,a=U$;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(n,o,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),o.push(":");continue}else if(u==="%"){if(!a(n,o,r))break;a=Mm}else{n.push(u);continue}}return n.length&&(a===Mm?r.zone=n.join(""):i?o.push(n.join("")):o.push(zc(n))),r.address=o.join(""),r}function Zm(t){if(V$(t,":")<2)return{host:t,isIPV6:!1};let e=F$(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,o=e.address;return e.zone&&(r+="%"+e.zone,o+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:o}}}function V$(t,e){let r=0;for(let o=0;o<t.length;o++)t[o]===e&&r++;return r}function H$(t){let e=t,r=[],o=-1,n=0;for(;n=e.length;){if(n===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(n===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(n===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((o=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,o)),e=e.slice(o)}return r.join("")}function J$(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function B$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!jm(r)){let o=Zm(r);o.isIPV6===!0?r=`[${o.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Dm.exports={nonSimpleDomain:L$,recomposeAuthority:B$,normalizeComponentEncoding:J$,removeDotSegments:H$,isIPv4:jm,isUUID:q$,normalizeIPv6:Zm,stringArrayToHexStripped:zc}});var Vm=k((dA,Fm)=>{"use strict";var{isUUID:W$}=Pc(),K$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,G$=["http","https","ws","wss","urn","urn:uuid"];function Y$(t){return G$.indexOf(t)!==-1}function Ec(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function qm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Lm(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function X$(t){return t.secure=Ec(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Q$(t){if((t.port===(Ec(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function eS(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(K$);if(r){let o=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let n=`${o}:${e.nid||t.nid}`,s=Tc(n);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function tS(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),n=`${r}:${e.nid||o}`,s=Tc(n);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${o||e.nid}:${a}`,e.skipEscape=!0,i}function rS(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!W$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function oS(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Um={scheme:"http",domainHost:!0,parse:qm,serialize:Lm},nS={scheme:"https",domainHost:Um.domainHost,parse:qm,serialize:Lm},ys={scheme:"ws",domainHost:!0,parse:X$,serialize:Q$},sS={scheme:"wss",domainHost:ys.domainHost,parse:ys.parse,serialize:ys.serialize},iS={scheme:"urn",parse:eS,serialize:tS,skipNormalize:!0},aS={scheme:"urn:uuid",parse:rS,serialize:oS,skipNormalize:!0},vs={http:Um,https:nS,ws:ys,wss:sS,urn:iS,"urn:uuid":aS};Object.setPrototypeOf(vs,null);function Tc(t){return t&&(vs[t]||vs[t.toLowerCase()])||void 0}Fm.exports={wsIsSecure:Ec,SCHEMES:vs,isValidSchemeName:Y$,getSchemeHandler:Tc}});var Bm=k((pA,bs)=>{"use strict";var{normalizeIPv6:cS,removeDotSegments:Fo,recomposeAuthority:uS,normalizeComponentEncoding:ws,isIPv4:lS,nonSimpleDomain:dS}=Pc(),{SCHEMES:pS,getSchemeHandler:Hm}=Vm();function fS(t,e){return typeof t=="string"?t=at(kt(t,e),e):typeof t=="object"&&(t=kt(at(t,e),e)),t}function hS(t,e,r){let o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Jm(kt(t,o),kt(e,o),o,!0);return o.skipEscape=!0,at(n,o)}function Jm(t,e,r,o){let n={};return o||(t=kt(at(t,r),r),e=kt(at(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Fo(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Fo(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=Fo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=Fo(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function mS(t,e,r){return typeof t=="string"?(t=unescape(t),t=at(ws(kt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=at(ws(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=at(ws(kt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=at(ws(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function at(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),n=[],s=Hm(o.scheme||r.scheme);s&&s.serialize&&s.serialize(r,o),r.path!==void 0&&(o.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),o.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");let i=uS(r);if(i!==void 0&&(o.reference!=="suffix"&&n.push("//"),n.push(i),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let a=r.path;!o.absolutePath&&(!s||!s.absolutePath)&&(a=Fo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),n.push(a)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}var gS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kt(t,e){let r=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(gS);if(s){if(o.scheme=s[1],o.userinfo=s[3],o.host=s[4],o.port=parseInt(s[5],10),o.path=s[6]||"",o.query=s[7],o.fragment=s[8],isNaN(o.port)&&(o.port=s[5]),o.host)if(lS(o.host)===!1){let c=cS(o.host);o.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");let i=Hm(r.scheme||o.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&o.host&&(r.domainHost||i&&i.domainHost)&&n===!1&&dS(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(a){o.error=o.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=unescape(o.host))),o.path&&(o.path=escape(unescape(o.path))),o.fragment&&(o.fragment=encodeURI(decodeURIComponent(o.fragment)))),i&&i.parse&&i.parse(o,r)}else o.error=o.error||"URI can not be parsed.";return o}var Rc={SCHEMES:pS,normalize:fS,resolve:hS,resolveComponent:Jm,equal:mS,serialize:at,parse:kt};bs.exports=Rc;bs.exports.default=Rc;bs.exports.fastUri=Rc});var Km=k(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Wm=Bm();Wm.code='require("ajv/dist/runtime/uri").default';Ic.default=Wm});var og=k(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=void 0;var _S=Lo();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return _S.KeywordCxt}});var Ur=Z();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Ur._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Ur.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Ur.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Ur.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Ur.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return Ur.CodeGen}});var yS=ms(),eg=Uo(),vS=ic(),Vo=_s(),wS=Z(),Ho=Zo(),$s=jo(),Oc=F(),Gm=Nm(),bS=Km(),tg=(t,e)=>new RegExp(t,e);tg.code="new RegExp";var $S=["removeAdditional","useDefaults","coerceTypes"],SS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xS={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."},kS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ym=200;function zS(t){var e,r,o,n,s,i,a,c,u,l,d,p,f,h,g,_,w,b,z,E,v,$,O,K,j;let ie=t.strict,dt=(e=t.code)===null||e===void 0?void 0:e.optimize,ae=dt===!0||dt===void 0?1:dt||0,Gt=(o=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&o!==void 0?o:tg,Et=(n=t.uriResolver)!==null&&n!==void 0?n:bS.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ie)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ie)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ie)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:ie)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:ie)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:ae,regExp:Gt}:{optimize:ae,regExp:Gt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Ym,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Ym,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:($=t.validateSchema)!==null&&$!==void 0?$:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(K=t.unicodeRegExp)!==null&&K!==void 0?K:!0,int32range:(j=t.int32range)!==null&&j!==void 0?j:!0,uriResolver:Et}}var Jo=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...zS(e)};let{es5:r,lines:o}=this.opts.code;this.scope=new wS.ValueScope({scope:{},prefixes:SS,es5:r,lines:o}),this.logger=CS(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,vS.getRules)(),Xm.call(this,xS,e,"NOT SUPPORTED"),Xm.call(this,kS,e,"DEPRECATED","warn"),this._metaOpts=RS.call(this),e.formats&&ES.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&TS.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),PS.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:o}=this.opts,n=Gm;o==="id"&&(n={...Gm},n.id=n.$id,delete n.$id),r&&e&&this.addMetaSchema(n,n[o],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let n=o(r);return"$async"in o||(this.errors=o.errors),n}compile(e,r){let o=this._addSchema(e,r);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return n.call(this,e,r);async function n(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await n.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof eg.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=o(l))}finally{delete this._loading[l]}}}addSchema(e,r,o,n=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,o,n);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ho.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,o,r,n,!0),this}addMetaSchema(e,r,o=this.opts.validateSchema){return this.addSchema(e,r,!0,o),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(o,e);if(!n&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return n}getSchema(e){let r;for(;typeof(r=Qm.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:o}=this.opts,n=new Vo.SchemaEnv({schema:{},schemaId:o});if(r=Vo.resolveSchema.call(this,n,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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":{let r=Qm.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let o=e[this.opts.schemaId];return o&&(o=(0,Ho.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let o;if(typeof e=="string")o=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=o);else if(typeof e=="object"&&r===void 0){if(r=e,o=r.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(AS.call(this,o,r),!r)return(0,Oc.eachItem)(o,s=>Cc.call(this,s)),this;MS.call(this,r);let n={...r,type:(0,$s.getJSONTypes)(r.type),schemaType:(0,$s.getJSONTypes)(r.schemaType)};return(0,Oc.eachItem)(o,n.type.length===0?s=>Cc.call(this,s,n):s=>n.type.forEach(i=>Cc.call(this,s,n,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let o of r.rules){let n=o.rules.findIndex(s=>s.keyword===e);n>=0&&o.rules.splice(n,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(n=>`${o}${n.instancePath} ${n.message}`).reduce((n,s)=>n+r+s)}$dataMetaSchema(e,r){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of r){let s=n.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=rg(l))}}return e}_removeAllSchemas(e,r){for(let o in e){let n=e[o];(!r||r.test(o))&&(typeof n=="string"?delete e[o]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[o]))}}_addSchema(e,r,o,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;o=(0,Ho.normalizeId)(i||o);let u=Ho.getSchemaRefs.call(this,e,o);return c=new Vo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:o,localRefs:u}),this._cache.set(c.schema,c),s&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),n&&this.validateSchema(e,!0),c}_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):Vo.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Vo.compileSchema.call(this,e)}finally{this.opts=r}}};Jo.ValidationError=yS.default;Jo.MissingRefError=eg.default;be.default=Jo;function Xm(t,e,r,o="error"){for(let n in t){let s=n;s in e&&this.logger[o](`${r}: option ${n}. ${t[s]}`)}}function Qm(t){return t=(0,Ho.normalizeId)(t),this.schemas[t]||this.refs[t]}function PS(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function ES(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function TS(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function RS(){let t={...this.opts};for(let e of $S)delete t[e];return t}var IS={log(){},warn(){},error(){}};function CS(t){if(t===!1)return IS;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var OS=/^[a-z_$][a-z0-9_$:-]*$/i;function AS(t,e){let{RULES:r}=this;if((0,Oc.eachItem)(t,o=>{if(r.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!OS.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Cc(t,e,r){var o;let n=e?.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=n?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,$s.getJSONTypes)(e.type),schemaType:(0,$s.getJSONTypes)(e.schemaType)}};e.before?NS.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(o=e.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function NS(t,e,r){let o=t.rules.findIndex(n=>n.keyword===r);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function MS(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rg(e)),t.validateSchema=this.compile(e,!0))}var jS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rg(t){return{anyOf:[t,jS]}}});var ng=k(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var ZS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ac.default=ZS});var cg=k(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.callRef=cr.getValidate=void 0;var DS=Uo(),sg=Be(),je=Z(),Fr=St(),ig=_s(),Ss=F(),qS={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:o}=t,{baseId:n,schemaEnv:s,validateName:i,opts:a,self:c}=o,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=ig.resolveRef.call(c,u,n,r);if(l===void 0)throw new DS.default(o.opts.uriResolver,n,r);if(l instanceof ig.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return xs(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return xs(t,(0,je._)`${h}.validate`,u,u.$async)}function p(h){let g=ag(t,h);xs(t,g,h,h.$async)}function f(h){let g=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,je.stringify)(h)}:{ref:h}),_=e.name("valid"),w=t.subschema({schema:h,dataTypes:[],schemaPath:je.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(w),t.ok(_)}}};function ag(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,je._)`${r.scopeValue("wrapper",{ref:e})}.validate`}cr.getValidate=ag;function xs(t,e,r,o){let{gen:n,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Fr.default.this:je.nil;o?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=n.let("valid");n.try(()=>{n.code((0,je._)`await ${(0,sg.callValidateCode)(t,e,u)}`),f(e),i||n.assign(h,!0)},g=>{n.if((0,je._)`!(${g} instanceof ${s.ValidationError})`,()=>n.throw(g)),p(g),i||n.assign(h,!1)}),t.ok(h)}function d(){t.result((0,sg.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let g=(0,je._)`${h}.errors`;n.assign(Fr.default.vErrors,(0,je._)`${Fr.default.vErrors} === null ? ${g} : ${Fr.default.vErrors}.concat(${g})`),n.assign(Fr.default.errors,(0,je._)`${Fr.default.vErrors}.length`)}function f(h){var g;if(!s.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(s.props=Ss.mergeEvaluated.props(n,_.props,s.props));else{let w=n.var("props",(0,je._)`${h}.evaluated.props`);s.props=Ss.mergeEvaluated.props(n,w,s.props,je.Name)}if(s.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(s.items=Ss.mergeEvaluated.items(n,_.items,s.items));else{let w=n.var("items",(0,je._)`${h}.evaluated.items`);s.items=Ss.mergeEvaluated.items(n,w,s.items,je.Name)}}}cr.callRef=xs;cr.default=qS});var ug=k(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var LS=ng(),US=cg(),FS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",LS.default,US.default];Nc.default=FS});var lg=k(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var ks=Z(),Jt=ks.operators,zs={maximum:{okStr:"<=",ok:Jt.LTE,fail:Jt.GT},minimum:{okStr:">=",ok:Jt.GTE,fail:Jt.LT},exclusiveMaximum:{okStr:"<",ok:Jt.LT,fail:Jt.GTE},exclusiveMinimum:{okStr:">",ok:Jt.GT,fail:Jt.LTE}},VS={message:({keyword:t,schemaCode:e})=>(0,ks.str)`must be ${zs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ks._)`{comparison: ${zs[t].okStr}, limit: ${e}}`},HS={keyword:Object.keys(zs),type:"number",schemaType:"number",$data:!0,error:VS,code(t){let{keyword:e,data:r,schemaCode:o}=t;t.fail$data((0,ks._)`${r} ${zs[e].fail} ${o} || isNaN(${r})`)}};Mc.default=HS});var dg=k(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Bo=Z(),JS={message:({schemaCode:t})=>(0,Bo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Bo._)`{multipleOf: ${t}}`},BS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JS,code(t){let{gen:e,data:r,schemaCode:o,it:n}=t,s=n.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Bo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Bo._)`${i} !== parseInt(${i})`;t.fail$data((0,Bo._)`(${o} === 0 || (${i} = ${r}/${o}, ${a}))`)}};jc.default=BS});var fg=k(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});function pg(t){let e=t.length,r=0,o=0,n;for(;o<e;)r++,n=t.charCodeAt(o++),n>=55296&&n<=56319&&o<e&&(n=t.charCodeAt(o),(n&64512)===56320&&o++);return r}Zc.default=pg;pg.code='require("ajv/dist/runtime/ucs2length").default'});var hg=k(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ur=Z(),WS=F(),KS=fg(),GS={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ur.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ur._)`{limit: ${t}}`},YS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:GS,code(t){let{keyword:e,data:r,schemaCode:o,it:n}=t,s=e==="maxLength"?ur.operators.GT:ur.operators.LT,i=n.opts.unicode===!1?(0,ur._)`${r}.length`:(0,ur._)`${(0,WS.useFunc)(t.gen,KS.default)}(${r})`;t.fail$data((0,ur._)`${i} ${s} ${o}`)}};Dc.default=YS});var mg=k(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var XS=Be(),QS=F(),Vr=Z(),ex={message:({schemaCode:t})=>(0,Vr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Vr._)`{pattern: ${t}}`},tx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ex,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Vr._)`new RegExp`:(0,QS.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Vr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Vr._)`!${l}`)}else{let c=(0,XS.usePattern)(t,n);t.fail$data((0,Vr._)`!${c}.test(${r})`)}}};qc.default=tx});var gg=k(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var Wo=Z(),rx={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Wo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Wo._)`{limit: ${t}}`},ox={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:rx,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxProperties"?Wo.operators.GT:Wo.operators.LT;t.fail$data((0,Wo._)`Object.keys(${r}).length ${n} ${o}`)}};Lc.default=ox});var _g=k(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Ko=Be(),Go=Z(),nx=F(),sx={message:({params:{missingProperty:t}})=>(0,Go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Go._)`{missingProperty: ${t}}`},ix={keyword:"required",type:"object",schemaType:"array",$data:!0,error:sx,code(t){let{gen:e,schema:r,schemaCode:o,data:n,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(f?.[g]===void 0&&!h.has(g)){let _=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,nx.checkStrictMode)(i,w,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Go.nil,d);else for(let f of r)(0,Ko.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Ko.checkMissingProp)(t,r,f)),(0,Ko.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",o,f=>{t.setParams({missingProperty:f}),e.if((0,Ko.noPropertyInData)(e,n,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,o,()=>{e.assign(h,(0,Ko.propertyInData)(e,n,f,a.ownProperties)),e.if((0,Go.not)(h),()=>{t.error(),e.break()})},Go.nil)}}};Uc.default=ix});var yg=k(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Yo=Z(),ax={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Yo._)`{limit: ${t}}`},cx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ax,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxItems"?Yo.operators.GT:Yo.operators.LT;t.fail$data((0,Yo._)`${r}.length ${n} ${o}`)}};Fc.default=cx});var Ps=k(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var vg=hc();vg.code='require("ajv/dist/runtime/equal").default';Vc.default=vg});var wg=k(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Hc=jo(),$e=Z(),ux=F(),lx=Ps(),dx={message:({params:{i:t,j:e}})=>(0,$e.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,$e._)`{i: ${t}, j: ${e}}`},px={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:dx,code(t){let{gen:e,data:r,$data:o,schema:n,parentSchema:s,schemaCode:i,it:a}=t;if(!o&&!n)return;let c=e.let("valid"),u=s.items?(0,Hc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,$e._)`${i} === false`),t.ok(c);function l(){let h=e.let("i",(0,$e._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(c,!0),e.if((0,$e._)`${h} > 1`,()=>(d()?p:f)(h,g))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let _=e.name("item"),w=(0,Hc.checkDataTypes)(u,_,a.opts.strictNumbers,Hc.DataType.Wrong),b=e.const("indices",(0,$e._)`{}`);e.for((0,$e._)`;${h}--;`,()=>{e.let(_,(0,$e._)`${r}[${h}]`),e.if(w,(0,$e._)`continue`),u.length>1&&e.if((0,$e._)`typeof ${_} == "string"`,(0,$e._)`${_} += "_"`),e.if((0,$e._)`typeof ${b}[${_}] == "number"`,()=>{e.assign(g,(0,$e._)`${b}[${_}]`),t.error(),e.assign(c,!1).break()}).code((0,$e._)`${b}[${_}] = ${h}`)})}function f(h,g){let _=(0,ux.useFunc)(e,lx.default),w=e.name("outer");e.label(w).for((0,$e._)`;${h}--;`,()=>e.for((0,$e._)`${g} = ${h}; ${g}--;`,()=>e.if((0,$e._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(w)})))}}};Jc.default=px});var bg=k(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Bc=Z(),fx=F(),hx=Ps(),mx={message:"must be equal to constant",params:({schemaCode:t})=>(0,Bc._)`{allowedValue: ${t}}`},gx={keyword:"const",$data:!0,error:mx,code(t){let{gen:e,data:r,$data:o,schemaCode:n,schema:s}=t;o||s&&typeof s=="object"?t.fail$data((0,Bc._)`!${(0,fx.useFunc)(e,hx.default)}(${r}, ${n})`):t.fail((0,Bc._)`${s} !== ${r}`)}};Wc.default=gx});var $g=k(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Xo=Z(),_x=F(),yx=Ps(),vx={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Xo._)`{allowedValues: ${t}}`},wx={keyword:"enum",schemaType:"array",$data:!0,error:vx,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:s,it:i}=t;if(!o&&n.length===0)throw new Error("enum must have non-empty array");let a=n.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,_x.useFunc)(e,yx.default)),l;if(a||o)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(n))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Xo.or)(...n.map((h,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Xo._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,h){let g=n[h];return typeof g=="object"&&g!==null?(0,Xo._)`${u()}(${r}, ${f}[${h}])`:(0,Xo._)`${r} === ${g}`}}};Kc.default=wx});var Sg=k(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var bx=lg(),$x=dg(),Sx=hg(),xx=mg(),kx=gg(),zx=_g(),Px=yg(),Ex=wg(),Tx=bg(),Rx=$g(),Ix=[bx.default,$x.default,Sx.default,xx.default,kx.default,zx.default,Px.default,Ex.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Tx.default,Rx.default];Gc.default=Ix});var Xc=k(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.validateAdditionalItems=void 0;var lr=Z(),Yc=F(),Cx={message:({params:{len:t}})=>(0,lr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,lr._)`{limit: ${t}}`},Ox={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Cx,code(t){let{parentSchema:e,it:r}=t,{items:o}=e;if(!Array.isArray(o)){(0,Yc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xg(t,o)}};function xg(t,e){let{gen:r,schema:o,data:n,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,lr._)`${n}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,lr._)`${a} <= ${e.length}`);else if(typeof o=="object"&&!(0,Yc.alwaysValidSchema)(i,o)){let u=r.var("valid",(0,lr._)`${a} <= ${e.length}`);r.if((0,lr.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Yc.Type.Num},u),i.allErrors||r.if((0,lr.not)(u),()=>r.break())})}}Qo.validateAdditionalItems=xg;Qo.default=Ox});var Qc=k(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.validateTuple=void 0;var kg=Z(),Es=F(),Ax=Be(),Nx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return zg(t,"additionalItems",e);r.items=!0,!(0,Es.alwaysValidSchema)(r,e)&&t.ok((0,Ax.validateArray)(t))}};function zg(t,e,r=t.schema){let{gen:o,parentSchema:n,data:s,keyword:i,it:a}=t;l(n),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Es.mergeEvaluated.items(o,r.length,a.items));let c=o.name("valid"),u=o.const("len",(0,kg._)`${s}.length`);r.forEach((d,p)=>{(0,Es.alwaysValidSchema)(a,d)||(o.if((0,kg._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let _=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Es.checkStrictMode)(a,_,p.strictTuples)}}}en.validateTuple=zg;en.default=Nx});var Pg=k(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var Mx=Qc(),jx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Mx.validateTuple)(t,"items")};eu.default=jx});var Tg=k(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var Eg=Z(),Zx=F(),Dx=Be(),qx=Xc(),Lx={message:({params:{len:t}})=>(0,Eg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Eg._)`{limit: ${t}}`},Ux={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Lx,code(t){let{schema:e,parentSchema:r,it:o}=t,{prefixItems:n}=r;o.items=!0,!(0,Zx.alwaysValidSchema)(o,e)&&(n?(0,qx.validateAdditionalItems)(t,n):t.ok((0,Dx.validateArray)(t)))}};tu.default=Ux});var Rg=k(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var Ke=Z(),Ts=F(),Fx={message:({params:{min:t,max:e}})=>e===void 0?(0,Ke.str)`must contain at least ${t} valid item(s)`:(0,Ke.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ke._)`{minContains: ${t}}`:(0,Ke._)`{minContains: ${t}, maxContains: ${e}}`},Vx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Fx,code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t,i,a,{minContains:c,maxContains:u}=o;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Ke._)`${n}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ts.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ts.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ts.alwaysValidSchema)(s,r)){let g=(0,Ke._)`${l} >= ${i}`;a!==void 0&&(g=(0,Ke._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ke._)`${n}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),_=e.let("count",0);f(g,()=>e.if(g,()=>h(_)))}function f(g,_){e.forRange("i",0,l,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:Ts.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,Ke._)`${g}++`),a===void 0?e.if((0,Ke._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ke._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ke._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};ru.default=Vx});var Og=k(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.validateSchemaDeps=ct.validatePropertyDeps=ct.error=void 0;var ou=Z(),Hx=F(),tn=Be();ct.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let o=e===1?"property":"properties";return(0,ou.str)`must have ${o} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:o}})=>(0,ou._)`{property: ${t},
|
|
7
7
|
missingProperty: ${o},
|
|
8
8
|
depsCount: ${e},
|
|
9
|
-
deps: ${r}}`};var Hx={keyword:"dependencies",type:"object",schemaType:"object",error:ct.error,code(t){let[e,r]=Jx(t);Ig(t,e),Cg(t,r)}};function Jx({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function Ig(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,tn.propertyInData)(r,o,i,n.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),n.allErrors?r.if(c,()=>{for(let u of a)(0,tn.checkReportMissingProp)(t,u)}):(r.if((0,ou._)`${c} && (${(0,tn.checkMissingProp)(t,a,s)})`),(0,tn.reportMissingProp)(t,s),r.else())}}ct.validatePropertyDeps=Ig;function Cg(t,e=t.schema){let{gen:r,data:o,keyword:n,it:s}=t,i=r.name("valid");for(let a in e)(0,Vx.alwaysValidSchema)(s,e[a])||(r.if((0,tn.propertyInData)(r,o,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:n,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}ct.validateSchemaDeps=Cg;ct.default=Hx});var Ng=k(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ag=Z(),Bx=F(),Wx={message:"property name must be valid",params:({params:t})=>(0,Ag._)`{propertyName: ${t.propertyName}}`},Kx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Wx,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,Bx.alwaysValidSchema)(n,r))return;let s=e.name("valid");e.forIn("key",o,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ag.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};nu.default=Kx});var iu=k(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Rs=Be(),tt=Z(),Gx=St(),Is=F(),Yx={message:"must NOT have additional properties",params:({params:t})=>(0,tt._)`{additionalProperty: ${t.additionalProperty}}`},Xx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Yx,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Is.alwaysValidSchema)(i,r))return;let u=(0,Rs.allSchemaProperties)(o.properties),l=(0,Rs.allSchemaProperties)(o.patternProperties);d(),t.ok((0,tt._)`${s} === ${Gx.default.errors}`);function d(){e.forIn("key",n,_=>{!u.length&&!l.length?h(_):e.if(p(_),()=>h(_))})}function p(_){let w;if(u.length>8){let b=(0,Is.schemaRefOrVal)(i,o.properties,"properties");w=(0,Rs.isOwnProperty)(e,b,_)}else u.length?w=(0,tt.or)(...u.map(b=>(0,tt._)`${_} === ${b}`)):w=tt.nil;return l.length&&(w=(0,tt.or)(w,...l.map(b=>(0,tt._)`${(0,Rs.usePattern)(t,b)}.test(${_})`))),(0,tt.not)(w)}function f(_){e.code((0,tt._)`delete ${n}[${_}]`)}function h(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Is.alwaysValidSchema)(i,r)){let w=e.name("valid");c.removeAdditional==="failing"?(g(_,w,!1),e.if((0,tt.not)(w),()=>{t.reset(),f(_)})):(g(_,w),a||e.if((0,tt.not)(w),()=>e.break()))}}function g(_,w,b){let z={keyword:"additionalProperties",dataProp:_,dataPropType:Is.Type.Str};b===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,w)}}};su.default=Xx});var Zg=k(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var Qx=Lo(),Mg=Be(),au=F(),jg=iu(),ek={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t;s.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&jg.default.code(new Qx.KeywordCxt(s,jg.default,"additionalProperties"));let i=(0,Mg.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=au.mergeEvaluated.props(e,(0,au.toHash)(i),s.props));let a=i.filter(d=>!(0,au.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Mg.propertyInData)(e,n,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};cu.default=ek});var Ug=k(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var Dg=Be(),Cs=Z(),qg=F(),Lg=F(),tk={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:o,parentSchema:n,it:s}=t,{opts:i}=s,a=(0,Dg.allSchemaProperties)(r),c=a.filter(g=>(0,qg.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&n.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Cs.Name)&&(s.props=(0,Lg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?h(g):(e.var(l,!0),h(g),e.if(l))}function f(g){for(let _ in u)new RegExp(g).test(_)&&(0,qg.checkStrictMode)(s,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",o,_=>{e.if((0,Cs._)`${(0,Dg.usePattern)(t,g)}.test(${_})`,()=>{let w=c.includes(g);w||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:Lg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Cs._)`${d}[${_}]`,!0):!w&&!s.allErrors&&e.if((0,Cs.not)(l),()=>e.break())})})}}};uu.default=tk});var Fg=k(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var rk=F(),ok={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:o}=t;if((0,rk.alwaysValidSchema)(o,r)){t.fail();return}let n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};lu.default=ok});var Vg=k(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var nk=Be(),sk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nk.validateUnion,error:{message:"must match a schema in anyOf"}};du.default=sk});var Hg=k(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var Os=Z(),ik=F(),ak={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Os._)`{passingSchemas: ${t.passing}}`},ck={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ak,code(t){let{gen:e,schema:r,parentSchema:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,ik.alwaysValidSchema)(n,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Os._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Os._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Os.Name)})})}}};pu.default=ck});var Jg=k(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var uk=F(),lk={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let n=e.name("valid");r.forEach((s,i)=>{if((0,uk.alwaysValidSchema)(o,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},n);t.ok(n),t.mergeEvaluated(a)})}};fu.default=lk});var Kg=k(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var As=Z(),Wg=F(),dk={message:({params:t})=>(0,As.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,As._)`{failingKeyword: ${t.ifClause}}`},pk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:dk,code(t){let{gen:e,parentSchema:r,it:o}=t;r.then===void 0&&r.else===void 0&&(0,Wg.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let n=Bg(o,"then"),s=Bg(o,"else");if(!n&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),n&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else n?e.if(a,u("then")):e.if((0,As.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,As._)`${l}`):t.setParams({ifClause:l})}}}};function Bg(t,e){let r=t.schema[e];return r!==void 0&&!(0,Wg.alwaysValidSchema)(t,r)}hu.default=pk});var Gg=k(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var fk=F(),hk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,fk.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};mu.default=hk});var Yg=k(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});var mk=Xc(),gk=Pg(),_k=Qc(),yk=Tg(),vk=Rg(),wk=Og(),bk=Ng(),$k=iu(),Sk=Zg(),xk=Ug(),kk=Fg(),zk=Vg(),Pk=Hg(),Ek=Jg(),Tk=Kg(),Rk=Gg();function Ik(t=!1){let e=[kk.default,zk.default,Pk.default,Ek.default,Tk.default,Rk.default,bk.default,$k.default,wk.default,Sk.default,xk.default];return t?e.push(gk.default,yk.default):e.push(mk.default,_k.default),e.push(vk.default),e}gu.default=Ik});var Xg=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var fe=Z(),Ck={message:({schemaCode:t})=>(0,fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,fe._)`{format: ${t}}`},Ok={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Ck,code(t,e){let{gen:r,data:o,$data:n,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;n?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,fe._)`${h}[${i}]`),_=r.let("fType"),w=r.let("format");r.if((0,fe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,fe._)`${g}.type || "string"`).assign(w,(0,fe._)`${g}.validate`),()=>r.assign(_,(0,fe._)`"string"`).assign(w,g)),t.fail$data((0,fe.or)(b(),z()));function b(){return c.strictSchema===!1?fe.nil:(0,fe._)`${i} && !${w}`}function z(){let E=l.$async?(0,fe._)`(${g}.async ? await ${w}(${o}) : ${w}(${o}))`:(0,fe._)`${w}(${o})`,v=(0,fe._)`(typeof ${w} == "function" ? ${E} : ${w}.test(${o}))`;return(0,fe._)`${w} && ${w} !== true && ${_} === ${e} && !${v}`}}function f(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[g,_,w]=z(h);g===e&&t.pass(E());function b(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function z(v){let $=v instanceof RegExp?(0,fe.regexpCode)(v):c.code.formats?(0,fe._)`${c.code.formats}${(0,fe.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:v,code:$});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,fe._)`${O}.validate`]:["string",v,O]}function E(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,fe._)`await ${w}(${o})`}return typeof _=="function"?(0,fe._)`${w}(${o})`:(0,fe._)`${w}.test(${o})`}}}};_u.default=Ok});var Qg=k(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var Ak=Xg(),Nk=[Ak.default];yu.default=Nk});var e_=k(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.contentVocabulary=Hr.metadataVocabulary=void 0;Hr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Hr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var r_=k(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var Mk=ug(),jk=Sg(),Zk=Yg(),Dk=Qg(),t_=e_(),qk=[Mk.default,jk.default,(0,Zk.default)(),Dk.default,t_.metadataVocabulary,t_.contentVocabulary];vu.default=qk});var n_=k(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.DiscrError=void 0;var o_;(function(t){t.Tag="tag",t.Mapping="mapping"})(o_||(Ns.DiscrError=o_={}))});var i_=k(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var Jr=Z(),wu=n_(),s_=_s(),Lk=Uo(),Uk=F(),Fk={message:({params:{discrError:t,tagName:e}})=>t===wu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Jr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Vk={keyword:"discriminator",type:"object",schemaType:"object",error:Fk,code(t){let{gen:e,data:r,schema:o,parentSchema:n,it:s}=t,{oneOf:i}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Jr._)`${r}${(0,Jr.getProperty)(a)}`);e.if((0,Jr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:wu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,Jr._)`${u} === ${h}`),e.assign(c,d(f[h]));e.else(),t.error(!1,{discrError:wu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(g,Jr.Name),h}function p(){var f;let h={},g=w(n),_=!0;for(let E=0;E<i.length;E++){let v=i[E];if(v?.$ref&&!(0,Uk.schemaHasRulesButRef)(v,s.self.RULES)){let O=v.$ref;if(v=s_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),v instanceof s_.SchemaEnv&&(v=v.schema),v===void 0)throw new Lk.default(s.opts.uriResolver,s.baseId,O)}let $=(f=v?.properties)===null||f===void 0?void 0:f[a];if(typeof $!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(g||w(v)),b($,E)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:E}){return Array.isArray(E)&&E.includes(a)}function b(E,v){if(E.const)z(E.const,v);else if(E.enum)for(let $ of E.enum)z($,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(E,v){if(typeof E!="string"||E in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[E]=v}}}};bu.default=Vk});var a_=k((QA,Hk)=>{Hk.exports={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0}});var Su=k((se,$u)=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.MissingRefError=se.ValidationError=se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=se.Ajv=void 0;var Jk=og(),Bk=r_(),Wk=i_(),c_=a_(),Kk=["/properties"],Ms="http://json-schema.org/draft-07/schema",Br=class extends Jk.default{_addVocabularies(){super._addVocabularies(),Bk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Wk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(c_,Kk):c_;this.addMetaSchema(e,Ms,!1),this.refs["http://json-schema.org/schema"]=Ms}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ms)?Ms:void 0)}};se.Ajv=Br;$u.exports=se=Br;$u.exports.Ajv=Br;Object.defineProperty(se,"__esModule",{value:!0});se.default=Br;var Gk=Lo();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Gk.KeywordCxt}});var Wr=Z();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Wr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Wr.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Wr.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Wr.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Wr.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Wr.CodeGen}});var Yk=ms();Object.defineProperty(se,"ValidationError",{enumerable:!0,get:function(){return Yk.default}});var Xk=Uo();Object.defineProperty(se,"MissingRefError",{enumerable:!0,get:function(){return Xk.default}})});var g_=k(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatNames=lt.fastFormats=lt.fullFormats=void 0;function ut(t,e){return{validate:t,compare:e}}lt.fullFormats={date:ut(p_,Pu),time:ut(ku(!0),Eu),"date-time":ut(u_(!0),h_),"iso-time":ut(ku(),f_),"iso-date-time":ut(u_(),m_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nz,"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:dz,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:sz,int32:{type:"number",validate:cz},int64:{type:"number",validate:uz},float:{type:"number",validate:d_},double:{type:"number",validate:d_},password:!0,binary:!0};lt.fastFormats={...lt.fullFormats,date:ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pu),time:ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Eu),"date-time":ut(/^\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,h_),"iso-time":ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f_),"iso-date-time":ut(/^\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,m_),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};lt.formatNames=Object.keys(lt.fullFormats);function Qk(t){return t%4===0&&(t%100!==0||t%400===0)}var ez=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function p_(t){let e=ez.exec(t);if(!e)return!1;let r=+e[1],o=+e[2],n=+e[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&Qk(r)?29:tz[o])}function Pu(t,e){if(t&&e)return t>e?1:t<e?-1:0}var xu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ku(t){return function(r){let o=xu.exec(r);if(!o)return!1;let n=+o[1],s=+o[2],i=+o[3],a=o[4],c=o[5]==="-"?-1:1,u=+(o[6]||0),l=+(o[7]||0);if(u>23||l>59||t&&!a)return!1;if(n<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Eu(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(r&&o)return r-o}function f_(t,e){if(!(t&&e))return;let r=xu.exec(t),o=xu.exec(e);if(r&&o)return t=r[1]+r[2]+r[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var zu=/t|\s/i;function u_(t){let e=ku(t);return function(o){let n=o.split(zu);return n.length===2&&p_(n[0])&&e(n[1])}}function h_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),o=new Date(e).valueOf();if(r&&o)return r-o}function m_(t,e){if(!(t&&e))return;let[r,o]=t.split(zu),[n,s]=e.split(zu),i=Pu(r,n);if(i!==void 0)return i||Eu(o,s)}var rz=/\/|:/,oz=/^(?:[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;function nz(t){return rz.test(t)&&oz.test(t)}var l_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function sz(t){return l_.lastIndex=0,l_.test(t)}var iz=-(2**31),az=2**31-1;function cz(t){return Number.isInteger(t)&&t<=az&&t>=iz}function uz(t){return Number.isInteger(t)}function d_(){return!0}var lz=/[^\\]\\Z/;function dz(t){if(lz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var __=k(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.formatLimitDefinition=void 0;var pz=Su(),rt=Z(),Bt=rt.operators,js={formatMaximum:{okStr:"<=",ok:Bt.LTE,fail:Bt.GT},formatMinimum:{okStr:">=",ok:Bt.GTE,fail:Bt.LT},formatExclusiveMaximum:{okStr:"<",ok:Bt.LT,fail:Bt.GTE},formatExclusiveMinimum:{okStr:">",ok:Bt.GT,fail:Bt.LTE}},fz={message:({keyword:t,schemaCode:e})=>(0,rt.str)`should be ${js[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rt._)`{comparison: ${js[t].okStr}, limit: ${e}}`};Kr.formatLimitDefinition={keyword:Object.keys(js),type:"string",schemaType:"string",$data:!0,error:fz,code(t){let{gen:e,data:r,schemaCode:o,keyword:n,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new pz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,rt._)`${p}[${c.schemaCode}]`);t.fail$data((0,rt.or)((0,rt._)`typeof ${f} != "object"`,(0,rt._)`${f} instanceof RegExp`,(0,rt._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${n}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,rt._)`${i.code.formats}${(0,rt.getProperty)(p)}`:void 0});t.fail$data(d(h))}function d(p){return(0,rt._)`${p}.compare(${r}, ${o}) ${js[n].fail} 0`}},dependencies:["format"]};var hz=t=>(t.addKeyword(Kr.formatLimitDefinition),t);Kr.default=hz});var b_=k((rn,w_)=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});var Gr=g_(),mz=__(),Tu=Z(),y_=new Tu.Name("fullFormats"),gz=new Tu.Name("fastFormats"),Ru=(t,e={keywords:!0})=>{if(Array.isArray(e))return v_(t,e,Gr.fullFormats,y_),t;let[r,o]=e.mode==="fast"?[Gr.fastFormats,gz]:[Gr.fullFormats,y_],n=e.formats||Gr.formatNames;return v_(t,n,r,o),e.keywords&&(0,mz.default)(t),t};Ru.get=(t,e="full")=>{let o=(e==="fast"?Gr.fastFormats:Gr.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function v_(t,e,r,o){var n,s;(n=(s=t.opts.code).formats)!==null&&n!==void 0||(s.formats=(0,Tu._)`require("ajv-formats/dist/formats").${o}`);for(let i of e)t.addFormat(i,r[i])}w_.exports=rn=Ru;Object.defineProperty(rn,"__esModule",{value:!0});rn.default=Ru});var P_=k(Iu=>{"use strict";var x_=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,vz=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,k_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,wz=/\\([\u000b\u0020-\u00ff])/g,bz=/([\\"])/g,z_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Iu.format=$z;Iu.parse=Sz;function $z(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!z_.test(r))throw new TypeError("invalid type");var o=r;if(e&&typeof e=="object")for(var n,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(n=s[i],!k_.test(n))throw new TypeError("invalid parameter name");o+="; "+n+"="+kz(e[n])}return o}function Sz(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?xz(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),o=r!==-1?e.slice(0,r).trim():e.trim();if(!z_.test(o))throw new TypeError("invalid media type");var n=new zz(o.toLowerCase());if(r!==-1){var s,i,a;for(x_.lastIndex=r;i=x_.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(wz,"$1"))),n.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return n}function xz(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function kz(t){var e=String(t);if(k_.test(e))return e;if(e.length>0&&!vz.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(bz,"\\$1")+'"'}function zz(t){this.parameters=Object.create(null),this.type=t}});var _P={};wn(_P,{CLI_NAME:()=>Ie,CLI_VERSION:()=>Xr,printHelp:()=>ny,runCli:()=>sy});module.exports=dy(_P);var oy=require("util");var si=require("child_process"),ft=De(Qu());var ot=class extends Error{status;data;constructor(e,r,o){super(e),this.name="HttpError",this.status=r,this.data=o}},fy=15e3,hy=2;async function Tt(t,e){let r=e?.method||"GET",o=e?.timeoutMs??fy,n=e?.retries??hy,s={Accept:"application/json",...e?.headers||{}},i;e?.body&&(typeof e.body=="string"?i=e.body:e.body instanceof URLSearchParams?(i=e.body.toString(),s["Content-Type"]||(s["Content-Type"]="application/x-www-form-urlencoded")):(i=JSON.stringify(e.body),s["Content-Type"]||(s["Content-Type"]="application/json")));let a=0,c=null;for(;a<=n;){a++;let u=new AbortController,l=setTimeout(()=>u.abort(),o);try{let p=await(e?.fetchFn||fetch)(t,{method:r,headers:s,body:i,signal:u.signal});clearTimeout(l);let f=p.headers.get("content-type")||"",h;if(f.includes("application/json"))try{h=await p.json()}catch{h=null}else h=await p.text();if(p.status>=500&&p.status<=504&&a<=n){let g=Math.min(1e3*Math.pow(2,a-1)+Math.random()*200,5e3);await new Promise(_=>setTimeout(_,g));continue}return{status:p.status,ok:p.ok,headers:p.headers,data:h}}catch(d){clearTimeout(l);let f=d instanceof Error&&d.name==="AbortError"?`Request timed out after ${o}ms`:d instanceof Error?d.message:String(d);if(c=new Error(`Network request failed for ${r} ${t}: ${f}`),a<=n){let h=Math.min(500*Math.pow(2,a-1)+Math.random()*200,3e3);await new Promise(g=>setTimeout(g,h));continue}}}throw c||new Error(`Network request failed after ${a} attempts`)}var de=De(require("fs")),eo=De(require("path")),tl=De(require("os"));function ti(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return!(typeof e.serverUrl!="string"||typeof e.clientId!="string"||typeof e.accessToken!="string"||typeof e.tokenType!="string"||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||!("organizationId"in e)||e.organizationId!==null&&typeof e.organizationId!="string"||e.refreshToken!==void 0&&typeof e.refreshToken!="string"||e.scope!==void 0&&typeof e.scope!="string"||e.resource!==void 0&&typeof e.resource!="string"||e.updatedAt!==void 0&&(typeof e.updatedAt!="number"||!Number.isFinite(e.updatedAt)))}function Yt(t,e){let r=(e||"").trim(),o=(t||"").trim();/^https?:\/\//i.test(o)||(o=`https://${o}`);try{return`${new URL(o).origin.toLowerCase()}::${r}`}catch{return`${o.replace(/\/+$/,"").toLowerCase()}::${r}`}}function pt(t,e){let r=t;for(let o of e)o&&typeof o=="string"&&o.length>=4&&(r=r.split(o).join("[REDACTED]"));return r}function Qr(t,e=60){if(!t.expiresAt)return!1;let r=t.expiresAt>1e11?t.expiresAt:t.expiresAt*1e3;return Date.now()+e*1e3>=r}var el=require("child_process");var ri=class{defaultTimeoutMs;constructor(e=5e3){this.defaultTimeoutMs=e}spawn(e,r,o){return new Promise(n=>{let s;try{s=(0,el.spawn)(e,r,{shell:!1,stdio:["pipe","pipe","pipe"]})}catch(d){let p=d instanceof Error?d.message:String(d);return n({stdout:"",stderr:p,exitCode:-1})}let i="",a="",c=!1,u=o?.timeoutMs??this.defaultTimeoutMs,l=setTimeout(()=>{if(!c){c=!0;try{s.kill("SIGKILL")}catch{}n({stdout:i,stderr:`Keychain operation timed out after ${u}ms`,exitCode:-1})}},u);if(s.stdout?.on("data",d=>{i+=d.toString()}),s.stderr?.on("data",d=>{a+=d.toString()}),s.on("error",d=>{a+=d.message}),s.on("close",d=>{c||(c=!0,clearTimeout(l),n({stdout:i,stderr:a,exitCode:d??-1}))}),o?.input!==void 0&&s.stdin)try{s.stdin.write(o.input),s.stdin.end()}catch{}})}},oi="iwas-cli",bn=class{service;runner;platform;constructor(e){this.service=e?.serviceName||oi,this.runner=e?.runner||new ri,this.platform=e?.platform||process.platform}availableCache=null;getPlatform(){return this.platform}async isAvailable(e=!1){if(!e&&this.availableCache===!0)return!0;if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["help"]),o=r.exitCode===0||r.stdout.includes("security")||r.stderr.includes("security");return o&&(this.availableCache=!0),o}if(this.platform==="linux"){let o=(await this.runner.spawn("which",["secret-tool"])).exitCode===0;return o&&(this.availableCache=!0),o}return!1}clearAvailabilityCache(){this.availableCache=null}async getSecret(e){if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["find-generic-password","-s",this.service,"-a",e,"-w"]);if(r.exitCode===0){let o=r.stdout.trim();if(o.length>0&&o.length%2===0&&/^[0-9a-fA-F]+$/.test(o)&&(o.startsWith("7b")||o.startsWith("7B")||o.startsWith("5b")||o.startsWith("5B")))try{let n=Buffer.from(o,"hex").toString("utf8");if(!n.includes("\uFFFD"))return n}catch{}return o}if(r.exitCode===44||r.stderr.includes("could not be found")||r.stderr.includes("The specified item could not be found"))return null;throw new Error(`Keychain read failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}if(this.platform==="linux"){let r=await this.runner.spawn("secret-tool",["lookup","service",this.service,"account",e]);if(r.exitCode===0)return r.stdout.length>0?r.stdout.trim():null;let o=r.stderr.trim();if(r.exitCode===1&&(o===""||o.toLowerCase().includes("not found")||o.toLowerCase().includes("no such secret")))return null;throw new Error(`Secret-tool read failed: ${o||`exit code ${r.exitCode}`}`)}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}async setSecret(e,r,o){let n=o||`${this.service} (${e})`,s=[r];try{let i=JSON.parse(r);if(typeof i=="object"&&i!==null)for(let a of Object.values(i))typeof a=="string"&&a.length>=4&&s.push(a)}catch{}if(this.platform==="darwin"){let i=await this.runner.spawn("/usr/bin/security",["add-generic-password","-U","-s",this.service,"-a",e,"-l",n,"-w",r]);if(i.exitCode!==0){let a=pt(i.stderr.trim(),s);throw new Error(`Keychain write failed: ${a||`exit code ${i.exitCode}`}`)}return}if(this.platform==="linux"){let i=await this.runner.spawn("secret-tool",["store",`--label=${n}`,"service",this.service,"account",e],{input:r});if(i.exitCode!==0){let a=pt(i.stderr.trim(),s);throw new Error(`Secret-tool write failed: ${a||`exit code ${i.exitCode}`}`)}return}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}async deleteSecret(e){if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["delete-generic-password","-s",this.service,"-a",e]);if(r.exitCode===0||r.exitCode===44||r.stderr.includes("could not be found"))return;throw new Error(`Keychain delete failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}if(this.platform==="linux"){let r=await this.runner.spawn("secret-tool",["clear","service",this.service,"account",e]);if(r.exitCode===0||r.exitCode===1)return;throw new Error(`Secret-tool clear failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}};var $n="__profiles__",Ge=class{vaultType;configDir;credentialsFilePath;keychain;constructor(e){let r=process.env.IWAS_MCP_VAULT;if(r&&!["auto","keychain","file"].includes(r))throw new Error(`Invalid IWAS_MCP_VAULT value: "${r}". Supported values are "auto", "keychain", or "file".`);let o=r;this.vaultType=e?.vaultType||o||"auto";let n=e?.configDir||process.env.XDG_CONFIG_HOME||eo.default.join(tl.default.homedir(),".config");this.configDir=e?.configDir?e.configDir:eo.default.join(n,"iwas"),this.credentialsFilePath=eo.default.join(this.configDir,"credentials.json"),this.keychain=e?.keychainService||new bn({serviceName:e?.serviceName||oi,runner:e?.keychainRunner})}getConfigDir(){return this.configDir}getCredentialsFilePath(){return this.credentialsFilePath}async getEffectiveBackend(){if(this.vaultType==="file")return"file";let e=await this.keychain.isAvailable().catch(()=>!1),r=this.keychain.getPlatform();if(this.vaultType==="keychain"){if(!e)throw new Error(`Keychain vault requested (IWAS_MCP_VAULT="keychain") but OS keychain is unavailable on platform: ${r}`);return"keychain"}return e?"keychain":"file"}async load(e){if(await this.getEffectiveBackend()==="keychain"){let o=null;try{let a=await this.keychain.getSecret(e);if(a)try{let c=JSON.parse(a);if(ti(c))o=c;else if(this.vaultType==="keychain")throw new Error(`Corrupt credentials stored in keychain for profile: ${e}`)}catch(c){if(this.vaultType==="keychain"){let u=c instanceof Error?c.message:String(c);throw new Error(`Corrupt credentials JSON in keychain for profile ${e}: ${u}`)}}}catch(a){if(this.vaultType==="keychain")throw a}if(this.vaultType==="keychain")return o;let n=this.loadFromFile(e);if(!o){if(n)try{await this.keychain.setSecret(e,JSON.stringify(n),`IWAS MCP Profile (${e})`),await this.addProfileToKeychainIndex(e),this.deleteFromFile(e)}catch{}return n}if(!n)return o;let s=o.updatedAt??o.expiresAt??0;if((n.updatedAt??n.expiresAt??0)>s){try{await this.keychain.setSecret(e,JSON.stringify(n),`IWAS MCP Profile (${e})`),await this.addProfileToKeychainIndex(e),this.deleteFromFile(e)}catch{}return n}else return this.deleteFromFile(e),o}return this.loadFromFile(e)}async save(e,r){let o=await this.getEffectiveBackend(),n={...r,updatedAt:r.updatedAt??Date.now()};if(o==="keychain"){let s=!1;try{let i=JSON.stringify(n);await this.keychain.setSecret(e,i,`IWAS MCP Profile (${e})`),s=!0;try{await this.addProfileToKeychainIndex(e)}catch(a){let c=a instanceof Error?a.message:String(a),u=pt(c,[n.accessToken,n.refreshToken]);throw new Error(`Keychain index update failed: ${u}`)}this.deleteFromFile(e);return}catch(i){if(this.vaultType==="keychain"||s){let a=i instanceof Error?i.message:String(i),c=pt(a,[n.accessToken,n.refreshToken]);throw i instanceof Error&&i.message.startsWith("Keychain")?i:new Error(`Keychain save failed: ${c}`)}}}this.saveToFile(e,n)}async delete(e){let r=null,o=!1;if(this.vaultType==="file"){this.deleteFromFile(e);return}try{if(o=await this.keychain.isAvailable().catch(()=>!1),this.vaultType==="keychain"&&!o)throw new Error(`Keychain vault requested (IWAS_MCP_VAULT="keychain") but OS keychain is unavailable on platform: ${this.keychain.getPlatform()}`);o&&(await this.keychain.deleteSecret(e),await this.removeProfileFromKeychainIndex(e))}catch(n){r=n}if(this.deleteFromFile(e),r&&(this.vaultType==="keychain"||this.vaultType==="auto"&&o))throw r}async listProfiles(){if(this.vaultType==="file")return this.listProfilesFromFile();if(this.vaultType==="keychain")return this.readKeychainIndex();let e=new Set;try{if(await this.keychain.isAvailable()){let o=await this.readKeychainIndex();for(let n of o)e.add(n)}}catch{}for(let r of this.listProfilesFromFile())e.add(r);return Array.from(e)}async readKeychainIndex(){let e=await this.keychain.getSecret($n);if(!e)return[];try{let r=JSON.parse(e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):[]}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Corrupt keychain profile index at ${$n}: ${o}`)}}async addProfileToKeychainIndex(e){let r=await this.readKeychainIndex();r.includes(e)||(r.push(e),await this.keychain.setSecret($n,JSON.stringify(r),"IWAS MCP Profiles Index"))}async removeProfileFromKeychainIndex(e){let r=await this.readKeychainIndex();if(r.includes(e)){let o=r.filter(n=>n!==e);await this.keychain.setSecret($n,JSON.stringify(o),"IWAS MCP Profiles Index")}}ensureConfigDirectory(){de.default.existsSync(this.configDir)||de.default.mkdirSync(this.configDir,{recursive:!0,mode:448});try{de.default.chmodSync(this.configDir,448)}catch{}}readAllFromFile(){if(!de.default.existsSync(this.credentialsFilePath))return{};if(process.platform!=="win32")try{de.default.chmodSync(this.credentialsFilePath,384)}catch{}let e=de.default.readFileSync(this.credentialsFilePath,"utf8").trim();if(!e)return{};try{let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("Root credentials object must be a JSON record");for(let[o,n]of Object.entries(r))if(!ti(n))throw new Error(`Profile "${o}" contains invalid or missing credential fields`);return r}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Corrupt credentials file at ${this.credentialsFilePath}: ${o}. Will not overwrite.`)}}writeAllToFile(e){this.ensureConfigDirectory();let r=JSON.stringify(e,null,2)+`
|
|
9
|
+
deps: ${r}}`};var Jx={keyword:"dependencies",type:"object",schemaType:"object",error:ct.error,code(t){let[e,r]=Bx(t);Ig(t,e),Cg(t,r)}};function Bx({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function Ig(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,tn.propertyInData)(r,o,i,n.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),n.allErrors?r.if(c,()=>{for(let u of a)(0,tn.checkReportMissingProp)(t,u)}):(r.if((0,ou._)`${c} && (${(0,tn.checkMissingProp)(t,a,s)})`),(0,tn.reportMissingProp)(t,s),r.else())}}ct.validatePropertyDeps=Ig;function Cg(t,e=t.schema){let{gen:r,data:o,keyword:n,it:s}=t,i=r.name("valid");for(let a in e)(0,Hx.alwaysValidSchema)(s,e[a])||(r.if((0,tn.propertyInData)(r,o,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:n,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}ct.validateSchemaDeps=Cg;ct.default=Jx});var Ng=k(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ag=Z(),Wx=F(),Kx={message:"property name must be valid",params:({params:t})=>(0,Ag._)`{propertyName: ${t.propertyName}}`},Gx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Kx,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,Wx.alwaysValidSchema)(n,r))return;let s=e.name("valid");e.forIn("key",o,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ag.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};nu.default=Gx});var iu=k(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Rs=Be(),tt=Z(),Yx=St(),Is=F(),Xx={message:"must NOT have additional properties",params:({params:t})=>(0,tt._)`{additionalProperty: ${t.additionalProperty}}`},Qx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Xx,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Is.alwaysValidSchema)(i,r))return;let u=(0,Rs.allSchemaProperties)(o.properties),l=(0,Rs.allSchemaProperties)(o.patternProperties);d(),t.ok((0,tt._)`${s} === ${Yx.default.errors}`);function d(){e.forIn("key",n,_=>{!u.length&&!l.length?h(_):e.if(p(_),()=>h(_))})}function p(_){let w;if(u.length>8){let b=(0,Is.schemaRefOrVal)(i,o.properties,"properties");w=(0,Rs.isOwnProperty)(e,b,_)}else u.length?w=(0,tt.or)(...u.map(b=>(0,tt._)`${_} === ${b}`)):w=tt.nil;return l.length&&(w=(0,tt.or)(w,...l.map(b=>(0,tt._)`${(0,Rs.usePattern)(t,b)}.test(${_})`))),(0,tt.not)(w)}function f(_){e.code((0,tt._)`delete ${n}[${_}]`)}function h(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Is.alwaysValidSchema)(i,r)){let w=e.name("valid");c.removeAdditional==="failing"?(g(_,w,!1),e.if((0,tt.not)(w),()=>{t.reset(),f(_)})):(g(_,w),a||e.if((0,tt.not)(w),()=>e.break()))}}function g(_,w,b){let z={keyword:"additionalProperties",dataProp:_,dataPropType:Is.Type.Str};b===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,w)}}};su.default=Qx});var Zg=k(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var ek=Lo(),Mg=Be(),au=F(),jg=iu(),tk={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:s}=t;s.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&jg.default.code(new ek.KeywordCxt(s,jg.default,"additionalProperties"));let i=(0,Mg.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=au.mergeEvaluated.props(e,(0,au.toHash)(i),s.props));let a=i.filter(d=>!(0,au.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Mg.propertyInData)(e,n,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};cu.default=tk});var Ug=k(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var Dg=Be(),Cs=Z(),qg=F(),Lg=F(),rk={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:o,parentSchema:n,it:s}=t,{opts:i}=s,a=(0,Dg.allSchemaProperties)(r),c=a.filter(g=>(0,qg.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&n.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Cs.Name)&&(s.props=(0,Lg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?h(g):(e.var(l,!0),h(g),e.if(l))}function f(g){for(let _ in u)new RegExp(g).test(_)&&(0,qg.checkStrictMode)(s,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",o,_=>{e.if((0,Cs._)`${(0,Dg.usePattern)(t,g)}.test(${_})`,()=>{let w=c.includes(g);w||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:Lg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Cs._)`${d}[${_}]`,!0):!w&&!s.allErrors&&e.if((0,Cs.not)(l),()=>e.break())})})}}};uu.default=rk});var Fg=k(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var ok=F(),nk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:o}=t;if((0,ok.alwaysValidSchema)(o,r)){t.fail();return}let n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};lu.default=nk});var Vg=k(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var sk=Be(),ik={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sk.validateUnion,error:{message:"must match a schema in anyOf"}};du.default=ik});var Hg=k(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var Os=Z(),ak=F(),ck={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Os._)`{passingSchemas: ${t.passing}}`},uk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ck,code(t){let{gen:e,schema:r,parentSchema:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,ak.alwaysValidSchema)(n,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Os._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Os._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Os.Name)})})}}};pu.default=uk});var Jg=k(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var lk=F(),dk={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let n=e.name("valid");r.forEach((s,i)=>{if((0,lk.alwaysValidSchema)(o,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},n);t.ok(n),t.mergeEvaluated(a)})}};fu.default=dk});var Kg=k(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var As=Z(),Wg=F(),pk={message:({params:t})=>(0,As.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,As._)`{failingKeyword: ${t.ifClause}}`},fk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:pk,code(t){let{gen:e,parentSchema:r,it:o}=t;r.then===void 0&&r.else===void 0&&(0,Wg.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let n=Bg(o,"then"),s=Bg(o,"else");if(!n&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),n&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else n?e.if(a,u("then")):e.if((0,As.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,As._)`${l}`):t.setParams({ifClause:l})}}}};function Bg(t,e){let r=t.schema[e];return r!==void 0&&!(0,Wg.alwaysValidSchema)(t,r)}hu.default=fk});var Gg=k(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var hk=F(),mk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,hk.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};mu.default=mk});var Yg=k(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});var gk=Xc(),_k=Pg(),yk=Qc(),vk=Tg(),wk=Rg(),bk=Og(),$k=Ng(),Sk=iu(),xk=Zg(),kk=Ug(),zk=Fg(),Pk=Vg(),Ek=Hg(),Tk=Jg(),Rk=Kg(),Ik=Gg();function Ck(t=!1){let e=[zk.default,Pk.default,Ek.default,Tk.default,Rk.default,Ik.default,$k.default,Sk.default,bk.default,xk.default,kk.default];return t?e.push(_k.default,vk.default):e.push(gk.default,yk.default),e.push(wk.default),e}gu.default=Ck});var Xg=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var fe=Z(),Ok={message:({schemaCode:t})=>(0,fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,fe._)`{format: ${t}}`},Ak={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Ok,code(t,e){let{gen:r,data:o,$data:n,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;n?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,fe._)`${h}[${i}]`),_=r.let("fType"),w=r.let("format");r.if((0,fe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,fe._)`${g}.type || "string"`).assign(w,(0,fe._)`${g}.validate`),()=>r.assign(_,(0,fe._)`"string"`).assign(w,g)),t.fail$data((0,fe.or)(b(),z()));function b(){return c.strictSchema===!1?fe.nil:(0,fe._)`${i} && !${w}`}function z(){let E=l.$async?(0,fe._)`(${g}.async ? await ${w}(${o}) : ${w}(${o}))`:(0,fe._)`${w}(${o})`,v=(0,fe._)`(typeof ${w} == "function" ? ${E} : ${w}.test(${o}))`;return(0,fe._)`${w} && ${w} !== true && ${_} === ${e} && !${v}`}}function f(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[g,_,w]=z(h);g===e&&t.pass(E());function b(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function z(v){let $=v instanceof RegExp?(0,fe.regexpCode)(v):c.code.formats?(0,fe._)`${c.code.formats}${(0,fe.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:v,code:$});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,fe._)`${O}.validate`]:["string",v,O]}function E(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,fe._)`await ${w}(${o})`}return typeof _=="function"?(0,fe._)`${w}(${o})`:(0,fe._)`${w}.test(${o})`}}}};_u.default=Ak});var Qg=k(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var Nk=Xg(),Mk=[Nk.default];yu.default=Mk});var e_=k(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.contentVocabulary=Hr.metadataVocabulary=void 0;Hr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Hr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var r_=k(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var jk=ug(),Zk=Sg(),Dk=Yg(),qk=Qg(),t_=e_(),Lk=[jk.default,Zk.default,(0,Dk.default)(),qk.default,t_.metadataVocabulary,t_.contentVocabulary];vu.default=Lk});var n_=k(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.DiscrError=void 0;var o_;(function(t){t.Tag="tag",t.Mapping="mapping"})(o_||(Ns.DiscrError=o_={}))});var i_=k(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var Jr=Z(),wu=n_(),s_=_s(),Uk=Uo(),Fk=F(),Vk={message:({params:{discrError:t,tagName:e}})=>t===wu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Jr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Hk={keyword:"discriminator",type:"object",schemaType:"object",error:Vk,code(t){let{gen:e,data:r,schema:o,parentSchema:n,it:s}=t,{oneOf:i}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Jr._)`${r}${(0,Jr.getProperty)(a)}`);e.if((0,Jr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:wu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,Jr._)`${u} === ${h}`),e.assign(c,d(f[h]));e.else(),t.error(!1,{discrError:wu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(g,Jr.Name),h}function p(){var f;let h={},g=w(n),_=!0;for(let E=0;E<i.length;E++){let v=i[E];if(v?.$ref&&!(0,Fk.schemaHasRulesButRef)(v,s.self.RULES)){let O=v.$ref;if(v=s_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),v instanceof s_.SchemaEnv&&(v=v.schema),v===void 0)throw new Uk.default(s.opts.uriResolver,s.baseId,O)}let $=(f=v?.properties)===null||f===void 0?void 0:f[a];if(typeof $!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(g||w(v)),b($,E)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:E}){return Array.isArray(E)&&E.includes(a)}function b(E,v){if(E.const)z(E.const,v);else if(E.enum)for(let $ of E.enum)z($,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(E,v){if(typeof E!="string"||E in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[E]=v}}}};bu.default=Hk});var a_=k((e1,Jk)=>{Jk.exports={$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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0}});var Su=k((se,$u)=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.MissingRefError=se.ValidationError=se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=se.Ajv=void 0;var Bk=og(),Wk=r_(),Kk=i_(),c_=a_(),Gk=["/properties"],Ms="http://json-schema.org/draft-07/schema",Br=class extends Bk.default{_addVocabularies(){super._addVocabularies(),Wk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Kk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(c_,Gk):c_;this.addMetaSchema(e,Ms,!1),this.refs["http://json-schema.org/schema"]=Ms}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ms)?Ms:void 0)}};se.Ajv=Br;$u.exports=se=Br;$u.exports.Ajv=Br;Object.defineProperty(se,"__esModule",{value:!0});se.default=Br;var Yk=Lo();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Yk.KeywordCxt}});var Wr=Z();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Wr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Wr.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Wr.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Wr.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Wr.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Wr.CodeGen}});var Xk=ms();Object.defineProperty(se,"ValidationError",{enumerable:!0,get:function(){return Xk.default}});var Qk=Uo();Object.defineProperty(se,"MissingRefError",{enumerable:!0,get:function(){return Qk.default}})});var g_=k(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatNames=lt.fastFormats=lt.fullFormats=void 0;function ut(t,e){return{validate:t,compare:e}}lt.fullFormats={date:ut(p_,Pu),time:ut(ku(!0),Eu),"date-time":ut(u_(!0),h_),"iso-time":ut(ku(),f_),"iso-date-time":ut(u_(),m_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:sz,"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:pz,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:iz,int32:{type:"number",validate:uz},int64:{type:"number",validate:lz},float:{type:"number",validate:d_},double:{type:"number",validate:d_},password:!0,binary:!0};lt.fastFormats={...lt.fullFormats,date:ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pu),time:ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Eu),"date-time":ut(/^\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,h_),"iso-time":ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f_),"iso-date-time":ut(/^\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,m_),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};lt.formatNames=Object.keys(lt.fullFormats);function ez(t){return t%4===0&&(t%100!==0||t%400===0)}var tz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function p_(t){let e=tz.exec(t);if(!e)return!1;let r=+e[1],o=+e[2],n=+e[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&ez(r)?29:rz[o])}function Pu(t,e){if(t&&e)return t>e?1:t<e?-1:0}var xu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ku(t){return function(r){let o=xu.exec(r);if(!o)return!1;let n=+o[1],s=+o[2],i=+o[3],a=o[4],c=o[5]==="-"?-1:1,u=+(o[6]||0),l=+(o[7]||0);if(u>23||l>59||t&&!a)return!1;if(n<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Eu(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(r&&o)return r-o}function f_(t,e){if(!(t&&e))return;let r=xu.exec(t),o=xu.exec(e);if(r&&o)return t=r[1]+r[2]+r[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var zu=/t|\s/i;function u_(t){let e=ku(t);return function(o){let n=o.split(zu);return n.length===2&&p_(n[0])&&e(n[1])}}function h_(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),o=new Date(e).valueOf();if(r&&o)return r-o}function m_(t,e){if(!(t&&e))return;let[r,o]=t.split(zu),[n,s]=e.split(zu),i=Pu(r,n);if(i!==void 0)return i||Eu(o,s)}var oz=/\/|:/,nz=/^(?:[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;function sz(t){return oz.test(t)&&nz.test(t)}var l_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iz(t){return l_.lastIndex=0,l_.test(t)}var az=-(2**31),cz=2**31-1;function uz(t){return Number.isInteger(t)&&t<=cz&&t>=az}function lz(t){return Number.isInteger(t)}function d_(){return!0}var dz=/[^\\]\\Z/;function pz(t){if(dz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var __=k(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.formatLimitDefinition=void 0;var fz=Su(),rt=Z(),Bt=rt.operators,js={formatMaximum:{okStr:"<=",ok:Bt.LTE,fail:Bt.GT},formatMinimum:{okStr:">=",ok:Bt.GTE,fail:Bt.LT},formatExclusiveMaximum:{okStr:"<",ok:Bt.LT,fail:Bt.GTE},formatExclusiveMinimum:{okStr:">",ok:Bt.GT,fail:Bt.LTE}},hz={message:({keyword:t,schemaCode:e})=>(0,rt.str)`should be ${js[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rt._)`{comparison: ${js[t].okStr}, limit: ${e}}`};Kr.formatLimitDefinition={keyword:Object.keys(js),type:"string",schemaType:"string",$data:!0,error:hz,code(t){let{gen:e,data:r,schemaCode:o,keyword:n,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new fz.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,rt._)`${p}[${c.schemaCode}]`);t.fail$data((0,rt.or)((0,rt._)`typeof ${f} != "object"`,(0,rt._)`${f} instanceof RegExp`,(0,rt._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${n}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,rt._)`${i.code.formats}${(0,rt.getProperty)(p)}`:void 0});t.fail$data(d(h))}function d(p){return(0,rt._)`${p}.compare(${r}, ${o}) ${js[n].fail} 0`}},dependencies:["format"]};var mz=t=>(t.addKeyword(Kr.formatLimitDefinition),t);Kr.default=mz});var b_=k((rn,w_)=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});var Gr=g_(),gz=__(),Tu=Z(),y_=new Tu.Name("fullFormats"),_z=new Tu.Name("fastFormats"),Ru=(t,e={keywords:!0})=>{if(Array.isArray(e))return v_(t,e,Gr.fullFormats,y_),t;let[r,o]=e.mode==="fast"?[Gr.fastFormats,_z]:[Gr.fullFormats,y_],n=e.formats||Gr.formatNames;return v_(t,n,r,o),e.keywords&&(0,gz.default)(t),t};Ru.get=(t,e="full")=>{let o=(e==="fast"?Gr.fastFormats:Gr.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function v_(t,e,r,o){var n,s;(n=(s=t.opts.code).formats)!==null&&n!==void 0||(s.formats=(0,Tu._)`require("ajv-formats/dist/formats").${o}`);for(let i of e)t.addFormat(i,r[i])}w_.exports=rn=Ru;Object.defineProperty(rn,"__esModule",{value:!0});rn.default=Ru});var P_=k(Iu=>{"use strict";var x_=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,wz=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,k_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,bz=/\\([\u000b\u0020-\u00ff])/g,$z=/([\\"])/g,z_=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Iu.format=Sz;Iu.parse=xz;function Sz(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!z_.test(r))throw new TypeError("invalid type");var o=r;if(e&&typeof e=="object")for(var n,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(n=s[i],!k_.test(n))throw new TypeError("invalid parameter name");o+="; "+n+"="+zz(e[n])}return o}function xz(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?kz(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),o=r!==-1?e.slice(0,r).trim():e.trim();if(!z_.test(o))throw new TypeError("invalid media type");var n=new Pz(o.toLowerCase());if(r!==-1){var s,i,a;for(x_.lastIndex=r;i=x_.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(bz,"$1"))),n.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return n}function kz(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function zz(t){var e=String(t);if(k_.test(e))return e;if(e.length>0&&!wz.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace($z,"\\$1")+'"'}function Pz(t){this.parameters=Object.create(null),this.type=t}});var yP={};wn(yP,{CLI_NAME:()=>Ie,CLI_VERSION:()=>Xr,printHelp:()=>ny,runCli:()=>sy});module.exports=dy(yP);var oy=require("util");var si=require("child_process"),ft=De(Qu());var ot=class extends Error{status;data;constructor(e,r,o){super(e),this.name="HttpError",this.status=r,this.data=o}},fy=15e3,hy=2;async function Tt(t,e){let r=e?.method||"GET",o=e?.timeoutMs??fy,n=e?.retries??hy,s={Accept:"application/json",...e?.headers||{}},i;e?.body&&(typeof e.body=="string"?i=e.body:e.body instanceof URLSearchParams?(i=e.body.toString(),s["Content-Type"]||(s["Content-Type"]="application/x-www-form-urlencoded")):(i=JSON.stringify(e.body),s["Content-Type"]||(s["Content-Type"]="application/json")));let a=0,c=null;for(;a<=n;){a++;let u=new AbortController,l=setTimeout(()=>u.abort(),o);try{let p=await(e?.fetchFn||fetch)(t,{method:r,headers:s,body:i,signal:u.signal});clearTimeout(l);let f=p.headers.get("content-type")||"",h;if(f.includes("application/json"))try{h=await p.json()}catch{h=null}else h=await p.text();if(p.status>=500&&p.status<=504&&a<=n){let g=Math.min(1e3*Math.pow(2,a-1)+Math.random()*200,5e3);await new Promise(_=>setTimeout(_,g));continue}return{status:p.status,ok:p.ok,headers:p.headers,data:h}}catch(d){clearTimeout(l);let f=d instanceof Error&&d.name==="AbortError"?`Request timed out after ${o}ms`:d instanceof Error?d.message:String(d);if(c=new Error(`Network request failed for ${r} ${t}: ${f}`),a<=n){let h=Math.min(500*Math.pow(2,a-1)+Math.random()*200,3e3);await new Promise(g=>setTimeout(g,h));continue}}}throw c||new Error(`Network request failed after ${a} attempts`)}var de=De(require("fs")),eo=De(require("path")),tl=De(require("os"));function ti(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return!(typeof e.serverUrl!="string"||typeof e.clientId!="string"||typeof e.accessToken!="string"||typeof e.tokenType!="string"||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||!("organizationId"in e)||e.organizationId!==null&&typeof e.organizationId!="string"||e.refreshToken!==void 0&&typeof e.refreshToken!="string"||e.scope!==void 0&&typeof e.scope!="string"||e.resource!==void 0&&typeof e.resource!="string"||e.updatedAt!==void 0&&(typeof e.updatedAt!="number"||!Number.isFinite(e.updatedAt)))}function Yt(t,e){let r=(e||"").trim(),o=(t||"").trim();/^https?:\/\//i.test(o)||(o=`https://${o}`);try{return`${new URL(o).origin.toLowerCase()}::${r}`}catch{return`${o.replace(/\/+$/,"").toLowerCase()}::${r}`}}function pt(t,e){let r=t;for(let o of e)o&&typeof o=="string"&&o.length>=4&&(r=r.split(o).join("[REDACTED]"));return r}function Qr(t,e=60){if(!t.expiresAt)return!1;let r=t.expiresAt>1e11?t.expiresAt:t.expiresAt*1e3;return Date.now()+e*1e3>=r}var el=require("child_process");var ri=class{defaultTimeoutMs;constructor(e=5e3){this.defaultTimeoutMs=e}spawn(e,r,o){return new Promise(n=>{let s;try{s=(0,el.spawn)(e,r,{shell:!1,stdio:["pipe","pipe","pipe"]})}catch(d){let p=d instanceof Error?d.message:String(d);return n({stdout:"",stderr:p,exitCode:-1})}let i="",a="",c=!1,u=o?.timeoutMs??this.defaultTimeoutMs,l=setTimeout(()=>{if(!c){c=!0;try{s.kill("SIGKILL")}catch{}n({stdout:i,stderr:`Keychain operation timed out after ${u}ms`,exitCode:-1})}},u);if(s.stdout?.on("data",d=>{i+=d.toString()}),s.stderr?.on("data",d=>{a+=d.toString()}),s.on("error",d=>{a+=d.message}),s.on("close",d=>{c||(c=!0,clearTimeout(l),n({stdout:i,stderr:a,exitCode:d??-1}))}),o?.input!==void 0&&s.stdin)try{s.stdin.write(o.input),s.stdin.end()}catch{}})}},oi="iwas-cli",bn=class{service;runner;platform;constructor(e){this.service=e?.serviceName||oi,this.runner=e?.runner||new ri,this.platform=e?.platform||process.platform}availableCache=null;getPlatform(){return this.platform}async isAvailable(e=!1){if(!e&&this.availableCache===!0)return!0;if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["help"]),o=r.exitCode===0||r.stdout.includes("security")||r.stderr.includes("security");return o&&(this.availableCache=!0),o}if(this.platform==="linux"){let o=(await this.runner.spawn("which",["secret-tool"])).exitCode===0;return o&&(this.availableCache=!0),o}return!1}clearAvailabilityCache(){this.availableCache=null}async getSecret(e){if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["find-generic-password","-s",this.service,"-a",e,"-w"]);if(r.exitCode===0){let o=r.stdout.trim();if(o.length>0&&o.length%2===0&&/^[0-9a-fA-F]+$/.test(o)&&(o.startsWith("7b")||o.startsWith("7B")||o.startsWith("5b")||o.startsWith("5B")))try{let n=Buffer.from(o,"hex").toString("utf8");if(!n.includes("\uFFFD"))return n}catch{}return o}if(r.exitCode===44||r.stderr.includes("could not be found")||r.stderr.includes("The specified item could not be found"))return null;throw new Error(`Keychain read failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}if(this.platform==="linux"){let r=await this.runner.spawn("secret-tool",["lookup","service",this.service,"account",e]);if(r.exitCode===0)return r.stdout.length>0?r.stdout.trim():null;let o=r.stderr.trim();if(r.exitCode===1&&(o===""||o.toLowerCase().includes("not found")||o.toLowerCase().includes("no such secret")))return null;throw new Error(`Secret-tool read failed: ${o||`exit code ${r.exitCode}`}`)}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}async setSecret(e,r,o){let n=o||`${this.service} (${e})`,s=[r];try{let i=JSON.parse(r);if(typeof i=="object"&&i!==null)for(let a of Object.values(i))typeof a=="string"&&a.length>=4&&s.push(a)}catch{}if(this.platform==="darwin"){let i=await this.runner.spawn("/usr/bin/security",["add-generic-password","-U","-s",this.service,"-a",e,"-l",n,"-w",r]);if(i.exitCode!==0){let a=pt(i.stderr.trim(),s);throw new Error(`Keychain write failed: ${a||`exit code ${i.exitCode}`}`)}return}if(this.platform==="linux"){let i=await this.runner.spawn("secret-tool",["store",`--label=${n}`,"service",this.service,"account",e],{input:r});if(i.exitCode!==0){let a=pt(i.stderr.trim(),s);throw new Error(`Secret-tool write failed: ${a||`exit code ${i.exitCode}`}`)}return}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}async deleteSecret(e){if(this.platform==="darwin"){let r=await this.runner.spawn("/usr/bin/security",["delete-generic-password","-s",this.service,"-a",e]);if(r.exitCode===0||r.exitCode===44||r.stderr.includes("could not be found"))return;throw new Error(`Keychain delete failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}if(this.platform==="linux"){let r=await this.runner.spawn("secret-tool",["clear","service",this.service,"account",e]);if(r.exitCode===0||r.exitCode===1)return;throw new Error(`Secret-tool clear failed: ${r.stderr.trim()||`exit code ${r.exitCode}`}`)}throw new Error(`OS keychain not supported on platform: ${this.platform}`)}};var $n="__profiles__",Ge=class{vaultType;configDir;credentialsFilePath;keychain;constructor(e){let r=process.env.IWAS_MCP_VAULT;if(r&&!["auto","keychain","file"].includes(r))throw new Error(`Invalid IWAS_MCP_VAULT value: "${r}". Supported values are "auto", "keychain", or "file".`);let o=r;this.vaultType=e?.vaultType||o||"auto";let n=e?.configDir||process.env.XDG_CONFIG_HOME||eo.default.join(tl.default.homedir(),".config");this.configDir=e?.configDir?e.configDir:eo.default.join(n,"iwas"),this.credentialsFilePath=eo.default.join(this.configDir,"credentials.json"),this.keychain=e?.keychainService||new bn({serviceName:e?.serviceName||oi,runner:e?.keychainRunner})}getConfigDir(){return this.configDir}getCredentialsFilePath(){return this.credentialsFilePath}async getEffectiveBackend(){if(this.vaultType==="file")return"file";let e=await this.keychain.isAvailable().catch(()=>!1),r=this.keychain.getPlatform();if(this.vaultType==="keychain"){if(!e)throw new Error(`Keychain vault requested (IWAS_MCP_VAULT="keychain") but OS keychain is unavailable on platform: ${r}`);return"keychain"}return e?"keychain":"file"}async load(e){if(await this.getEffectiveBackend()==="keychain"){let o=null;try{let a=await this.keychain.getSecret(e);if(a)try{let c=JSON.parse(a);if(ti(c))o=c;else if(this.vaultType==="keychain")throw new Error(`Corrupt credentials stored in keychain for profile: ${e}`)}catch(c){if(this.vaultType==="keychain"){let u=c instanceof Error?c.message:String(c);throw new Error(`Corrupt credentials JSON in keychain for profile ${e}: ${u}`)}}}catch(a){if(this.vaultType==="keychain")throw a}if(this.vaultType==="keychain")return o;let n=this.loadFromFile(e);if(!o){if(n)try{await this.keychain.setSecret(e,JSON.stringify(n),`IWAS MCP Profile (${e})`),await this.addProfileToKeychainIndex(e),this.deleteFromFile(e)}catch{}return n}if(!n)return o;let s=o.updatedAt??o.expiresAt??0;if((n.updatedAt??n.expiresAt??0)>s){try{await this.keychain.setSecret(e,JSON.stringify(n),`IWAS MCP Profile (${e})`),await this.addProfileToKeychainIndex(e),this.deleteFromFile(e)}catch{}return n}else return this.deleteFromFile(e),o}return this.loadFromFile(e)}async save(e,r){let o=await this.getEffectiveBackend(),n={...r,updatedAt:r.updatedAt??Date.now()};if(o==="keychain"){let s=!1;try{let i=JSON.stringify(n);await this.keychain.setSecret(e,i,`IWAS MCP Profile (${e})`),s=!0;try{await this.addProfileToKeychainIndex(e)}catch(a){let c=a instanceof Error?a.message:String(a),u=pt(c,[n.accessToken,n.refreshToken]);throw new Error(`Keychain index update failed: ${u}`)}this.deleteFromFile(e);return}catch(i){if(this.vaultType==="keychain"||s){let a=i instanceof Error?i.message:String(i),c=pt(a,[n.accessToken,n.refreshToken]);throw i instanceof Error&&i.message.startsWith("Keychain")?i:new Error(`Keychain save failed: ${c}`)}}}this.saveToFile(e,n)}async delete(e){let r=null,o=!1;if(this.vaultType==="file"){this.deleteFromFile(e);return}try{if(o=await this.keychain.isAvailable().catch(()=>!1),this.vaultType==="keychain"&&!o)throw new Error(`Keychain vault requested (IWAS_MCP_VAULT="keychain") but OS keychain is unavailable on platform: ${this.keychain.getPlatform()}`);o&&(await this.keychain.deleteSecret(e),await this.removeProfileFromKeychainIndex(e))}catch(n){r=n}if(this.deleteFromFile(e),r&&(this.vaultType==="keychain"||this.vaultType==="auto"&&o))throw r}async listProfiles(){if(this.vaultType==="file")return this.listProfilesFromFile();if(this.vaultType==="keychain")return this.readKeychainIndex();let e=new Set;try{if(await this.keychain.isAvailable()){let o=await this.readKeychainIndex();for(let n of o)e.add(n)}}catch{}for(let r of this.listProfilesFromFile())e.add(r);return Array.from(e)}async readKeychainIndex(){let e=await this.keychain.getSecret($n);if(!e)return[];try{let r=JSON.parse(e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):[]}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Corrupt keychain profile index at ${$n}: ${o}`)}}async addProfileToKeychainIndex(e){let r=await this.readKeychainIndex();r.includes(e)||(r.push(e),await this.keychain.setSecret($n,JSON.stringify(r),"IWAS MCP Profiles Index"))}async removeProfileFromKeychainIndex(e){let r=await this.readKeychainIndex();if(r.includes(e)){let o=r.filter(n=>n!==e);await this.keychain.setSecret($n,JSON.stringify(o),"IWAS MCP Profiles Index")}}ensureConfigDirectory(){de.default.existsSync(this.configDir)||de.default.mkdirSync(this.configDir,{recursive:!0,mode:448});try{de.default.chmodSync(this.configDir,448)}catch{}}readAllFromFile(){if(!de.default.existsSync(this.credentialsFilePath))return{};if(process.platform!=="win32")try{de.default.chmodSync(this.credentialsFilePath,384)}catch{}let e=de.default.readFileSync(this.credentialsFilePath,"utf8").trim();if(!e)return{};try{let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("Root credentials object must be a JSON record");for(let[o,n]of Object.entries(r))if(!ti(n))throw new Error(`Profile "${o}" contains invalid or missing credential fields`);return r}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Corrupt credentials file at ${this.credentialsFilePath}: ${o}. Will not overwrite.`)}}writeAllToFile(e){this.ensureConfigDirectory();let r=JSON.stringify(e,null,2)+`
|
|
10
10
|
`,o=eo.default.join(this.configDir,`.credentials.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`),n=null;try{n=de.default.openSync(o,"w",384),de.default.writeSync(n,r,void 0,"utf8"),de.default.fsyncSync(n),de.default.closeSync(n),n=null;try{de.default.chmodSync(o,384)}catch{}de.default.renameSync(o,this.credentialsFilePath);try{de.default.chmodSync(this.credentialsFilePath,384)}catch{}if(process.platform!=="win32")try{let s=de.default.openSync(this.configDir,"r");de.default.fsyncSync(s),de.default.closeSync(s)}catch{}}catch(s){if(n!==null)try{de.default.closeSync(n)}catch{}if(de.default.existsSync(o))try{de.default.unlinkSync(o)}catch{}throw s}}loadFromFile(e){return this.readAllFromFile()[e]??null}saveToFile(e,r){let o=this.readAllFromFile();o[e]=r,this.writeAllToFile(o)}deleteFromFile(e){if(!de.default.existsSync(this.credentialsFilePath))return;let r=this.readAllFromFile();e in r&&(delete r[e],this.writeAllToFile(r))}listProfilesFromFile(){if(!de.default.existsSync(this.credentialsFilePath))return[];let e=this.readAllFromFile();return Object.keys(e)}};async function ni(t){let e=t?.logger||(h=>process.stdout.write(`${h}
|
|
11
11
|
`)),r=t?.errorLogger||(h=>process.stderr.write(`${h}
|
|
12
12
|
`)),o=yr(t?.server),n=(t?.clientId||_r).trim(),s=Yt(o,n),i=t?.vault||new Ge,a=t?.force===!0,c=await i.load(s);if(!c){let h={success:!0,profileKey:s,serverRevoked:!1,refreshTokenRevoked:!1,localCleared:!1,message:`No stored credentials found for profile: ${s}`};return t?.json?e(JSON.stringify({event:"logout",success:!0,loggedOut:!0,profileKey:s,serverRevoked:!1,refreshTokenRevoked:!1,localCleared:!1,message:h.message})):e(`\u2139\uFE0F No stored credentials found for profile: ${s}`),h}let u=!1,l=null,d=`${o.replace(/\/+$/,"")}/api/v1/mcp-session/logout`;try{let h=c.tokenType||"Bearer",g=await Tt(d,{method:"POST",headers:{Authorization:`${h} ${c.accessToken}`},fetchFn:t?.fetchFn});if(g.status===204||g.status===200)u=!0;else if(g.status===401||g.status===403)u=!0;else if(g.status===400){let _=g.data;throw new Error(_?.message||"Server rejected logout request (HTTP 400).")}else throw new ot(`Server returned status ${g.status} during logout`,g.status,g.data)}catch(h){l=h instanceof Error?h:new Error(String(h))}if(l&&!a){let h=`Server revocation failed: ${l.message}. Local credentials preserved. Use --force to clear local credentials anyway if the server is permanently offline.`;throw new Error(h)}let p=!1;if(c.refreshToken)try{let h=`${o.replace(/\/+$/,"")}/api/auth/oauth2/revoke`,g=new URLSearchParams({token:c.refreshToken,token_type_hint:"refresh_token",client_id:n}),_=await Tt(h,{method:"POST",body:g,fetchFn:t?.fetchFn});(_.ok||_.status===200||_.status===204||_.status===401||_.status===400)&&(p=!0)}catch{}await i.delete(s);let f={success:!0,profileKey:s,serverRevoked:u,refreshTokenRevoked:p,localCleared:!0,message:l?`Local credentials cleared with --force (server unreachable: ${l.message})`:"Successfully logged out and revoked all grants server-side"};return t?.json?e(JSON.stringify({event:"logout",success:!0,loggedOut:!0,profileKey:s,serverRevoked:u,refreshTokenRevoked:p,localCleared:!0,forced:a&&!!l})):l?(r(`\u26A0\uFE0F Warning: Server revocation failed (${l.message})`),e(`\u2705 Local credentials cleared for profile: ${s} (--force)
|
|
@@ -23,14 +23,14 @@
|
|
|
23
23
|
`),e("To verify, open:"),e(` \u{1F517} ${u.verification_uri_complete}
|
|
24
24
|
`),e("Waiting for approval in browser...");let l=t?.spawnFn||si.spawn,d=t?.browserOpener||(ae=>wy(ae,l,Gt=>{t?.json?r(`\u26A0\uFE0F ${Gt}`):e(`\u26A0\uFE0F ${Gt}`)}));t?.noBrowser||d(u.verification_uri_complete);let p=t?.pollTimeoutMs??u.expires_in*1e3,f=await $y(o,{clientId:s,deviceCode:u.device_code,resource:n,initialInterval:u.interval,timeoutMs:p},ae=>{!t?.json&&ae.startsWith("slow_down")&&e("Rate limit reached: slowing poll interval.")}),h=ai(f.access_token);if(!h||Object.keys(h).length===0)throw new Error("Server returned an opaque or non-JWT access token. Expected a JWT access token targeted for MCP resource.");let g=Array.isArray(h.aud)?h.aud:typeof h.aud=="string"?[h.aud]:[],_=n.replace(/\/+$/,"").toLowerCase();if(!g.some(ae=>{try{return new URL(String(ae)).href.replace(/\/+$/,"").toLowerCase()===_}catch{return String(ae).toLowerCase()===_}}))throw new Error(`Access token audience [${g.join(", ")}] does not match MCP resource URL "${n}".`);let z=(typeof f.scope=="string"&&f.scope||typeof h.scope=="string"&&h.scope||"").split(/\s+/).filter(Boolean),E=i.split(/\s+/).filter(Boolean);if(E.filter(ae=>z.includes(ae)).filter(ae=>ae!==ft.OFFLINE_ACCESS_SCOPE).length===0)throw new Error(`Access token lacks granted capability scopes (requested: [${E.join(", ")}], granted: [${z.join(", ")}]). At least one permission scope besides offline_access must be granted.`);let O=typeof h.organizationId=="string"?h.organizationId:null,K=f.expires_in?Date.now()+f.expires_in*1e3:typeof h.exp=="number"?h.exp*1e3:Date.now()+36e5,j={serverUrl:o,clientId:s,accessToken:f.access_token,refreshToken:f.refresh_token,tokenType:f.token_type||"Bearer",scope:f.scope||i,resource:n,organizationId:O,expiresAt:K,updatedAt:Date.now()},ie=Yt(o,s);await a.save(ie,j);let dt={profileKey:ie,serverUrl:o,clientId:s,organizationId:O,scope:j.scope,resource:j.resource,expiresAt:K};if(t?.json){let ae={event:"login_success",success:!0,...dt};e(JSON.stringify(ae))}else e(`
|
|
25
25
|
\u2705 Login successful!`),e(`- Profile: ${ie}`),e(`- Server: ${o}`),e(`- Client ID: ${s}`),e(`- Organization: ${O||"(none / platform scope)"}`),e(`- Scopes: ${j.scope||"none"}`),e(`- Resource: ${n}`),e(`- Expires: ${new Date(K).toISOString()}
|
|
26
|
-
`);return dt}async function nl(t){let e=t?.logger||(
|
|
26
|
+
`);return dt}function Sy(t){if(t<=0)return"0s";let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),o=Math.floor(t%3600/60),n=t%60,s=[];return e>0&&s.push(`${e}d`),r>0&&s.push(`${r}h`),o>0&&s.push(`${o}m`),(n>0||s.length===0)&&s.push(`${n}s`),s.join(" ")}async function nl(t){let e=t?.logger||(d=>process.stdout.write(`${d}
|
|
27
27
|
`)),r=yr(t?.server),o=(t?.clientId||_r).trim(),n=Yt(r,o),i=await(t?.vault||new Ge).load(n);if(!i){t?.json?e(JSON.stringify({authenticated:!1,profileKey:n,serverUrl:r,clientId:o})):(e(`No active session found for profile: ${n}`),e(`Run \`iwas login --server ${r}\` to authenticate.
|
|
28
|
-
`));return}let a=Qr(i,60),c={authenticated:!a,expired:a,profileKey:n,serverUrl:i.serverUrl,clientId:i.clientId,organizationId:i.organizationId,scope:i.scope,resource:i.resource,expiresAt:new Date(i.expiresAt).toISOString(),expiresInSeconds:
|
|
28
|
+
`));return}let a=Qr(i,60),c=Math.max(0,Math.round((i.expiresAt-Date.now())/1e3)),u=Sy(c),l={authenticated:!a,expired:a,profileKey:n,serverUrl:i.serverUrl,clientId:i.clientId,organizationId:i.organizationId,scope:i.scope,resource:i.resource,expiresAt:new Date(i.expiresAt).toISOString(),expiresInSeconds:c,expiresInFormatted:u};t?.json?e(JSON.stringify(l)):(e(`
|
|
29
29
|
============================================================`),e(" IWAS MCP Auth Status "),e(`============================================================
|
|
30
|
-
`),e(`- Profile: ${n}`),e(`- Server: ${i.serverUrl}`),e(`- Client ID: ${i.clientId}`),e(`- Status: ${a?"\u{1F534} Expired":"\u{1F7E2} Active"}`),e(`- Organization: ${i.organizationId||"(none / platform scope)"}`),e(`- Scopes: ${i.scope||"none"}`),i.resource&&e(`- Resource: ${i.resource}`),e(`- Expires: ${
|
|
31
|
-
`))}var sl,ci=Object.freeze({status:"aborted"});function y(t,e,r){function o(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in a||(a[p]=u[p].bind(a))}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;o(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var nt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vr=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(sl=globalThis).__zod_globalConfig??(sl.__zod_globalConfig={});var wr=globalThis.__zod_globalConfig;function Ce(t){return t&&Object.assign(wr,t),wr}var L={};wn(L,{BIGINT_FORMAT_RANGES:()=>ul,Class:()=>li,NUMBER_FORMAT_RANGES:()=>gi,aborted:()=>Ct,allowsEval:()=>fi,assert:()=>Py,assertEqual:()=>Sy,assertIs:()=>ky,assertNever:()=>zy,assertNotEqual:()=>xy,assignProp:()=>Rt,base64ToUint8Array:()=>dl,base64urlToUint8Array:()=>Vy,cached:()=>$r,captureStackTrace:()=>kn,cleanEnum:()=>Fy,cleanRegex:()=>no,clone:()=>Ue,cloneDef:()=>Ty,createTransparentProxy:()=>Ny,defineLazy:()=>W,esc:()=>xn,escapeRegex:()=>mt,explicitlyAborted:()=>_i,extend:()=>Zy,finalizeIssue:()=>Fe,floatSafeRemainder:()=>di,getElementAtPath:()=>Ry,getEnumValues:()=>ro,getLengthableOrigin:()=>so,getParsedType:()=>Ay,getSizableOrigin:()=>ll,hexToUint8Array:()=>Jy,isObject:()=>Xt,isPlainObject:()=>It,issue:()=>Sr,joinValues:()=>Sn,jsonStringifyReplacer:()=>br,merge:()=>qy,mergeDefs:()=>ht,normalizeParams:()=>I,nullish:()=>oo,numKeys:()=>Oy,objectClone:()=>Ey,omit:()=>jy,optionalKeys:()=>mi,parsedType:()=>yi,partial:()=>Ly,pick:()=>My,prefixIssues:()=>gt,primitiveTypes:()=>cl,promiseAllObject:()=>Iy,propertyKeyTypes:()=>hi,randomString:()=>Cy,required:()=>Uy,safeExtend:()=>Dy,shallowClone:()=>al,slugify:()=>pi,stringifyPrimitive:()=>zn,uint8ArrayToBase64:()=>pl,uint8ArrayToBase64url:()=>Hy,uint8ArrayToHex:()=>By,unwrapMessage:()=>to});function Sy(t){return t}function xy(t){return t}function ky(t){}function zy(t){throw new Error("Unexpected value in exhaustive check")}function Py(t){}function ro(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function Sn(t,e="|"){return t.map(r=>zn(r)).join(e)}function br(t,e){return typeof e=="bigint"?e.toString():e}function $r(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function oo(t){return t==null}function no(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function di(t,e){let r=t/e,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var il=Symbol("evaluating");function W(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==il)return o===void 0&&(o=il,o=r()),o},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Ey(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Rt(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ht(...t){let e={};for(let r of t){let o=Object.getOwnPropertyDescriptors(r);Object.assign(e,o)}return Object.defineProperties({},e)}function Ty(t){return ht(t._zod.def)}function Ry(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function Iy(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let s=0;s<e.length;s++)n[e[s]]=o[s];return n})}function Cy(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function xn(t){return JSON.stringify(t)}function pi(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var kn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fi=$r(()=>{if(wr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function It(t){if(Xt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Xt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function al(t){return It(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Oy(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Ay=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},hi=new Set(["string","number","symbol"]),cl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Ny(t){let e;return new Proxy({},{get(r,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,s){return e??(e=t()),Reflect.set(e,o,n,s)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function zn(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function mi(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var gi={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]},ul={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function My(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=ht(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return Rt(this,"shape",i),i},checks:[]});return Ue(t,s)}function jy(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=ht(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Rt(this,"shape",i),i},checks:[]});return Ue(t,s)}function Zy(t,e){if(!It(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=ht(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Rt(this,"shape",s),s}});return Ue(t,n)}function Dy(t,e){if(!It(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=ht(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return Rt(this,"shape",o),o}});return Ue(t,r)}function qy(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=ht(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e._zod.def.shape};return Rt(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Ue(t,r)}function Ly(t,e,r){let n=e._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=ht(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Rt(this,"shape",c),c},checks:[]});return Ue(e,i)}function Uy(t,e,r){let o=ht(e._zod.def,{get shape(){let n=e._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)s[i]=new t({type:"nonoptional",innerType:n[i]});return Rt(this,"shape",s),s}});return Ue(e,o)}function Ct(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function _i(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function gt(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function to(t){return typeof t=="string"?t:t?.message}function Fe(t,e,r){let o=t.message?t.message:to(t.inst?._zod.def?.error?.(t))??to(e?.error?.(t))??to(r.customError?.(t))??to(r.localeError?.(t))??"Invalid input",{inst:n,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=o,e?.reportInput&&(a.input=i),a}function ll(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function so(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function yi(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Sr(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function Fy(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function dl(t){let e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}function pl(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Vy(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return dl(e+r)}function Hy(t){return pl(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Jy(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)r[o/2]=Number.parseInt(e.slice(o,o+2),16);return r}function By(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var li=class{constructor(...e){}};var fl=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,br,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Pn=y("$ZodError",fl),vi=y("$ZodError",fl,{Parent:Error});function wi(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):o.push(e(n));return{formErrors:o,fieldErrors:r}}function bi(t,e=r=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u<a.length;){let l=a[u];u===a.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(e(i))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return o(t),r}var En=t=>(e,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new nt;if(i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Fe(c,s,Ce())));throw kn(a,n?.callee),a}return i.value};var Tn=t=>async(e,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Fe(c,s,Ce())));throw kn(a,n?.callee),a}return i.value};var io=t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new nt;return s.issues.length?{success:!1,error:new(t??Pn)(s.issues.map(i=>Fe(i,n,Ce())))}:{success:!0,data:s.value}},ao=io(vi),co=t=>async(e,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Fe(i,n,Ce())))}:{success:!0,data:s.value}},Rn=co(vi),hl=t=>(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return En(t)(e,r,n)};var ml=t=>(e,r,o)=>En(t)(e,r,o);var gl=t=>async(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Tn(t)(e,r,n)};var _l=t=>async(e,r,o)=>Tn(t)(e,r,o);var yl=t=>(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return io(t)(e,r,n)};var vl=t=>(e,r,o)=>io(t)(e,r,o);var wl=t=>async(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return co(t)(e,r,n)};var bl=t=>async(e,r,o)=>co(t)(e,r,o);var $l=/^[cC][0-9a-z]{6,}$/,Sl=/^[0-9a-z]+$/,xl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kl=/^[0-9a-vA-V]{20}$/,zl=/^[A-Za-z0-9]{27}$/,Pl=/^[a-zA-Z0-9_-]{21}$/,El=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Tl=/^([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})$/,$i=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/;var Rl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Ky="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Il(){return new RegExp(Ky,"u")}var Cl=/^(?:(?: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])$/,Ol=/^(([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}|:))$/;var Al=/^((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])$/,Nl=/^(([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])$/,Ml=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Si=/^[A-Za-z0-9_-]*$/;var jl=/^https?$/,Zl=/^\+[1-9]\d{6,14}$/,Dl="(?:(?:\\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])))",ql=new RegExp(`^${Dl}$`);function Ll(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ul(t){return new RegExp(`^${Ll(t)}$`)}function Fl(t){let e=Ll({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${e}(?:${r.join("|")})`;return new RegExp(`^${Dl}T(?:${o})$`)}var Vl=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Hl=/^-?\d+n?$/,Jl=/^-?\d+$/,xi=/^-?\d+(?:\.\d+)?$/,Bl=/^(?:true|false)$/i,Wl=/^null$/i;var Kl=/^[^A-Z]*$/,Gl=/^[^a-z]*$/;var _e=y("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Yl={number:"number",bigint:"bigint",object:"date"},ki=y("$ZodCheckLessThan",(t,e)=>{_e.init(t,e);let r=Yl[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zi=y("$ZodCheckGreaterThan",(t,e)=>{_e.init(t,e);let r=Yl[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Xl=y("$ZodCheckMultipleOf",(t,e)=>{_e.init(t,e),t._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):di(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ql=y("$ZodCheckNumberFormat",(t,e)=>{_e.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),o=r?"int":"number",[n,s]=gi[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=n,a.maximum=s,r&&(a.pattern=Jl)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}a<n&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var ed=y("$ZodCheckMaxLength",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let n=o.value;if(n.length<=e.maximum)return;let i=so(n);o.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),td=y("$ZodCheckMinLength",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let n=o.value;if(n.length>=e.minimum)return;let i=so(n);o.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),rd=y("$ZodCheckLengthEquals",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=o=>{let n=o.value,s=n.length;if(s===e.length)return;let i=so(n),a=s>e.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),lo=y("$ZodCheckStringFormat",(t,e)=>{var r,o;_e.init(t,e),t._zod.onattach.push(n=>{let s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),od=y("$ZodCheckRegex",(t,e)=>{lo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),nd=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Kl),lo.init(t,e)}),sd=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Gl),lo.init(t,e)}),id=y("$ZodCheckIncludes",(t,e)=>{_e.init(t,e);let r=mt(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),ad=y("$ZodCheckStartsWith",(t,e)=>{_e.init(t,e);let r=new RegExp(`^${mt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),cd=y("$ZodCheckEndsWith",(t,e)=>{_e.init(t,e);let r=new RegExp(`.*${mt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});var ud=y("$ZodCheckOverwrite",(t,e)=>{_e.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var In=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
|
|
30
|
+
`),e(`- Profile: ${n}`),e(`- Server: ${i.serverUrl}`),e(`- Client ID: ${i.clientId}`),e(`- Status: ${a?"\u{1F534} Expired":"\u{1F7E2} Active"}`),e(`- Organization: ${i.organizationId||"(none / platform scope)"}`),e(`- Scopes: ${i.scope||"none"}`),i.resource&&e(`- Resource: ${i.resource}`),e(`- Expires: ${l.expiresAt} (${u} remaining)
|
|
31
|
+
`))}var sl,ci=Object.freeze({status:"aborted"});function y(t,e,r){function o(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in a||(a[p]=u[p].bind(a))}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;o(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var nt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},vr=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(sl=globalThis).__zod_globalConfig??(sl.__zod_globalConfig={});var wr=globalThis.__zod_globalConfig;function Ce(t){return t&&Object.assign(wr,t),wr}var L={};wn(L,{BIGINT_FORMAT_RANGES:()=>ul,Class:()=>li,NUMBER_FORMAT_RANGES:()=>gi,aborted:()=>Ct,allowsEval:()=>fi,assert:()=>Ey,assertEqual:()=>xy,assertIs:()=>zy,assertNever:()=>Py,assertNotEqual:()=>ky,assignProp:()=>Rt,base64ToUint8Array:()=>dl,base64urlToUint8Array:()=>Hy,cached:()=>$r,captureStackTrace:()=>kn,cleanEnum:()=>Vy,cleanRegex:()=>no,clone:()=>Ue,cloneDef:()=>Ry,createTransparentProxy:()=>My,defineLazy:()=>W,esc:()=>xn,escapeRegex:()=>mt,explicitlyAborted:()=>_i,extend:()=>Dy,finalizeIssue:()=>Fe,floatSafeRemainder:()=>di,getElementAtPath:()=>Iy,getEnumValues:()=>ro,getLengthableOrigin:()=>so,getParsedType:()=>Ny,getSizableOrigin:()=>ll,hexToUint8Array:()=>By,isObject:()=>Xt,isPlainObject:()=>It,issue:()=>Sr,joinValues:()=>Sn,jsonStringifyReplacer:()=>br,merge:()=>Ly,mergeDefs:()=>ht,normalizeParams:()=>I,nullish:()=>oo,numKeys:()=>Ay,objectClone:()=>Ty,omit:()=>Zy,optionalKeys:()=>mi,parsedType:()=>yi,partial:()=>Uy,pick:()=>jy,prefixIssues:()=>gt,primitiveTypes:()=>cl,promiseAllObject:()=>Cy,propertyKeyTypes:()=>hi,randomString:()=>Oy,required:()=>Fy,safeExtend:()=>qy,shallowClone:()=>al,slugify:()=>pi,stringifyPrimitive:()=>zn,uint8ArrayToBase64:()=>pl,uint8ArrayToBase64url:()=>Jy,uint8ArrayToHex:()=>Wy,unwrapMessage:()=>to});function xy(t){return t}function ky(t){return t}function zy(t){}function Py(t){throw new Error("Unexpected value in exhaustive check")}function Ey(t){}function ro(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function Sn(t,e="|"){return t.map(r=>zn(r)).join(e)}function br(t,e){return typeof e=="bigint"?e.toString():e}function $r(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function oo(t){return t==null}function no(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function di(t,e){let r=t/e,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var il=Symbol("evaluating");function W(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==il)return o===void 0&&(o=il,o=r()),o},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Ty(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Rt(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ht(...t){let e={};for(let r of t){let o=Object.getOwnPropertyDescriptors(r);Object.assign(e,o)}return Object.defineProperties({},e)}function Ry(t){return ht(t._zod.def)}function Iy(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function Cy(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let s=0;s<e.length;s++)n[e[s]]=o[s];return n})}function Oy(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function xn(t){return JSON.stringify(t)}function pi(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var kn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fi=$r(()=>{if(wr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function It(t){if(Xt(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Xt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function al(t){return It(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function Ay(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Ny=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},hi=new Set(["string","number","symbol"]),cl=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function My(t){let e;return new Proxy({},{get(r,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,s){return e??(e=t()),Reflect.set(e,o,n,s)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function zn(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function mi(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var gi={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]},ul={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function jy(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=ht(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return Rt(this,"shape",i),i},checks:[]});return Ue(t,s)}function Zy(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=ht(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Rt(this,"shape",i),i},checks:[]});return Ue(t,s)}function Dy(t,e){if(!It(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=ht(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Rt(this,"shape",s),s}});return Ue(t,n)}function qy(t,e){if(!It(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=ht(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return Rt(this,"shape",o),o}});return Ue(t,r)}function Ly(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=ht(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e._zod.def.shape};return Rt(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Ue(t,r)}function Uy(t,e,r){let n=e._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=ht(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Rt(this,"shape",c),c},checks:[]});return Ue(e,i)}function Fy(t,e,r){let o=ht(e._zod.def,{get shape(){let n=e._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)s[i]=new t({type:"nonoptional",innerType:n[i]});return Rt(this,"shape",s),s}});return Ue(e,o)}function Ct(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function _i(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function gt(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function to(t){return typeof t=="string"?t:t?.message}function Fe(t,e,r){let o=t.message?t.message:to(t.inst?._zod.def?.error?.(t))??to(e?.error?.(t))??to(r.customError?.(t))??to(r.localeError?.(t))??"Invalid input",{inst:n,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=o,e?.reportInput&&(a.input=i),a}function ll(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function so(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function yi(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Sr(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function Vy(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function dl(t){let e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}function pl(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Hy(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return dl(e+r)}function Jy(t){return pl(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function By(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)r[o/2]=Number.parseInt(e.slice(o,o+2),16);return r}function Wy(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var li=class{constructor(...e){}};var fl=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,br,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Pn=y("$ZodError",fl),vi=y("$ZodError",fl,{Parent:Error});function wi(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):o.push(e(n));return{formErrors:o,fieldErrors:r}}function bi(t,e=r=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u<a.length;){let l=a[u];u===a.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(e(i))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return o(t),r}var En=t=>(e,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new nt;if(i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Fe(c,s,Ce())));throw kn(a,n?.callee),a}return i.value};var Tn=t=>async(e,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(n?.Err??t)(i.issues.map(c=>Fe(c,s,Ce())));throw kn(a,n?.callee),a}return i.value};var io=t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new nt;return s.issues.length?{success:!1,error:new(t??Pn)(s.issues.map(i=>Fe(i,n,Ce())))}:{success:!0,data:s.value}},ao=io(vi),co=t=>async(e,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Fe(i,n,Ce())))}:{success:!0,data:s.value}},Rn=co(vi),hl=t=>(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return En(t)(e,r,n)};var ml=t=>(e,r,o)=>En(t)(e,r,o);var gl=t=>async(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Tn(t)(e,r,n)};var _l=t=>async(e,r,o)=>Tn(t)(e,r,o);var yl=t=>(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return io(t)(e,r,n)};var vl=t=>(e,r,o)=>io(t)(e,r,o);var wl=t=>async(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return co(t)(e,r,n)};var bl=t=>async(e,r,o)=>co(t)(e,r,o);var $l=/^[cC][0-9a-z]{6,}$/,Sl=/^[0-9a-z]+$/,xl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kl=/^[0-9a-vA-V]{20}$/,zl=/^[A-Za-z0-9]{27}$/,Pl=/^[a-zA-Z0-9_-]{21}$/,El=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Tl=/^([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})$/,$i=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/;var Rl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Gy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Il(){return new RegExp(Gy,"u")}var Cl=/^(?:(?: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])$/,Ol=/^(([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}|:))$/;var Al=/^((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])$/,Nl=/^(([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])$/,Ml=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Si=/^[A-Za-z0-9_-]*$/;var jl=/^https?$/,Zl=/^\+[1-9]\d{6,14}$/,Dl="(?:(?:\\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])))",ql=new RegExp(`^${Dl}$`);function Ll(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ul(t){return new RegExp(`^${Ll(t)}$`)}function Fl(t){let e=Ll({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${e}(?:${r.join("|")})`;return new RegExp(`^${Dl}T(?:${o})$`)}var Vl=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Hl=/^-?\d+n?$/,Jl=/^-?\d+$/,xi=/^-?\d+(?:\.\d+)?$/,Bl=/^(?:true|false)$/i,Wl=/^null$/i;var Kl=/^[^A-Z]*$/,Gl=/^[^a-z]*$/;var _e=y("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Yl={number:"number",bigint:"bigint",object:"date"},ki=y("$ZodCheckLessThan",(t,e)=>{_e.init(t,e);let r=Yl[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zi=y("$ZodCheckGreaterThan",(t,e)=>{_e.init(t,e);let r=Yl[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Xl=y("$ZodCheckMultipleOf",(t,e)=>{_e.init(t,e),t._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):di(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ql=y("$ZodCheckNumberFormat",(t,e)=>{_e.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),o=r?"int":"number",[n,s]=gi[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=n,a.maximum=s,r&&(a.pattern=Jl)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}a<n&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var ed=y("$ZodCheckMaxLength",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let n=o.value;if(n.length<=e.maximum)return;let i=so(n);o.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),td=y("$ZodCheckMinLength",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let n=o.value;if(n.length>=e.minimum)return;let i=so(n);o.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),rd=y("$ZodCheckLengthEquals",(t,e)=>{var r;_e.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!oo(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=o=>{let n=o.value,s=n.length;if(s===e.length)return;let i=so(n),a=s>e.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),lo=y("$ZodCheckStringFormat",(t,e)=>{var r,o;_e.init(t,e),t._zod.onattach.push(n=>{let s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),od=y("$ZodCheckRegex",(t,e)=>{lo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),nd=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Kl),lo.init(t,e)}),sd=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Gl),lo.init(t,e)}),id=y("$ZodCheckIncludes",(t,e)=>{_e.init(t,e);let r=mt(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),ad=y("$ZodCheckStartsWith",(t,e)=>{_e.init(t,e);let r=new RegExp(`^${mt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),cd=y("$ZodCheckEndsWith",(t,e)=>{_e.init(t,e);let r=new RegExp(`.*${mt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});var ud=y("$ZodCheckOverwrite",(t,e)=>{_e.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var In=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
|
|
32
32
|
`).filter(i=>i),n=Math.min(...o.map(i=>i.length-i.trimStart().length)),s=o.map(i=>i.slice(n)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,n=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
|
|
33
|
-
`))}};var dd={major:4,minor:4,patch:3};var G=y("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=dd;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let n of o)for(let s of n._zod.onattach)s(t);if(o.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let n=(i,a,c)=>{let u=Ct(i),l;for(let d of a){if(d._zod.def.when){if(_i(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new nt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Ct(i,p)))});else{if(i.issues.length===p)continue;u||(u=Ct(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Ct(i))return i.aborted=!0,i;let u=n(a,o,c);if(u instanceof Promise){if(c.async===!1)throw new nt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new nt;return c.then(u=>n(u,o,a))}return n(c,o,a)}}W(t,"~standard",()=>({validate:n=>{try{let s=ao(t,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Rn(t,n).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),An=y("$ZodString",(t,e)=>{G.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Vl(t._zod.bag),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),re=y("$ZodStringFormat",(t,e)=>{lo.init(t,e),An.init(t,e)}),wd=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Tl),re.init(t,e)}),bd=y("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=$i(o))}else e.pattern??(e.pattern=$i());re.init(t,e)}),$d=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Rl),re.init(t,e)}),Sd=y("$ZodURL",(t,e)=>{re.init(t,e),t._zod.check=r=>{try{let o=r.value.trim();if(!e.normalize&&e.protocol?.source===jl.source&&!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let n=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),xd=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Il()),re.init(t,e)}),kd=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Pl),re.init(t,e)}),zd=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$l),re.init(t,e)}),Pd=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Sl),re.init(t,e)}),Ed=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=xl),re.init(t,e)}),Td=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=kl),re.init(t,e)}),Rd=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=zl),re.init(t,e)}),Id=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Fl(e)),re.init(t,e)}),Cd=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ql),re.init(t,e)}),Od=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ul(e)),re.init(t,e)}),Ad=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=El),re.init(t,e)}),Nd=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Cl),re.init(t,e),t._zod.bag.format="ipv4"}),Md=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ol),re.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var jd=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Al),re.init(t,e)}),Zd=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Nl),re.init(t,e),t._zod.check=r=>{let o=r.value.split("/");try{if(o.length!==2)throw new Error;let[n,s]=o;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Dd(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var qd=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ml),re.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Dd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Xy(t){if(!Si.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Dd(r)}var Ld=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Si),re.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{Xy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ud=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Zl),re.init(t,e)});function Qy(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}var Fd=y("$ZodJWT",(t,e)=>{re.init(t,e),t._zod.check=r=>{Qy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Ei=y("$ZodNumber",(t,e)=>{G.init(t,e),t._zod.pattern=t._zod.bag.pattern??xi,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Vd=y("$ZodNumberFormat",(t,e)=>{Ql.init(t,e),Ei.init(t,e)}),Hd=y("$ZodBoolean",(t,e)=>{G.init(t,e),t._zod.pattern=Bl,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Jd=y("$ZodBigInt",(t,e)=>{G.init(t,e),t._zod.pattern=Hl,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var Bd=y("$ZodNull",(t,e)=>{G.init(t,e),t._zod.pattern=Wl,t._zod.values=new Set([null]),t._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Wd=y("$ZodAny",(t,e)=>{G.init(t,e),t._zod.parse=r=>r}),Kd=y("$ZodUnknown",(t,e)=>{G.init(t,e),t._zod.parse=r=>r}),Gd=y("$ZodNever",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Yd=y("$ZodDate",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,s=n instanceof Date;return s&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...s?{received:"Invalid Date"}:{},inst:t}),r}});function pd(t,e,r){t.issues.length&&e.issues.push(...gt(r,t.issues)),e.value[r]=t.value}var Xd=y("$ZodArray",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=e.element._zod.run({value:a,issues:[]},o);c instanceof Promise?s.push(c.then(u=>pd(u,r,i))):pd(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function On(t,e,r,o,n,s){let i=r in o;if(t.issues.length){if(n&&s&&!i)return;e.issues.push(...gt(r,t.issues))}if(!i&&!n){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Qd(t){let e=Object.keys(t.shape);for(let o of e)if(!t.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=mi(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function ep(t,e,r,o,n,s){let i=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},o);f instanceof Promise?t.push(f.then(h=>On(h,r,p,e,l,d))):On(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var ev=y("$ZodObject",(t,e)=>{if(G.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let o=$r(()=>Qd(e));W(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let n=Xt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],h=f._zod.optin==="optional",g=f._zod.optout==="optional",_=f._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?l.push(_.then(w=>On(w,a,p,u,h,g))):On(_,a,p,u,h,g)}return s?ep(l,u,a,c,o.value,t):l.length?Promise.all(l).then(()=>a):a}}),tp=y("$ZodObjectJIT",(t,e)=>{ev.init(t,e);let r=t._zod.parse,o=$r(()=>Qd(e)),n=p=>{let f=new In(["shape","payload","ctx"]),h=o.value,g=z=>{let E=xn(z);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");let _=Object.create(null),w=0;for(let z of h.keys)_[z]=`key_${w++}`;f.write("const newResult = {};");for(let z of h.keys){let E=_[z],v=xn(z),$=p[z],O=$?._zod?.optin==="optional",K=$?._zod?.optout==="optional";f.write(`const ${E} = ${g(z)};`),O&&K?f.write(`
|
|
33
|
+
`))}};var dd={major:4,minor:4,patch:3};var G=y("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=dd;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let n of o)for(let s of n._zod.onattach)s(t);if(o.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let n=(i,a,c)=>{let u=Ct(i),l;for(let d of a){if(d._zod.def.when){if(_i(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new nt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Ct(i,p)))});else{if(i.issues.length===p)continue;u||(u=Ct(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Ct(i))return i.aborted=!0,i;let u=n(a,o,c);if(u instanceof Promise){if(c.async===!1)throw new nt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new nt;return c.then(u=>n(u,o,a))}return n(c,o,a)}}W(t,"~standard",()=>({validate:n=>{try{let s=ao(t,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Rn(t,n).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),An=y("$ZodString",(t,e)=>{G.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Vl(t._zod.bag),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),re=y("$ZodStringFormat",(t,e)=>{lo.init(t,e),An.init(t,e)}),wd=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Tl),re.init(t,e)}),bd=y("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=$i(o))}else e.pattern??(e.pattern=$i());re.init(t,e)}),$d=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Rl),re.init(t,e)}),Sd=y("$ZodURL",(t,e)=>{re.init(t,e),t._zod.check=r=>{try{let o=r.value.trim();if(!e.normalize&&e.protocol?.source===jl.source&&!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let n=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),xd=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Il()),re.init(t,e)}),kd=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Pl),re.init(t,e)}),zd=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$l),re.init(t,e)}),Pd=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Sl),re.init(t,e)}),Ed=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=xl),re.init(t,e)}),Td=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=kl),re.init(t,e)}),Rd=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=zl),re.init(t,e)}),Id=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Fl(e)),re.init(t,e)}),Cd=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ql),re.init(t,e)}),Od=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ul(e)),re.init(t,e)}),Ad=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=El),re.init(t,e)}),Nd=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Cl),re.init(t,e),t._zod.bag.format="ipv4"}),Md=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ol),re.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var jd=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Al),re.init(t,e)}),Zd=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Nl),re.init(t,e),t._zod.check=r=>{let o=r.value.split("/");try{if(o.length!==2)throw new Error;let[n,s]=o;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Dd(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var qd=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ml),re.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Dd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Qy(t){if(!Si.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Dd(r)}var Ld=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Si),re.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{Qy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ud=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Zl),re.init(t,e)});function ev(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}var Fd=y("$ZodJWT",(t,e)=>{re.init(t,e),t._zod.check=r=>{ev(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Ei=y("$ZodNumber",(t,e)=>{G.init(t,e),t._zod.pattern=t._zod.bag.pattern??xi,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Vd=y("$ZodNumberFormat",(t,e)=>{Ql.init(t,e),Ei.init(t,e)}),Hd=y("$ZodBoolean",(t,e)=>{G.init(t,e),t._zod.pattern=Bl,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Jd=y("$ZodBigInt",(t,e)=>{G.init(t,e),t._zod.pattern=Hl,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var Bd=y("$ZodNull",(t,e)=>{G.init(t,e),t._zod.pattern=Wl,t._zod.values=new Set([null]),t._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Wd=y("$ZodAny",(t,e)=>{G.init(t,e),t._zod.parse=r=>r}),Kd=y("$ZodUnknown",(t,e)=>{G.init(t,e),t._zod.parse=r=>r}),Gd=y("$ZodNever",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Yd=y("$ZodDate",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,s=n instanceof Date;return s&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...s?{received:"Invalid Date"}:{},inst:t}),r}});function pd(t,e,r){t.issues.length&&e.issues.push(...gt(r,t.issues)),e.value[r]=t.value}var Xd=y("$ZodArray",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=e.element._zod.run({value:a,issues:[]},o);c instanceof Promise?s.push(c.then(u=>pd(u,r,i))):pd(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function On(t,e,r,o,n,s){let i=r in o;if(t.issues.length){if(n&&s&&!i)return;e.issues.push(...gt(r,t.issues))}if(!i&&!n){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Qd(t){let e=Object.keys(t.shape);for(let o of e)if(!t.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=mi(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function ep(t,e,r,o,n,s){let i=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},o);f instanceof Promise?t.push(f.then(h=>On(h,r,p,e,l,d))):On(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var tv=y("$ZodObject",(t,e)=>{if(G.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let o=$r(()=>Qd(e));W(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let n=Xt,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],h=f._zod.optin==="optional",g=f._zod.optout==="optional",_=f._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?l.push(_.then(w=>On(w,a,p,u,h,g))):On(_,a,p,u,h,g)}return s?ep(l,u,a,c,o.value,t):l.length?Promise.all(l).then(()=>a):a}}),tp=y("$ZodObjectJIT",(t,e)=>{tv.init(t,e);let r=t._zod.parse,o=$r(()=>Qd(e)),n=p=>{let f=new In(["shape","payload","ctx"]),h=o.value,g=z=>{let E=xn(z);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");let _=Object.create(null),w=0;for(let z of h.keys)_[z]=`key_${w++}`;f.write("const newResult = {};");for(let z of h.keys){let E=_[z],v=xn(z),$=p[z],O=$?._zod?.optin==="optional",K=$?._zod?.optout==="optional";f.write(`const ${E} = ${g(z)};`),O&&K?f.write(`
|
|
34
34
|
if (${E}.issues.length) {
|
|
35
35
|
if (${v} in input) {
|
|
36
36
|
payload.issues = payload.issues.concat(${E}.issues.map(iss => ({
|
|
@@ -89,23 +89,23 @@
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
`)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(z,E)=>b(p,z,E)},s,i=Xt,a=!wr.jitless,u=a&&fi.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=o.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=n(e.shape)),p=s(p,f),l?ep([],h,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function fd(t,e,r,o){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let n=t.filter(s=>!Ct(s));return n.length===1?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Fe(i,o,Ce())))}),e)}var Ti=y("$ZodUnion",(t,e)=>{G.init(t,e),W(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),W(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),W(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),W(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){let o=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${o.map(n=>no(n.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:o.value,issues:[]},n);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>fd(a,o,t,n)):fd(i,o,t,n)}});var rp=y("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ti.init(t,e);let r=t._zod.parse;W(t._zod,"propValues",()=>{let n={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){n[a]||(n[a]=new Set);for(let u of c)n[a].add(u)}}return n});let o=$r(()=>{let n=e.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(n,s)=>{let i=n.value;if(!Xt(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),n;let a=o.value.get(i?.[e.discriminator]);return a?a._zod.run(n,s):e.unionFallback||s.direction==="backward"?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:i,path:[e.discriminator],inst:t}),n)}}),op=y("$ZodIntersection",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value,s=e.left._zod.run({value:n,issues:[]},o),i=e.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>hd(r,c,u)):hd(r,s,i)}});function Pi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(It(t)&&It(e)){let r=Object.keys(e),o=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(let s of o){let i=Pi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<t.length;o++){let n=t[o],s=e[o],i=Pi(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hd(t,e,r){let o=new Map,n;for(let a of e.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).r=!0;else t.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n&&t.issues.push({...n,keys:s}),Ct(t))return t;let i=Pi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var np=y("$ZodRecord",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!It(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>Fe(f,o,Ce())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:n[u],issues:[]},o);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...gt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...gt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in n)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xi.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Fe(d,o,Ce())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:n[a],issues:[]},o);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...gt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...gt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var sp=y("$ZodEnum",(t,e)=>{G.init(t,e);let r=ro(e.entries),o=new Set(r);t._zod.values=o,t._zod.pattern=new RegExp(`^(${r.filter(n=>hi.has(typeof n)).map(n=>typeof n=="string"?mt(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let i=n.value;return o.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),ip=y("$ZodLiteral",(t,e)=>{if(G.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?mt(o):o?mt(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,n)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),o}});var ap=y("$ZodTransform",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vr(t.constructor.name);let n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(i=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new nt;return r.value=n,r.fallback=!0,r}});function md(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Ri=y("$ZodOptional",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.optout="optional",W(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),W(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${no(r.source)})?$`):void 0}),t._zod.parse=(r,o)=>{if(e.innerType._zod.optin==="optional"){let n=r.value,s=e.innerType._zod.run(r,o);return s instanceof Promise?s.then(i=>md(i,n)):md(s,n)}return r.value===void 0?r:e.innerType._zod.run(r,o)}}),cp=y("$ZodExactOptional",(t,e)=>{Ri.init(t,e),W(t._zod,"values",()=>e.innerType._zod.values),W(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,o)=>e.innerType._zod.run(r,o)}),up=y("$ZodNullable",(t,e)=>{G.init(t,e),W(t._zod,"optin",()=>e.innerType._zod.optin),W(t._zod,"optout",()=>e.innerType._zod.optout),W(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${no(r.source)}|null)$`):void 0}),W(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,o)=>r.value===null?r:e.innerType._zod.run(r,o)}),lp=y("$ZodDefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);if(r.value===void 0)return r.value=e.defaultValue,r;let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>gd(s,e)):gd(n,e)}});function gd(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var dp=y("$ZodPrefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>(o.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,o))}),pp=y("$ZodNonOptional",(t,e)=>{G.init(t,e),W(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>_d(s,t)):_d(n,t)}});function _d(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var fp=y("$ZodCatch",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"optout",()=>e.innerType._zod.optout),W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Fe(i,o,Ce()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Fe(s,o,Ce()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Ii=y("$ZodPipe",(t,e)=>{G.init(t,e),W(t._zod,"values",()=>e.in._zod.values),W(t._zod,"optin",()=>e.in._zod.optin),W(t._zod,"optout",()=>e.out._zod.optout),W(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=e.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Cn(i,e.in,o)):Cn(s,e.in,o)}let n=e.in._zod.run(r,o);return n instanceof Promise?n.then(s=>Cn(s,e.out,o)):Cn(n,e.out,o)}});function Cn(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var hp=y("$ZodPreprocess",(t,e)=>{Ii.init(t,e)}),mp=y("$ZodReadonly",(t,e)=>{G.init(t,e),W(t._zod,"propValues",()=>e.innerType._zod.propValues),W(t._zod,"values",()=>e.innerType._zod.values),W(t._zod,"optin",()=>e.innerType?._zod?.optin),W(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(yd):yd(n)}});function yd(t){return t.value=Object.freeze(t.value),t}var gp=y("$ZodCustom",(t,e)=>{_e.init(t,e),G.init(t,e),t._zod.parse=(r,o)=>r,t._zod.check=r=>{let o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(s=>vd(s,r,o,t));vd(n,r,o,t)}});function vd(t,e,r,o){if(!t){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),e.issues.push(Sr(n))}}var tv=()=>{let t={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 e(n){return t[n]??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"},o={nan:"NaN"};return n=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=yi(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return n.values.length===1?`Invalid input: expected ${zn(n.values[0])}`:`Invalid option: expected one of ${Sn(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Sn(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return n.options&&Array.isArray(n.options)&&n.options.length>0?`Invalid discriminator value. Expected ${n.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function _p(){return{localeError:tv()}}var yp;var Ci=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let o=r[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let o={...this.get(r)??{}};delete o.id;let n={...o,...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 vp(){return new Ci}(yp=globalThis).__zod_globalRegistry??(yp.__zod_globalRegistry=vp());var Ot=globalThis.__zod_globalRegistry;function wp(t,e){return new t({type:"string",...I(e)})}function bp(t,e){return new t({type:"string",coerce:!0,...I(e)})}function $p(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Oi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function Sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function xp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function kp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function zp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Ai(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Pp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function Ep(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Rp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Ip(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Cp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Op(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Ap(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function Np(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Mp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function jp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Zp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function qp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Lp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Up(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Fp(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Vp(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Hp(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Jp(t,e){return new t({type:"number",checks:[],...I(e)})}function Bp(t,e){return new t({type:"number",coerce:!0,checks:[],...I(e)})}function Wp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Kp(t,e){return new t({type:"boolean",...I(e)})}function Gp(t,e){return new t({type:"boolean",coerce:!0,...I(e)})}function Yp(t,e){return new t({type:"bigint",coerce:!0,...I(e)})}function Xp(t,e){return new t({type:"null",...I(e)})}function Qp(t){return new t({type:"any"})}function ef(t){return new t({type:"unknown"})}function tf(t,e){return new t({type:"never",...I(e)})}function rf(t,e){return new t({type:"date",coerce:!0,...I(e)})}function xr(t,e){return new ki({check:"less_than",...I(e),value:t,inclusive:!1})}function _t(t,e){return new ki({check:"less_than",...I(e),value:t,inclusive:!0})}function kr(t,e){return new zi({check:"greater_than",...I(e),value:t,inclusive:!1})}function Ye(t,e){return new zi({check:"greater_than",...I(e),value:t,inclusive:!0})}function po(t,e){return new Xl({check:"multiple_of",...I(e),value:t})}function Nn(t,e){return new ed({check:"max_length",...I(e),maximum:t})}function zr(t,e){return new td({check:"min_length",...I(e),minimum:t})}function Mn(t,e){return new rd({check:"length_equals",...I(e),length:t})}function Ni(t,e){return new od({check:"string_format",format:"regex",...I(e),pattern:t})}function Mi(t){return new nd({check:"string_format",format:"lowercase",...I(t)})}function ji(t){return new sd({check:"string_format",format:"uppercase",...I(t)})}function Zi(t,e){return new id({check:"string_format",format:"includes",...I(e),includes:t})}function Di(t,e){return new ad({check:"string_format",format:"starts_with",...I(e),prefix:t})}function qi(t,e){return new cd({check:"string_format",format:"ends_with",...I(e),suffix:t})}function At(t){return new ud({check:"overwrite",tx:t})}function Li(t){return At(e=>e.normalize(t))}function Ui(){return At(t=>t.trim())}function Fi(){return At(t=>t.toLowerCase())}function Vi(){return At(t=>t.toUpperCase())}function Hi(){return At(t=>pi(t))}function of(t,e,r){return new t({type:"array",element:e,...I(r)})}function nf(t,e,r){let o=I(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function sf(t,e,r){return new t({type:"custom",check:"custom",fn:e,...I(r)})}function af(t,e){let r=rv(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Sr(n,o.value,r._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(Sr(s))}},t(o.value,o)),e);return r}function rv(t,e){let r=new _e({check:"custom",...I(e)});return r._zod.check=t,r}function Ji(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ot,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function pe(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),pe(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&Pe(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((o=i.schema).default??(o.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Bi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=o.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=n(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
92
|
+
`)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(z,E)=>b(p,z,E)},s,i=Xt,a=!wr.jitless,u=a&&fi.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=o.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=n(e.shape)),p=s(p,f),l?ep([],h,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function fd(t,e,r,o){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let n=t.filter(s=>!Ct(s));return n.length===1?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Fe(i,o,Ce())))}),e)}var Ti=y("$ZodUnion",(t,e)=>{G.init(t,e),W(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),W(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),W(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),W(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){let o=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${o.map(n=>no(n.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:o.value,issues:[]},n);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>fd(a,o,t,n)):fd(i,o,t,n)}});var rp=y("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ti.init(t,e);let r=t._zod.parse;W(t._zod,"propValues",()=>{let n={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){n[a]||(n[a]=new Set);for(let u of c)n[a].add(u)}}return n});let o=$r(()=>{let n=e.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(n,s)=>{let i=n.value;if(!Xt(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),n;let a=o.value.get(i?.[e.discriminator]);return a?a._zod.run(n,s):e.unionFallback||s.direction==="backward"?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:i,path:[e.discriminator],inst:t}),n)}}),op=y("$ZodIntersection",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value,s=e.left._zod.run({value:n,issues:[]},o),i=e.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>hd(r,c,u)):hd(r,s,i)}});function Pi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(It(t)&&It(e)){let r=Object.keys(e),o=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(let s of o){let i=Pi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<t.length;o++){let n=t[o],s=e[o],i=Pi(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hd(t,e,r){let o=new Map,n;for(let a of e.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)o.has(c)||o.set(c,{}),o.get(c).r=!0;else t.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n&&t.issues.push({...n,keys:s}),Ct(t))return t;let i=Pi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var np=y("$ZodRecord",(t,e)=>{G.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!It(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>Fe(f,o,Ce())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:n[u],issues:[]},o);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...gt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...gt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in n)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xi.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Fe(d,o,Ce())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:n[a],issues:[]},o);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...gt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...gt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var sp=y("$ZodEnum",(t,e)=>{G.init(t,e);let r=ro(e.entries),o=new Set(r);t._zod.values=o,t._zod.pattern=new RegExp(`^(${r.filter(n=>hi.has(typeof n)).map(n=>typeof n=="string"?mt(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let i=n.value;return o.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),ip=y("$ZodLiteral",(t,e)=>{if(G.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?mt(o):o?mt(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,n)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),o}});var ap=y("$ZodTransform",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vr(t.constructor.name);let n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(i=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new nt;return r.value=n,r.fallback=!0,r}});function md(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Ri=y("$ZodOptional",(t,e)=>{G.init(t,e),t._zod.optin="optional",t._zod.optout="optional",W(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),W(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${no(r.source)})?$`):void 0}),t._zod.parse=(r,o)=>{if(e.innerType._zod.optin==="optional"){let n=r.value,s=e.innerType._zod.run(r,o);return s instanceof Promise?s.then(i=>md(i,n)):md(s,n)}return r.value===void 0?r:e.innerType._zod.run(r,o)}}),cp=y("$ZodExactOptional",(t,e)=>{Ri.init(t,e),W(t._zod,"values",()=>e.innerType._zod.values),W(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,o)=>e.innerType._zod.run(r,o)}),up=y("$ZodNullable",(t,e)=>{G.init(t,e),W(t._zod,"optin",()=>e.innerType._zod.optin),W(t._zod,"optout",()=>e.innerType._zod.optout),W(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${no(r.source)}|null)$`):void 0}),W(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,o)=>r.value===null?r:e.innerType._zod.run(r,o)}),lp=y("$ZodDefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);if(r.value===void 0)return r.value=e.defaultValue,r;let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>gd(s,e)):gd(n,e)}});function gd(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var dp=y("$ZodPrefault",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>(o.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,o))}),pp=y("$ZodNonOptional",(t,e)=>{G.init(t,e),W(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>_d(s,t)):_d(n,t)}});function _d(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var fp=y("$ZodCatch",(t,e)=>{G.init(t,e),t._zod.optin="optional",W(t._zod,"optout",()=>e.innerType._zod.optout),W(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Fe(i,o,Ce()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Fe(s,o,Ce()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Ii=y("$ZodPipe",(t,e)=>{G.init(t,e),W(t._zod,"values",()=>e.in._zod.values),W(t._zod,"optin",()=>e.in._zod.optin),W(t._zod,"optout",()=>e.out._zod.optout),W(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=e.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Cn(i,e.in,o)):Cn(s,e.in,o)}let n=e.in._zod.run(r,o);return n instanceof Promise?n.then(s=>Cn(s,e.out,o)):Cn(n,e.out,o)}});function Cn(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var hp=y("$ZodPreprocess",(t,e)=>{Ii.init(t,e)}),mp=y("$ZodReadonly",(t,e)=>{G.init(t,e),W(t._zod,"propValues",()=>e.innerType._zod.propValues),W(t._zod,"values",()=>e.innerType._zod.values),W(t._zod,"optin",()=>e.innerType?._zod?.optin),W(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,o)=>{if(o.direction==="backward")return e.innerType._zod.run(r,o);let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(yd):yd(n)}});function yd(t){return t.value=Object.freeze(t.value),t}var gp=y("$ZodCustom",(t,e)=>{_e.init(t,e),G.init(t,e),t._zod.parse=(r,o)=>r,t._zod.check=r=>{let o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(s=>vd(s,r,o,t));vd(n,r,o,t)}});function vd(t,e,r,o){if(!t){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),e.issues.push(Sr(n))}}var rv=()=>{let t={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 e(n){return t[n]??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"},o={nan:"NaN"};return n=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=yi(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return n.values.length===1?`Invalid input: expected ${zn(n.values[0])}`:`Invalid option: expected one of ${Sn(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Sn(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return n.options&&Array.isArray(n.options)&&n.options.length>0?`Invalid discriminator value. Expected ${n.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function _p(){return{localeError:rv()}}var yp;var Ci=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let o=r[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let o={...this.get(r)??{}};delete o.id;let n={...o,...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 vp(){return new Ci}(yp=globalThis).__zod_globalRegistry??(yp.__zod_globalRegistry=vp());var Ot=globalThis.__zod_globalRegistry;function wp(t,e){return new t({type:"string",...I(e)})}function bp(t,e){return new t({type:"string",coerce:!0,...I(e)})}function $p(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Oi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function Sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function xp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function kp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function zp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Ai(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Pp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function Ep(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Rp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Ip(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Cp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Op(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function Ap(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function Np(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function Mp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function jp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Zp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function qp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function Lp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function Up(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Fp(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Vp(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Hp(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Jp(t,e){return new t({type:"number",checks:[],...I(e)})}function Bp(t,e){return new t({type:"number",coerce:!0,checks:[],...I(e)})}function Wp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Kp(t,e){return new t({type:"boolean",...I(e)})}function Gp(t,e){return new t({type:"boolean",coerce:!0,...I(e)})}function Yp(t,e){return new t({type:"bigint",coerce:!0,...I(e)})}function Xp(t,e){return new t({type:"null",...I(e)})}function Qp(t){return new t({type:"any"})}function ef(t){return new t({type:"unknown"})}function tf(t,e){return new t({type:"never",...I(e)})}function rf(t,e){return new t({type:"date",coerce:!0,...I(e)})}function xr(t,e){return new ki({check:"less_than",...I(e),value:t,inclusive:!1})}function _t(t,e){return new ki({check:"less_than",...I(e),value:t,inclusive:!0})}function kr(t,e){return new zi({check:"greater_than",...I(e),value:t,inclusive:!1})}function Ye(t,e){return new zi({check:"greater_than",...I(e),value:t,inclusive:!0})}function po(t,e){return new Xl({check:"multiple_of",...I(e),value:t})}function Nn(t,e){return new ed({check:"max_length",...I(e),maximum:t})}function zr(t,e){return new td({check:"min_length",...I(e),minimum:t})}function Mn(t,e){return new rd({check:"length_equals",...I(e),length:t})}function Ni(t,e){return new od({check:"string_format",format:"regex",...I(e),pattern:t})}function Mi(t){return new nd({check:"string_format",format:"lowercase",...I(t)})}function ji(t){return new sd({check:"string_format",format:"uppercase",...I(t)})}function Zi(t,e){return new id({check:"string_format",format:"includes",...I(e),includes:t})}function Di(t,e){return new ad({check:"string_format",format:"starts_with",...I(e),prefix:t})}function qi(t,e){return new cd({check:"string_format",format:"ends_with",...I(e),suffix:t})}function At(t){return new ud({check:"overwrite",tx:t})}function Li(t){return At(e=>e.normalize(t))}function Ui(){return At(t=>t.trim())}function Fi(){return At(t=>t.toLowerCase())}function Vi(){return At(t=>t.toUpperCase())}function Hi(){return At(t=>pi(t))}function of(t,e,r){return new t({type:"array",element:e,...I(r)})}function nf(t,e,r){let o=I(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function sf(t,e,r){return new t({type:"custom",check:"custom",fn:e,...I(r)})}function af(t,e){let r=ov(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Sr(n,o.value,r._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(Sr(s))}},t(o.value,o)),e);return r}function ov(t,e){let r=new _e({check:"custom",...I(e)});return r._zod.check=t,r}function Ji(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ot,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function pe(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),pe(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&Pe(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((o=i.schema).default??(o.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Bi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=o.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=n(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
93
93
|
|
|
94
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Wi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,l),a._zod.parent===d)for(let _ in u)_==="$ref"||_==="allOf"||_ in l||delete u[_];if(h.$ref&&f.def)for(let _ in u)_==="$ref"||_==="allOf"||_ in f.def&&JSON.stringify(u[_])===JSON.stringify(f.def[_])&&delete u[_]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())o(a[0]);let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Object.assign(n,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&n.id===s&&delete n.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:fo(e,"input",t.processors),output:fo(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Pe(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Pe(o.element,r);if(o.type==="set")return Pe(o.valueType,r);if(o.type==="lazy")return Pe(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Pe(o.innerType,r);if(o.type==="intersection")return Pe(o.left,r)||Pe(o.right,r);if(o.type==="record"||o.type==="map")return Pe(o.keyType,r)||Pe(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Pe(o.in,r)||Pe(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Pe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Pe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Pe(n,r))return!0;return!!(o.rest&&Pe(o.rest,r))}return!1}var cf=(t,e={})=>r=>{let o=Ji({...r,processors:e});return pe(t,o),Bi(o,t),Wi(o,t)},fo=(t,e,r={})=>o=>{let{libraryOptions:n,target:s}=o??{},i=Ji({...n??{},target:s,io:e,processors:r});return pe(t,i),Bi(i,t),Wi(i,t)};var ov={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uf=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(n.minLength=s),typeof i=="number"&&(n.maxLength=i),a&&(n.format=ov[a]??a,n.format===""&&delete n.format,a==="time"&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?n.pattern=l[0].source:l.length>1&&(n.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},lf=(t,e,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?n.type="integer":n.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof s=="number"&&(n.minimum=s),p?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof i=="number"&&(n.maximum=i),typeof c=="number"&&(n.multipleOf=c)},df=(t,e,r,o)=>{r.type="boolean"},pf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var ff=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var hf=(t,e,r,o)=>{r.not={}},mf=(t,e,r,o)=>{},gf=(t,e,r,o)=>{},_f=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},yf=(t,e,r,o)=>{let n=t._zod.def,s=ro(n.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},vf=(t,e,r,o)=>{let n=t._zod.def,s=[];for(let i of n.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var wf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var bf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var $f=(t,e,r,o)=>{let n=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(n.minItems=i),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=pe(s.element,e,{...o,path:[...o.path,"items"]})},Sf=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=pe(i[u],e,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(n.required=Array.from(c)),s.catchall?._zod.def.type==="never"?n.additionalProperties=!1:s.catchall?s.catchall&&(n.additionalProperties=pe(s.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},xf=(t,e,r,o)=>{let n=t._zod.def,s=n.inclusive===!1,i=n.options.map((a,c)=>pe(a,e,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},kf=(t,e,r,o)=>{let n=t._zod.def,s=pe(n.left,e,{...o,path:[...o.path,"allOf",0]}),i=pe(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var zf=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=pe(s.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of c)n.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(n.propertyNames=pe(s.keyType,e,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=pe(s.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l)}},Pf=(t,e,r,o)=>{let n=t._zod.def,s=pe(n.innerType,e,o),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Ef=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType},Tf=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Rf=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},If=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Cf=(t,e,r,o)=>{let n=t._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?n.out:n.in:n.out;pe(i,e,o);let a=e.seen.get(t);a.ref=i},Of=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.readOnly=!0};var Ki=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType};function jn(t){return!!t._zod}function Ee(t,e){return jn(t)?ao(t,e):t.safeParse(e)}function Er(t){if(!t)return;let e;if(jn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Tr(t){if(jn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let o=t.value;if(o!==void 0)return o}var ho={};wn(ho,{ZodISODate:()=>Nf,ZodISODateTime:()=>Af,ZodISODuration:()=>jf,ZodISOTime:()=>Mf,date:()=>Yi,datetime:()=>Gi,duration:()=>Qi,time:()=>Xi});var Af=y("ZodISODateTime",(t,e)=>{Id.init(t,e),ce.init(t,e)});function Gi(t){return Up(Af,t)}var Nf=y("ZodISODate",(t,e)=>{Cd.init(t,e),ce.init(t,e)});function Yi(t){return Fp(Nf,t)}var Mf=y("ZodISOTime",(t,e)=>{Od.init(t,e),ce.init(t,e)});function Xi(t){return Vp(Mf,t)}var jf=y("ZodISODuration",(t,e)=>{Ad.init(t,e),ce.init(t,e)});function Qi(t){return Hp(jf,t)}var dv=(t,e)=>{Pn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bi(t,r)},flatten:{value:r=>wi(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,br,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,br,2)}},isEmpty:{get(){return t.issues.length===0}}})};var qe=y("ZodError",dv,{Parent:Error});var Df=En(qe),qf=Tn(qe),Lf=io(qe),Uf=co(qe),Ff=hl(qe),Vf=ml(qe),Hf=gl(qe),Jf=_l(qe),Bf=yl(qe),Wf=vl(qe),Kf=wl(qe),Gf=bl(qe);var Yf=new WeakMap;function mo(t,e,r){let o=Object.getPrototypeOf(t),n=Yf.get(o);if(n||(n=new Set,Yf.set(o,n)),!n.has(e)){n.add(e);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var X=y("ZodType",(t,e)=>(G.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:fo(t,"input"),output:fo(t,"output")}}),t.toJSONSchema=cf(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,o)=>Df(t,r,o,{callee:t.parse}),t.safeParse=(r,o)=>Lf(t,r,o),t.parseAsync=async(r,o)=>qf(t,r,o,{callee:t.parseAsync}),t.safeParseAsync=async(r,o)=>Uf(t,r,o),t.spa=t.safeParseAsync,t.encode=(r,o)=>Ff(t,r,o),t.decode=(r,o)=>Vf(t,r,o),t.encodeAsync=async(r,o)=>Hf(t,r,o),t.decodeAsync=async(r,o)=>Jf(t,r,o),t.safeEncode=(r,o)=>Bf(t,r,o),t.safeDecode=(r,o)=>Wf(t,r,o),t.safeEncodeAsync=async(r,o)=>Kf(t,r,o),t.safeDecodeAsync=async(r,o)=>Gf(t,r,o),mo(t,"ZodType",{check(...r){let o=this.def;return this.clone(L.mergeDefs(o,{checks:[...o.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return Ue(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(Qv(r,o))},superRefine(r,o){return this.check(ew(r,o))},overwrite(r){return this.check(At(r))},optional(){return le(this)},exactOptional(){return Lv(this)},nullable(){return th(this)},nullish(){return le(th(this))},nonoptional(r){return Bv(this,r)},array(){return S(this)},or(r){return oe([this,r])},and(r){return qn(this,r)},transform(r){return rh(this,ph(r))},default(r){return Vv(this,r)},prefault(r){return Jv(this,r)},catch(r){return Kv(this,r)},pipe(r){return rh(this,r)},readonly(){return Xv(this)},describe(r){let o=this.clone();return Ot.add(o,{description:r}),o},meta(...r){if(r.length===0)return Ot.get(this);let o=this.clone();return Ot.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ot.get(t)?.description},configurable:!0}),t)),oh=y("_ZodString",(t,e)=>{An.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>uf(t,o,n,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,mo(t,"_ZodString",{regex(...o){return this.check(Ni(...o))},includes(...o){return this.check(Zi(...o))},startsWith(...o){return this.check(Di(...o))},endsWith(...o){return this.check(qi(...o))},min(...o){return this.check(zr(...o))},max(...o){return this.check(Nn(...o))},length(...o){return this.check(Mn(...o))},nonempty(...o){return this.check(zr(1,...o))},lowercase(o){return this.check(Mi(o))},uppercase(o){return this.check(ji(o))},trim(){return this.check(Ui())},normalize(...o){return this.check(Li(...o))},toLowerCase(){return this.check(Fi())},toUpperCase(){return this.check(Vi())},slugify(){return this.check(Hi())}})}),ta=y("ZodString",(t,e)=>{An.init(t,e),oh.init(t,e),t.email=r=>t.check($p(fv,r)),t.url=r=>t.check(Ai(nh,r)),t.jwt=r=>t.check(Lp(Ev,r)),t.emoji=r=>t.check(Pp(hv,r)),t.guid=r=>t.check(Oi(Xf,r)),t.uuid=r=>t.check(Sp(Zn,r)),t.uuidv4=r=>t.check(xp(Zn,r)),t.uuidv6=r=>t.check(kp(Zn,r)),t.uuidv7=r=>t.check(zp(Zn,r)),t.nanoid=r=>t.check(Ep(mv,r)),t.guid=r=>t.check(Oi(Xf,r)),t.cuid=r=>t.check(Tp(gv,r)),t.cuid2=r=>t.check(Rp(_v,r)),t.ulid=r=>t.check(Ip(yv,r)),t.base64=r=>t.check(Zp(kv,r)),t.base64url=r=>t.check(Dp(zv,r)),t.xid=r=>t.check(Cp(vv,r)),t.ksuid=r=>t.check(Op(wv,r)),t.ipv4=r=>t.check(Ap(bv,r)),t.ipv6=r=>t.check(Np($v,r)),t.cidrv4=r=>t.check(Mp(Sv,r)),t.cidrv6=r=>t.check(jp(xv,r)),t.e164=r=>t.check(qp(Pv,r)),t.datetime=r=>t.check(Gi(r)),t.date=r=>t.check(Yi(r)),t.time=r=>t.check(Xi(r)),t.duration=r=>t.check(Qi(r))});function m(t){return wp(ta,t)}var ce=y("ZodStringFormat",(t,e)=>{re.init(t,e),oh.init(t,e)}),fv=y("ZodEmail",(t,e)=>{$d.init(t,e),ce.init(t,e)});var Xf=y("ZodGUID",(t,e)=>{wd.init(t,e),ce.init(t,e)});var Zn=y("ZodUUID",(t,e)=>{bd.init(t,e),ce.init(t,e)});var nh=y("ZodURL",(t,e)=>{Sd.init(t,e),ce.init(t,e)});function sh(t){return Ai(nh,t)}var hv=y("ZodEmoji",(t,e)=>{xd.init(t,e),ce.init(t,e)});var mv=y("ZodNanoID",(t,e)=>{kd.init(t,e),ce.init(t,e)});var gv=y("ZodCUID",(t,e)=>{zd.init(t,e),ce.init(t,e)});var _v=y("ZodCUID2",(t,e)=>{Pd.init(t,e),ce.init(t,e)});var yv=y("ZodULID",(t,e)=>{Ed.init(t,e),ce.init(t,e)});var vv=y("ZodXID",(t,e)=>{Td.init(t,e),ce.init(t,e)});var wv=y("ZodKSUID",(t,e)=>{Rd.init(t,e),ce.init(t,e)});var bv=y("ZodIPv4",(t,e)=>{Nd.init(t,e),ce.init(t,e)});var $v=y("ZodIPv6",(t,e)=>{Md.init(t,e),ce.init(t,e)});var Sv=y("ZodCIDRv4",(t,e)=>{jd.init(t,e),ce.init(t,e)});var xv=y("ZodCIDRv6",(t,e)=>{Zd.init(t,e),ce.init(t,e)});var kv=y("ZodBase64",(t,e)=>{qd.init(t,e),ce.init(t,e)});var zv=y("ZodBase64URL",(t,e)=>{Ld.init(t,e),ce.init(t,e)});var Pv=y("ZodE164",(t,e)=>{Ud.init(t,e),ce.init(t,e)});var Ev=y("ZodJWT",(t,e)=>{Fd.init(t,e),ce.init(t,e)});var Dn=y("ZodNumber",(t,e)=>{Ei.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>lf(t,o,n,s),mo(t,"ZodNumber",{gt(o,n){return this.check(kr(o,n))},gte(o,n){return this.check(Ye(o,n))},min(o,n){return this.check(Ye(o,n))},lt(o,n){return this.check(xr(o,n))},lte(o,n){return this.check(_t(o,n))},max(o,n){return this.check(_t(o,n))},int(o){return this.check(Qf(o))},safe(o){return this.check(Qf(o))},positive(o){return this.check(kr(0,o))},nonnegative(o){return this.check(Ye(0,o))},negative(o){return this.check(xr(0,o))},nonpositive(o){return this.check(_t(0,o))},multipleOf(o,n){return this.check(po(o,n))},step(o,n){return this.check(po(o,n))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function H(t){return Jp(Dn,t)}var Tv=y("ZodNumberFormat",(t,e)=>{Vd.init(t,e),Dn.init(t,e)});function Qf(t){return Wp(Tv,t)}var ra=y("ZodBoolean",(t,e)=>{Hd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>df(t,r,o,n)});function Q(t){return Kp(ra,t)}var ih=y("ZodBigInt",(t,e)=>{Jd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>pf(t,o,n,s),t.gte=(o,n)=>t.check(Ye(o,n)),t.min=(o,n)=>t.check(Ye(o,n)),t.gt=(o,n)=>t.check(kr(o,n)),t.gte=(o,n)=>t.check(Ye(o,n)),t.min=(o,n)=>t.check(Ye(o,n)),t.lt=(o,n)=>t.check(xr(o,n)),t.lte=(o,n)=>t.check(_t(o,n)),t.max=(o,n)=>t.check(_t(o,n)),t.positive=o=>t.check(kr(BigInt(0),o)),t.negative=o=>t.check(xr(BigInt(0),o)),t.nonpositive=o=>t.check(_t(BigInt(0),o)),t.nonnegative=o=>t.check(Ye(BigInt(0),o)),t.multipleOf=(o,n)=>t.check(po(o,n));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var Rv=y("ZodNull",(t,e)=>{Bd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ff(t,r,o,n)});function ah(t){return Xp(Rv,t)}var Iv=y("ZodAny",(t,e)=>{Wd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mf(t,r,o,n)});function ch(){return Qp(Iv)}var Cv=y("ZodUnknown",(t,e)=>{Kd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gf(t,r,o,n)});function ue(){return ef(Cv)}var Ov=y("ZodNever",(t,e)=>{Gd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hf(t,r,o,n)});function Av(t){return tf(Ov,t)}var uh=y("ZodDate",(t,e)=>{Yd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>_f(t,o,n,s),t.min=(o,n)=>t.check(Ye(o,n)),t.max=(o,n)=>t.check(_t(o,n));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var Nv=y("ZodArray",(t,e)=>{Xd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$f(t,r,o,n),t.element=e.element,mo(t,"ZodArray",{min(r,o){return this.check(zr(r,o))},nonempty(r){return this.check(zr(1,r))},max(r,o){return this.check(Nn(r,o))},length(r,o){return this.check(Mn(r,o))},unwrap(){return this.element}})});function S(t,e){return of(Nv,t,e)}var lh=y("ZodObject",(t,e)=>{tp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Sf(t,r,o,n),L.defineLazy(t,"shape",()=>e.shape),mo(t,"ZodObject",{keyof(){return Oe(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ue()})},loose(){return this.clone({...this._zod.def,catchall:ue()})},strict(){return this.clone({...this._zod.def,catchall:Av()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return L.extend(this,r)},safeExtend(r){return L.safeExtend(this,r)},merge(r){return L.merge(this,r)},pick(r){return L.pick(this,r)},omit(r){return L.omit(this,r)},partial(...r){return L.partial(fh,this,r[0])},required(...r){return L.required(hh,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...L.normalizeParams(e)};return new lh(r)}function me(t,e){return new lh({type:"object",shape:t,catchall:ue(),...L.normalizeParams(e)})}var dh=y("ZodUnion",(t,e)=>{Ti.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xf(t,r,o,n),t.options=e.options});function oe(t,e){return new dh({type:"union",options:t,...L.normalizeParams(e)})}var Mv=y("ZodDiscriminatedUnion",(t,e)=>{dh.init(t,e),rp.init(t,e)});function oa(t,e,r){return new Mv({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var jv=y("ZodIntersection",(t,e)=>{op.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kf(t,r,o,n)});function qn(t,e){return new jv({type:"intersection",left:t,right:e})}var eh=y("ZodRecord",(t,e)=>{np.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zf(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function te(t,e,r){return!e||!e._zod?new eh({type:"record",keyType:m(),valueType:t,...L.normalizeParams(e)}):new eh({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var ea=y("ZodEnum",(t,e)=>{sp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>yf(t,o,n,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new ea({...e,checks:[],...L.normalizeParams(n),entries:s})},t.exclude=(o,n)=>{let s={...e.entries};for(let i of o)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new ea({...e,checks:[],...L.normalizeParams(n),entries:s})}});function Oe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new ea({type:"enum",entries:r,...L.normalizeParams(e)})}var Zv=y("ZodLiteral",(t,e)=>{ip.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vf(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function T(t,e){return new Zv({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var Dv=y("ZodTransform",(t,e)=>{ap.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bf(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vr(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(L.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(L.issue(i))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=n,r.fallback=!0,r)}});function ph(t){return new Dv({type:"transform",transform:t})}var fh=y("ZodOptional",(t,e)=>{Ri.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ki(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function le(t){return new fh({type:"optional",innerType:t})}var qv=y("ZodExactOptional",(t,e)=>{cp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ki(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Lv(t){return new qv({type:"optional",innerType:t})}var Uv=y("ZodNullable",(t,e)=>{up.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Pf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function th(t){return new Uv({type:"nullable",innerType:t})}var Fv=y("ZodDefault",(t,e)=>{lp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Vv(t,e){return new Fv({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Hv=y("ZodPrefault",(t,e)=>{dp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Rf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Jv(t,e){return new Hv({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var hh=y("ZodNonOptional",(t,e)=>{pp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ef(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Bv(t,e){return new hh({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var Wv=y("ZodCatch",(t,e)=>{fp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>If(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Kv(t,e){return new Wv({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var mh=y("ZodPipe",(t,e)=>{Ii.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Cf(t,r,o,n),t.in=e.in,t.out=e.out});function rh(t,e){return new mh({type:"pipe",in:t,out:e})}var Gv=y("ZodPreprocess",(t,e)=>{mh.init(t,e),hp.init(t,e)}),Yv=y("ZodReadonly",(t,e)=>{mp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Of(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Xv(t){return new Yv({type:"readonly",innerType:t})}var gh=y("ZodCustom",(t,e)=>{gp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wf(t,r,o,n)});function _h(t,e){return nf(gh,t??(()=>!0),e)}function Qv(t,e={}){return sf(gh,t,e)}function ew(t,e){return af(t,e)}function na(t,e){return new Gv({type:"pipe",in:ph(t),out:e})}var vh={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"};var yh;yh||(yh={});var Ln={};wn(Ln,{bigint:()=>nw,boolean:()=>ow,date:()=>sw,number:()=>rw,string:()=>tw});function tw(t){return bp(ta,t)}function rw(t){return Bp(Dn,t)}function ow(t){return Gp(ra,t)}function nw(t){return Yp(ih,t)}function sw(t){return rf(uh,t)}Ce(_p());var Nt="2025-11-25";var Fn=[Nt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mt="io.modelcontextprotocol/related-task",Vn="2.0",ge=_h(t=>t!==null&&(typeof t=="object"||typeof t=="function")),wh=oe([m(),H().int()]),bh=m(),eR=me({ttl:H().optional(),pollInterval:H().optional()}),aw=x({ttl:H().optional()}),cw=x({taskId:m()}),ia=me({progressToken:wh.optional(),[Mt]:cw.optional()}),Le=x({_meta:ia.optional()}),go=Le.extend({task:aw.optional()}),$h=t=>go.safeParse(t).success,ye=x({method:m(),params:Le.loose().optional()}),Ve=x({_meta:ia.optional()}),He=x({method:m(),params:Ve.loose().optional()}),ve=me({_meta:ia.optional()}),Hn=oe([m(),H().int()]),Sh=x({jsonrpc:T(Vn),id:Hn,...ye.shape}).strict(),_o=t=>Sh.safeParse(t).success,xh=x({jsonrpc:T(Vn),...He.shape}).strict(),kh=t=>xh.safeParse(t).success,aa=x({jsonrpc:T(Vn),id:Hn,result:ve}).strict(),Qt=t=>aa.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var ca=x({jsonrpc:T(Vn),id:Hn.optional(),error:x({code:H().int(),message:m(),data:ue().optional()})}).strict();var zh=t=>ca.safeParse(t).success;var Ir=oe([Sh,xh,aa,ca]),tR=oe([aa,ca]),yt=ve.strict(),uw=Ve.extend({requestId:Hn.optional(),reason:m().optional()}),Jn=He.extend({method:T("notifications/cancelled"),params:uw}),lw=x({src:m(),mimeType:m().optional(),sizes:S(m()).optional(),theme:Oe(["light","dark"]).optional()}),yo=x({icons:S(lw).optional()}),Rr=x({name:m(),title:m().optional()}),Ph=Rr.extend({...Rr.shape,...yo.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),dw=qn(x({applyDefaults:Q().optional()}),te(m(),ue())),pw=na(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qn(x({form:dw.optional(),url:ge.optional()}),te(m(),ue()).optional())),fw=me({list:ge.optional(),cancel:ge.optional(),requests:me({sampling:me({createMessage:ge.optional()}).optional(),elicitation:me({create:ge.optional()}).optional()}).optional()}),hw=me({list:ge.optional(),cancel:ge.optional(),requests:me({tools:me({call:ge.optional()}).optional()}).optional()}),mw=x({experimental:te(m(),ge).optional(),sampling:x({context:ge.optional(),tools:ge.optional()}).optional(),elicitation:pw.optional(),roots:x({listChanged:Q().optional()}).optional(),tasks:fw.optional(),extensions:te(m(),ge).optional()}),gw=Le.extend({protocolVersion:m(),capabilities:mw,clientInfo:Ph}),ua=ye.extend({method:T("initialize"),params:gw});var _w=x({experimental:te(m(),ge).optional(),logging:ge.optional(),completions:ge.optional(),prompts:x({listChanged:Q().optional()}).optional(),resources:x({subscribe:Q().optional(),listChanged:Q().optional()}).optional(),tools:x({listChanged:Q().optional()}).optional(),tasks:hw.optional(),extensions:te(m(),ge).optional()}),la=ve.extend({protocolVersion:m(),capabilities:_w,serverInfo:Ph,instructions:m().optional()}),Bn=He.extend({method:T("notifications/initialized"),params:Ve.optional()}),Eh=t=>Bn.safeParse(t).success,Wn=ye.extend({method:T("ping"),params:Le.optional()}),yw=x({progress:H(),total:le(H()),message:le(m())}),vw=x({...Ve.shape,...yw.shape,progressToken:wh}),Kn=He.extend({method:T("notifications/progress"),params:vw}),ww=Le.extend({cursor:bh.optional()}),vo=ye.extend({params:ww.optional()}),wo=ve.extend({nextCursor:bh.optional()}),bw=Oe(["working","input_required","completed","failed","cancelled"]),bo=x({taskId:m(),status:bw,ttl:oe([H(),ah()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:le(H()),statusMessage:le(m())}),vt=ve.extend({task:bo}),$w=Ve.merge(bo),$o=He.extend({method:T("notifications/tasks/status"),params:$w}),Gn=ye.extend({method:T("tasks/get"),params:Le.extend({taskId:m()})}),Yn=ve.merge(bo),Xn=ye.extend({method:T("tasks/result"),params:Le.extend({taskId:m()})}),rR=ve.loose(),Qn=vo.extend({method:T("tasks/list")}),es=wo.extend({tasks:S(bo)}),ts=ye.extend({method:T("tasks/cancel"),params:Le.extend({taskId:m()})}),Th=ve.merge(bo),Rh=x({uri:m(),mimeType:le(m()),_meta:te(m(),ue()).optional()}),Ih=Rh.extend({text:m()}),da=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ch=Rh.extend({blob:da}),So=Oe(["user","assistant"]),Cr=x({audience:S(So).optional(),priority:H().min(0).max(1).optional(),lastModified:ho.datetime({offset:!0}).optional()}),Oh=x({...Rr.shape,...yo.shape,uri:m(),description:le(m()),mimeType:le(m()),size:le(H()),annotations:Cr.optional(),_meta:le(me({}))}),Sw=x({...Rr.shape,...yo.shape,uriTemplate:m(),description:le(m()),mimeType:le(m()),annotations:Cr.optional(),_meta:le(me({}))}),pa=vo.extend({method:T("resources/list")}),fa=wo.extend({resources:S(Oh)}),ha=vo.extend({method:T("resources/templates/list")}),ma=wo.extend({resourceTemplates:S(Sw)}),ga=Le.extend({uri:m()}),xw=ga,_a=ye.extend({method:T("resources/read"),params:xw}),ya=ve.extend({contents:S(oe([Ih,Ch]))}),va=He.extend({method:T("notifications/resources/list_changed"),params:Ve.optional()}),kw=ga,zw=ye.extend({method:T("resources/subscribe"),params:kw}),Pw=ga,Ew=ye.extend({method:T("resources/unsubscribe"),params:Pw}),Tw=Ve.extend({uri:m()}),Rw=He.extend({method:T("notifications/resources/updated"),params:Tw}),Iw=x({name:m(),description:le(m()),required:le(Q())}),Cw=x({...Rr.shape,...yo.shape,description:le(m()),arguments:le(S(Iw)),_meta:le(me({}))}),wa=vo.extend({method:T("prompts/list")}),ba=wo.extend({prompts:S(Cw)}),Ow=Le.extend({name:m(),arguments:te(m(),m()).optional()}),$a=ye.extend({method:T("prompts/get"),params:Ow}),Sa=x({type:T("text"),text:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),xa=x({type:T("image"),data:da,mimeType:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),ka=x({type:T("audio"),data:da,mimeType:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),Aw=x({type:T("tool_use"),name:m(),id:m(),input:te(m(),ue()),_meta:te(m(),ue()).optional()}),Nw=x({type:T("resource"),resource:oe([Ih,Ch]),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),Mw=Oh.extend({type:T("resource_link")}),za=oe([Sa,xa,ka,Mw,Nw]),jw=x({role:So,content:za}),Pa=ve.extend({description:m().optional(),messages:S(jw)}),Ea=He.extend({method:T("notifications/prompts/list_changed"),params:Ve.optional()}),Zw=x({title:m().optional(),readOnlyHint:Q().optional(),destructiveHint:Q().optional(),idempotentHint:Q().optional(),openWorldHint:Q().optional()}),Dw=x({taskSupport:Oe(["required","optional","forbidden"]).optional()}),Ah=x({...Rr.shape,...yo.shape,description:m().optional(),inputSchema:x({type:T("object"),properties:te(m(),ge).optional(),required:S(m()).optional()}).catchall(ue()),outputSchema:x({type:T("object"),properties:te(m(),ge).optional(),required:S(m()).optional()}).catchall(ue()).optional(),annotations:Zw.optional(),execution:Dw.optional(),_meta:te(m(),ue()).optional()}),Ta=vo.extend({method:T("tools/list")}),Ra=wo.extend({tools:S(Ah)}),jt=ve.extend({content:S(za).default([]),structuredContent:te(m(),ue()).optional(),isError:Q().optional()}),oR=jt.or(ve.extend({toolResult:ue()})),qw=go.extend({name:m(),arguments:te(m(),ue()).optional()}),xo=ye.extend({method:T("tools/call"),params:qw}),Ia=He.extend({method:T("notifications/tools/list_changed"),params:Ve.optional()}),Nh=x({autoRefresh:Q().default(!0),debounceMs:H().int().nonnegative().default(300)}),ko=Oe(["debug","info","notice","warning","error","critical","alert","emergency"]),Lw=Le.extend({level:ko}),Ca=ye.extend({method:T("logging/setLevel"),params:Lw}),Uw=Ve.extend({level:ko,logger:m().optional(),data:ue()}),Fw=He.extend({method:T("notifications/message"),params:Uw}),Vw=x({name:m().optional()}),Hw=x({hints:S(Vw).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Jw=x({mode:Oe(["auto","required","none"]).optional()}),Bw=x({type:T("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:S(za).default([]),structuredContent:x({}).loose().optional(),isError:Q().optional(),_meta:te(m(),ue()).optional()}),Ww=oa("type",[Sa,xa,ka]),Un=oa("type",[Sa,xa,ka,Aw,Bw]),Kw=x({role:So,content:oe([Un,S(Un)]),_meta:te(m(),ue()).optional()}),Gw=go.extend({messages:S(Kw),modelPreferences:Hw.optional(),systemPrompt:m().optional(),includeContext:Oe(["none","thisServer","allServers"]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:S(m()).optional(),metadata:ge.optional(),tools:S(Ah).optional(),toolChoice:Jw.optional()}),Oa=ye.extend({method:T("sampling/createMessage"),params:Gw}),er=ve.extend({model:m(),stopReason:le(Oe(["endTurn","stopSequence","maxTokens"]).or(m())),role:So,content:Ww}),zo=ve.extend({model:m(),stopReason:le(Oe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:So,content:oe([Un,S(Un)])}),Yw=x({type:T("boolean"),title:m().optional(),description:m().optional(),default:Q().optional()}),Xw=x({type:T("string"),title:m().optional(),description:m().optional(),minLength:H().optional(),maxLength:H().optional(),format:Oe(["email","uri","date","date-time"]).optional(),default:m().optional()}),Qw=x({type:Oe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),eb=x({type:T("string"),title:m().optional(),description:m().optional(),enum:S(m()),default:m().optional()}),tb=x({type:T("string"),title:m().optional(),description:m().optional(),oneOf:S(x({const:m(),title:m()})),default:m().optional()}),rb=x({type:T("string"),title:m().optional(),description:m().optional(),enum:S(m()),enumNames:S(m()).optional(),default:m().optional()}),ob=oe([eb,tb]),nb=x({type:T("array"),title:m().optional(),description:m().optional(),minItems:H().optional(),maxItems:H().optional(),items:x({type:T("string"),enum:S(m())}),default:S(m()).optional()}),sb=x({type:T("array"),title:m().optional(),description:m().optional(),minItems:H().optional(),maxItems:H().optional(),items:x({anyOf:S(x({const:m(),title:m()}))}),default:S(m()).optional()}),ib=oe([nb,sb]),ab=oe([rb,ob,ib]),cb=oe([ab,Yw,Xw,Qw]),ub=go.extend({mode:T("form").optional(),message:m(),requestedSchema:x({type:T("object"),properties:te(m(),cb),required:S(m()).optional()})}),lb=go.extend({mode:T("url"),message:m(),elicitationId:m(),url:m().url()}),db=oe([ub,lb]),Aa=ye.extend({method:T("elicitation/create"),params:db}),pb=Ve.extend({elicitationId:m()}),fb=He.extend({method:T("notifications/elicitation/complete"),params:pb}),Zt=ve.extend({action:Oe(["accept","decline","cancel"]),content:na(t=>t===null?void 0:t,te(m(),oe([m(),H(),Q(),S(m())])).optional())}),hb=x({type:T("ref/resource"),uri:m()});var mb=x({type:T("ref/prompt"),name:m()}),gb=Le.extend({ref:oe([mb,hb]),argument:x({name:m(),value:m()}),context:x({arguments:te(m(),m()).optional()}).optional()}),_b=ye.extend({method:T("completion/complete"),params:gb});var Na=ve.extend({completion:me({values:S(m()).max(100),total:le(H().int()),hasMore:le(Q())})}),yb=x({uri:m().startsWith("file://"),name:m().optional(),_meta:te(m(),ue()).optional()}),vb=ye.extend({method:T("roots/list"),params:Le.optional()}),Ma=ve.extend({roots:S(yb)}),wb=He.extend({method:T("notifications/roots/list_changed"),params:Ve.optional()}),nR=oe([Wn,ua,_b,Ca,$a,wa,pa,ha,_a,zw,Ew,xo,Ta,Gn,Xn,Qn,ts]),sR=oe([Jn,Kn,Bn,wb,$o]),iR=oe([yt,er,zo,Zt,Ma,Yn,es,vt]),aR=oe([Wn,Oa,Aa,vb,Gn,Xn,Qn,ts]),cR=oe([Jn,Kn,Fw,Rw,va,Ia,Ea,$o,fb]),uR=oe([yt,la,Na,Pa,ba,fa,ma,ya,jt,Ra,Yn,es,vt]),P=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===C.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new sa(n.elicitations,r)}return new t(e,r,o)}},sa=class extends P{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dt(t){return t==="completed"||t==="failed"||t==="cancelled"}var UR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ja(t){let r=Er(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Tr(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Za(t,e){let r=Ee(t,e);if(!r.success)throw r.error;return r.data}var zb=6e4,Or=class{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(Jn,r=>{this._oncancel(r)}),this.setNotificationHandler(Kn,r=>{this._onprogress(r)}),this.setRequestHandler(Wn,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gn,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new P(C.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Xn,async(r,o)=>{let n=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,o.sessionId))throw new P(C.InvalidParams,`Task not found: ${s}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new P(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let i=await this._taskStore.getTask(s,o.sessionId);if(!i)throw new P(C.InvalidParams,`Task not found: ${s}`);if(!Dt(i.status))return await this._waitForTaskUpdate(s,o.signal,o.sessionId),await n();if(Dt(i.status)){let a=await this._taskStore.getTaskResult(s,o.sessionId);return this._clearTaskQueue(s,o.sessionId),{...a,_meta:{...a._meta,[Mt]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Qn,async(r,o)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new P(C.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(ts,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new P(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(Dt(n.status))throw new P(C.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId,o.sessionId);let s=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!s)throw new P(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(n){throw n instanceof P?n:new P(C.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),P.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.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;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=s=>{o?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Qt(s)||zh(s)?this._onresponse(s):_o(s)?this._onrequest(s,i):kh(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=P.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[Mt]?.taskId,i=n?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new P(C.InvalidParams,`Task not found: ${s}`);c=!0})()),o===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:C.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:h,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>n?.send(h)).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:h,timestamp:Date.now()},n?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):n?.send(h).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=$h(e.params)?e.params.task:void 0,p=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,f={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(h,g)},sendRequest:async(h,g,_)=>{if(l.signal.aborted)throw new P(C.ConnectionClosed,"Request was cancelled");let w={..._,relatedRequestId:e.id};s&&!w.relatedTask&&(w.relatedTask={taskId:s});let b=w.relatedTask?.taskId??s;return b&&p&&await p.updateTaskStatus(b,"input_required"),await this.request(h,g,w)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new P(C.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,f)).then(async h=>{if(l.signal.aborted)return;let g={result:h,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},n?.sessionId):await n?.send(g)},async h=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:C.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},n?.sessionId):await n?.send(g)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Qt(e))o(e);else{let i=new P(e.error.code,e.error.message,e.error.data);o(i)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Qt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Qt(e))n(e);else{let i=P.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(i){yield{type:"error",error:i instanceof P?i:new P(C.InternalError,String(i))}}return}let s;try{let i=await this.request(e,vt,o);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new P(C.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},o);if(yield{type:"taskStatus",task:a},Dt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)}:a.status==="failed"?yield{type:"error",error:new P(C.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new P(C.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof P?i:new P(C.InternalError,String(i))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=b=>{l(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){d(b);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Mt]:c}});let h=b=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(b)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let z=b instanceof P?b:new P(C.RequestTimeout,String(b));l(z)};this._responseHandlers.set(p,b=>{if(!o?.signal?.aborted){if(b instanceof Error)return l(b);try{let z=Ee(r,b.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});let g=o?.timeout??zb,_=()=>h(P.fromError(C.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,o?.maxTotalTimeout,_,o?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=z=>{let E=this._responseHandlers.get(p);E?E(z):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(p),l(z)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Yn,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},es,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Th,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let o=ja(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,s)=>{let i=Za(e,n);return Promise.resolve(r(i,s))})}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,r){let o=ja(e);this._notificationHandlers.set(o,n=>{let s=Za(e,n);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o??this._transport?.sessionId,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&_o(n.message)){let s=n.message.id,i=this._requestResolvers.get(s);i?(i(new P(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r,o){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,o);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new P(C.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new P(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let s=await o.getTask(n,r);if(!s)throw new P(C.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,i)=>{await o.storeTaskResult(n,s,i,r);let a=await o.getTask(n,r);if(a){let c=$o.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Dt(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,s,i)=>{let a=await o.getTask(n,r);if(!a)throw new P(C.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Dt(a.status))throw new P(C.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,s,i,r);let c=await o.getTask(n,r);if(c){let u=$o.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Dt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Mh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rs(t,e){let r={...t};for(let o in e){let n=o,s=e[n];if(s===void 0)continue;let i=r[n];Mh(i)&&Mh(s)?r[n]={...i,...s}:r[n]=s}return r}var $_=De(Su(),1),S_=De(b_(),1);function _z(){let t=new $_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,S_.default)(t),t}var Yr=class{constructor(e){this._ajv=e??_z()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Zs=class{constructor(e){this._client=e}async*callToolStream(e,r=jt,o){let n=this._client,s={...o,task:o?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},r,s),a=n.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new P(C.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new P(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof P){yield{type:"error",error:l};return}yield{type:"error",error:new P(C.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._client.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,o){return this._client.requestStream(e,r,o)}};function Ds(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function qs(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Ls(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,o=t.properties;for(let n of Object.keys(o)){let s=o[n];r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[n]=s.default),r[n]!==void 0&&Ls(s,r[n])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ls(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ls(r,e)}}function yz(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Us=class extends Or{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Yr,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ia,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ea,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",va,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Zs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rs(this._capabilities,e)}setRequestHandler(e,r){let n=Er(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s=Tr(n);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=Ee(Aa,c);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=yz(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new P(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new P(C.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let b=Ee(vt,h);if(!b.success){let z=b.error instanceof Error?b.error.message:String(b.error);throw new P(C.InvalidParams,`Invalid task creation result: ${z}`)}return b.data}let g=Ee(Zt,h);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new P(C.InvalidParams,`Invalid elicitation result: ${b}`)}let _=g.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ls(w,_.content)}catch{}return _};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Ee(Oa,c);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let _=Ee(vt,p);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new P(C.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let h=d.tools||d.toolChoice?zo:er,g=Ee(h,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new P(C.InvalidParams,`Invalid sampling result: ${_}`)}return g.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:Nt,capabilities:this._capabilities,clientInfo:this._clientInfo}},la,r);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!Fn.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Ds(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&qs(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},yt,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Na,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},yt,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Pa,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ba,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},fa,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ma,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ya,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},yt,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},yt,r)}async callTool(e,r=jt,o){if(this.isToolTaskRequired(e.name))throw new P(C.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this.request({method:"tools/call",params:e},r,o),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new P(C.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let i=s(n.structuredContent);if(!i.valid)throw new P(C.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof P?i:new P(C.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}let o=r.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(r.name),o==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let o=await this.request({method:"tools/list",params:e},Ra,r);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(e,r,o,n){let s=Nh.safeParse(o);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=o,u=async()=>{if(!i){c(null,null);return}try{let d=await n();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var E_=De(P_(),1);function T_(t){if(t)try{return E_.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Fs(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function R_(t=fetch,e){return e?async(r,o)=>{let n={...e,...o,headers:o?.headers?{...Fs(e.headers),...Fs(o.headers)}:e.headers};return t(r,n)}:t}var Pz=5,Ez=[301,302,303,307,308];function Tz(t,e){return t.protocol===e.protocol&&t.hostname===e.hostname&&t.port===e.port?!0:t.hostname===e.hostname&&t.protocol==="http:"&&t.port===""&&e.protocol==="https:"&&e.port===""}function I_(t,e){let r=Ez.includes(t.status)?t.headers.get("location"):null;try{return r?new URL(r,e):void 0}catch{return}}function Vs(t,e,r,o,n=0){let s=I_(o,e),i=o.status===307||o.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!s||n===Pz||!i)return;let a=new URL(e);if(!((s.username||s.password)&&(s.username!==a.username||s.password!==a.password)||!Tz(a,s)))return Promise.resolve(o.body?.cancel()).then(()=>t(s,{...r,redirect:"manual"})).then(u=>Vs(t,s,r,u,n+1)??u)}var C_=new WeakSet;function Cu(t){let e=(r,o)=>(t??fetch)(r,o);return C_.add(e),e}function dr(t=fetch){return C_.has(t)?t:(e,r)=>r?.redirect==="error"||r?.redirect==="manual"?t(e,r):Promise.resolve(t(e,{...r,redirect:"manual"})).then(o=>Vs(t,e,r,o)??o)}function Hs(t,e){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let r=t.url||e,o=I_(t,r);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(r).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var Ou;Ou=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function Rz(t){return(await Ou).getRandomValues(new Uint8Array(t))}async function Iz(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,o="";for(;o.length<t;){let n=await Rz(t-o.length);for(let s of n)s<r&&(o+=e[s%e.length])}return o}async function Cz(t){return await Iz(t)}async function Oz(t){let e=await(await Ou).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Au(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Cz(t),r=await Oz(e);return{code_verifier:e,code_challenge:r}}var Se=sh().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:vh.custom,message:"URL must be parseable",fatal:!0}),ci}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),A_=me({resource:m().url(),authorization_servers:S(Se).optional(),jwks_uri:m().url().optional(),scopes_supported:S(m()).optional(),bearer_methods_supported:S(m()).optional(),resource_signing_alg_values_supported:S(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:Q().optional(),authorization_details_types_supported:S(m()).optional(),dpop_signing_alg_values_supported:S(m()).optional(),dpop_bound_access_tokens_required:Q().optional()}),Nu=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,registration_endpoint:Se.optional(),scopes_supported:S(m()).optional(),response_types_supported:S(m()),response_modes_supported:S(m()).optional(),grant_types_supported:S(m()).optional(),token_endpoint_auth_methods_supported:S(m()).optional(),token_endpoint_auth_signing_alg_values_supported:S(m()).optional(),service_documentation:Se.optional(),revocation_endpoint:Se.optional(),revocation_endpoint_auth_methods_supported:S(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:S(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(m()).optional(),code_challenge_methods_supported:S(m()).optional(),client_id_metadata_document_supported:Q().optional()}),Az=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,userinfo_endpoint:Se.optional(),jwks_uri:Se,registration_endpoint:Se.optional(),scopes_supported:S(m()).optional(),response_types_supported:S(m()),response_modes_supported:S(m()).optional(),grant_types_supported:S(m()).optional(),acr_values_supported:S(m()).optional(),subject_types_supported:S(m()),id_token_signing_alg_values_supported:S(m()),id_token_encryption_alg_values_supported:S(m()).optional(),id_token_encryption_enc_values_supported:S(m()).optional(),userinfo_signing_alg_values_supported:S(m()).optional(),userinfo_encryption_alg_values_supported:S(m()).optional(),userinfo_encryption_enc_values_supported:S(m()).optional(),request_object_signing_alg_values_supported:S(m()).optional(),request_object_encryption_alg_values_supported:S(m()).optional(),request_object_encryption_enc_values_supported:S(m()).optional(),token_endpoint_auth_methods_supported:S(m()).optional(),token_endpoint_auth_signing_alg_values_supported:S(m()).optional(),display_values_supported:S(m()).optional(),claim_types_supported:S(m()).optional(),claims_supported:S(m()).optional(),service_documentation:m().optional(),claims_locales_supported:S(m()).optional(),ui_locales_supported:S(m()).optional(),claims_parameter_supported:Q().optional(),request_parameter_supported:Q().optional(),request_uri_parameter_supported:Q().optional(),require_request_uri_registration:Q().optional(),op_policy_uri:Se.optional(),op_tos_uri:Se.optional(),client_id_metadata_document_supported:Q().optional()}),N_=x({...Az.shape,...Nu.pick({code_challenge_methods_supported:!0}).shape}),M_=x({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:Ln.number().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:m().optional().catch(void 0)}).strip(),j_=x({error:m(),error_description:m().optional(),error_uri:m().optional()}),O_=Se.optional().or(T("").transform(()=>{})),Nz=x({redirect_uris:S(Se),token_endpoint_auth_method:m().optional(),grant_types:S(m()).optional(),response_types:S(m()).optional(),client_name:m().optional(),client_uri:Se.optional(),logo_uri:O_,scope:m().optional(),contacts:S(m()).optional(),tos_uri:O_,policy_uri:m().optional(),jwks_uri:Se.optional(),jwks:ch().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Mz=x({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional(),issuer:m().optional().catch(void 0)}).strip(),Z_=Nz.merge(Mz),_1=x({error:m(),error_description:m().optional()}).strip(),y1=x({token:m(),token_type_hint:m().optional()}).strip();function D_(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function q_({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),o=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var he=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},on=class extends he{};on.errorCode="invalid_request";var pr=class extends he{};pr.errorCode="invalid_client";var fr=class extends he{};fr.errorCode="invalid_grant";var hr=class extends he{};hr.errorCode="unauthorized_client";var nn=class extends he{};nn.errorCode="unsupported_grant_type";var sn=class extends he{};sn.errorCode="invalid_scope";var an=class extends he{};an.errorCode="access_denied";var zt=class extends he{};zt.errorCode="server_error";var cn=class extends he{};cn.errorCode="temporarily_unavailable";var un=class extends he{};un.errorCode="unsupported_response_type";var ln=class extends he{};ln.errorCode="unsupported_token_type";var dn=class extends he{};dn.errorCode="invalid_token";var pn=class extends he{};pn.errorCode="method_not_allowed";var fn=class extends he{};fn.errorCode="too_many_requests";var mr=class extends he{};mr.errorCode="invalid_client_metadata";var hn=class extends he{};hn.errorCode="insufficient_scope";var mn=class extends he{};mn.errorCode="invalid_target";var L_={[on.errorCode]:on,[pr.errorCode]:pr,[fr.errorCode]:fr,[hr.errorCode]:hr,[nn.errorCode]:nn,[sn.errorCode]:sn,[an.errorCode]:an,[zt.errorCode]:zt,[cn.errorCode]:cn,[un.errorCode]:un,[ln.errorCode]:ln,[dn.errorCode]:dn,[pn.errorCode]:pn,[fn.errorCode]:fn,[mr.errorCode]:mr,[hn.errorCode]:hn,[mn.errorCode]:mn};var Pt=class extends Error{constructor(e){super(e??"Unauthorized")}};function jz(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Mu="code",ju="S256";function Zz(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&jz(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Dz(t,e,r,o){let{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":qz(n,s,r);return;case"client_secret_post":Lz(n,s,o);return;case"none":Uz(n,o);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qz(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${o}`)}function Lz(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Uz(t,e){e.set("client_id",t)}async function F_(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let o=j_.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:i}=o,a=L_[n]||zt;return new a(s||"",i)}catch(o){let n=t instanceof Response?Hs(t,t.url):void 0,s=`${e?`HTTP ${e}: `:""}${n??`Invalid OAuth error response: ${o}. Raw body: ${r}`}`;return new zt(s)}}function Fz(t,e){let[r,o]=[t,e];try{[r,o]=[new URL(t).href,new URL(e).href]}catch{}return r===o||r.endsWith("/")&&r.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===r}function qu(t,e){if(t)return typeof t.issuer!="string"?t.issuer==null?t:{...t,issuer:void 0}:Fz(t.issuer,e)?t:void 0}var Vz=M_.omit({issuer:!0}),Hz=Z_.omit({issuer:!0});function V_(t,e){return new Error(`OAuth client information is bound to authorization server ${t.issuer} and is not presented to ${e}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function gn(t,e){try{return await Zu(t,e)}catch(r){if(r instanceof pr||r instanceof hr)return await t.invalidateCredentials?.("all"),await Zu(t,e);if(r instanceof fr)return await t.invalidateCredentials?.("tokens"),await Zu(t,e);throw r}}async function Zu(t,{serverUrl:e,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,l=n;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await J_(c,{fetchFn:s}),!a)try{a=await H_(e,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let j=await Xz(e,{resourceMetadataUrl:l,fetchFn:s});c=j.authorizationServerUrl,u=j.authorizationServerMetadata,a=j.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=String(c),p=await Bz(e,t,a),f=p&&a&&!t.validateResourceURL?a.resource:p,h=o||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,g=await Promise.resolve(t.clientInformation()),_=qu(g,d),w=t.saveClientInformation!==void 0&&!!t.redirectUrl;if(g&&!_&&!w)throw V_(g,d);let b=_?.issuer==null?_:void 0,z=async()=>{try{b&&await t.saveClientInformation?.({...b,issuer:d})}catch{}};if(!_){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let j=u?.client_id_metadata_document_supported===!0,ie=t.clientMetadataUrl;if(ie&&!Jz(ie))throw new mr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ie}`);if(j&&ie)_={client_id:ie,issuer:d},await t.saveClientInformation?.(_);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");_={...await oP(c,{metadata:u,clientMetadata:t.clientMetadata,scope:h,fetchFn:s}),issuer:d},await t.saveClientInformation(_)}}let E=!t.redirectUrl;if(r!==void 0||E){let j=await rP(t,c,{metadata:u,resource:f,authorizationCode:r,fetchFn:s});return await z(),await t.saveTokens({...j,issuer:d}),"AUTHORIZED"}let v=qu(await t.tokens(),d);if(v?.refresh_token&&v.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),v?.refresh_token)try{let j=await tP(c,{metadata:u,clientInformation:_,refreshToken:v.refresh_token,resource:f,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await z(),await t.saveTokens({...j,issuer:d}),"AUTHORIZED"}catch(j){if(!(!(j instanceof he)||j instanceof zt))throw j}let $=t.state?await t.state():void 0,{authorizationUrl:O,codeVerifier:K}=await Qz(c,{metadata:u,clientInformation:_,state:$,redirectUrl:t.redirectUrl,scope:h,resource:f});return await t.saveCodeVerifier(K),await t.redirectToAuthorization(O),"REDIRECT"}function Jz(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Bz(t,e,r){let o=D_(t);if(e.validateResourceURL)return await e.validateResourceURL(o,r?.resource);if(r){if(!q_({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function Lu(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,o]=e.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Du(t,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=Du(t,"scope")||void 0,a=Du(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Du(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function H_(t,e,r=fetch){let o=await Gz(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return A_.parse(await o.json())}async function Uu(t,e,r=fetch){try{return await dr(r)(t,{headers:e})}catch(o){if(o instanceof TypeError)return e?Uu(t,void 0,r):void 0;throw o}}function Wz(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function U_(t,e,r=fetch){return await Uu(t,{"MCP-Protocol-Version":e},r)}function Kz(t,e){return!t||!t.ok&&t.status<500&&e!=="/"}async function Gz(t,e,r,o){let n=new URL(t),s=o?.protocolVersion??Nt,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let c=Wz(e,n.pathname);i=new URL(c,o?.metadataServerUrl??n),i.search=n.search}let a=await U_(i,s,r);if(!o?.metadataUrl&&Kz(a,n.pathname)){let c=new URL(`/.well-known/${e}`,n);a=await U_(c,s,r)}return a}function Yz(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),o;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),o}async function J_(t,{fetchFn:e=fetch,protocolVersion:r=Nt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=Yz(t);for(let{url:s,type:i}of n){let a=await Uu(s,o,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Nu.parse(await a.json()):N_.parse(await a.json())}}}async function Xz(t,e){let r,o;try{r=await H_(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",t)));let n=await J_(o,{fetchFn:e?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function B_(t){return typeof t=="string"?t:t.href}async function Qz(t,{metadata:e,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Mu))throw new Error(`Incompatible auth server: does not support response type ${Mu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(ju))throw new Error(`Incompatible auth server: does not support code challenge method ${ju}`)}else a=new URL("/authorize",t);let c=await Au(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",Mu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",ju),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),n&&a.searchParams.set("scope",n),n?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",B_(i)),{authorizationUrl:a,codeVerifier:u}}function eP(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function W_(t,{metadata:e,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:i}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",B_(s)),n)await n(c,r,a,e);else if(o){let l=e?.token_endpoint_auth_methods_supported??[],d=Zz(o,l);Dz(d,o,c,r)}let u=await dr(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await F_(u);return Vz.parse(await u.json())}async function tP(t,{metadata:e,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await W_(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:i});return{refresh_token:o,...c}}async function rP(t,e,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){let i=async()=>{let l=await t.clientInformation(),d=qu(l,String(e));if(l&&!d)throw V_(l,String(e));return d},a=await i(),c=t.clientMetadata.scope,u;if(t.prepareTokenRequest&&(u=await t.prepareTokenRequest(c)),!u){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await t.codeVerifier();u=eP(n,l,t.redirectUrl)}return a??(a=await i()),W_(e,{metadata:r,tokenRequestParams:u,clientInformation:a,addClientAuthentication:t.addClientAuthentication,resource:o,fetchFn:s})}async function oP(t,{metadata:e,clientMetadata:r,scope:o,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);let i=await dr(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!i.ok)throw await F_(i);return Hz.parse(await i.json())}var _n=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},K_=10,nP=13,gr=32;function Fu(t){}function X_(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Fu,onError:r=Fu,onRetry:o=Fu,onComment:n,maxBufferSize:s}=t,i=[],a=0,c=!0,u,l="",d=0,p,f=!1;function h(v){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){let K=_(v);K!==""&&(i.push(K),a=K.length),g();return}if(v.indexOf(`
|
|
94
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Wi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,l),a._zod.parent===d)for(let _ in u)_==="$ref"||_==="allOf"||_ in l||delete u[_];if(h.$ref&&f.def)for(let _ in u)_==="$ref"||_==="allOf"||_ in f.def&&JSON.stringify(u[_])===JSON.stringify(f.def[_])&&delete u[_]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())o(a[0]);let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Object.assign(n,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&n.id===s&&delete n.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:fo(e,"input",t.processors),output:fo(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Pe(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Pe(o.element,r);if(o.type==="set")return Pe(o.valueType,r);if(o.type==="lazy")return Pe(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Pe(o.innerType,r);if(o.type==="intersection")return Pe(o.left,r)||Pe(o.right,r);if(o.type==="record"||o.type==="map")return Pe(o.keyType,r)||Pe(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Pe(o.in,r)||Pe(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Pe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Pe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Pe(n,r))return!0;return!!(o.rest&&Pe(o.rest,r))}return!1}var cf=(t,e={})=>r=>{let o=Ji({...r,processors:e});return pe(t,o),Bi(o,t),Wi(o,t)},fo=(t,e,r={})=>o=>{let{libraryOptions:n,target:s}=o??{},i=Ji({...n??{},target:s,io:e,processors:r});return pe(t,i),Bi(i,t),Wi(i,t)};var nv={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uf=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(n.minLength=s),typeof i=="number"&&(n.maxLength=i),a&&(n.format=nv[a]??a,n.format===""&&delete n.format,a==="time"&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?n.pattern=l[0].source:l.length>1&&(n.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},lf=(t,e,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?n.type="integer":n.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof s=="number"&&(n.minimum=s),p?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof i=="number"&&(n.maximum=i),typeof c=="number"&&(n.multipleOf=c)},df=(t,e,r,o)=>{r.type="boolean"},pf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var ff=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var hf=(t,e,r,o)=>{r.not={}},mf=(t,e,r,o)=>{},gf=(t,e,r,o)=>{},_f=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},yf=(t,e,r,o)=>{let n=t._zod.def,s=ro(n.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},vf=(t,e,r,o)=>{let n=t._zod.def,s=[];for(let i of n.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var wf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var bf=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var $f=(t,e,r,o)=>{let n=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(n.minItems=i),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=pe(s.element,e,{...o,path:[...o.path,"items"]})},Sf=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=pe(i[u],e,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(n.required=Array.from(c)),s.catchall?._zod.def.type==="never"?n.additionalProperties=!1:s.catchall?s.catchall&&(n.additionalProperties=pe(s.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},xf=(t,e,r,o)=>{let n=t._zod.def,s=n.inclusive===!1,i=n.options.map((a,c)=>pe(a,e,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},kf=(t,e,r,o)=>{let n=t._zod.def,s=pe(n.left,e,{...o,path:[...o.path,"allOf",0]}),i=pe(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var zf=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=pe(s.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of c)n.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(n.propertyNames=pe(s.keyType,e,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=pe(s.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l)}},Pf=(t,e,r,o)=>{let n=t._zod.def,s=pe(n.innerType,e,o),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Ef=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType},Tf=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Rf=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},If=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Cf=(t,e,r,o)=>{let n=t._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?n.out:n.in:n.out;pe(i,e,o);let a=e.seen.get(t);a.ref=i},Of=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.readOnly=!0};var Ki=(t,e,r,o)=>{let n=t._zod.def;pe(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType};function jn(t){return!!t._zod}function Ee(t,e){return jn(t)?ao(t,e):t.safeParse(e)}function Er(t){if(!t)return;let e;if(jn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Tr(t){if(jn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let o=t.value;if(o!==void 0)return o}var ho={};wn(ho,{ZodISODate:()=>Nf,ZodISODateTime:()=>Af,ZodISODuration:()=>jf,ZodISOTime:()=>Mf,date:()=>Yi,datetime:()=>Gi,duration:()=>Qi,time:()=>Xi});var Af=y("ZodISODateTime",(t,e)=>{Id.init(t,e),ce.init(t,e)});function Gi(t){return Up(Af,t)}var Nf=y("ZodISODate",(t,e)=>{Cd.init(t,e),ce.init(t,e)});function Yi(t){return Fp(Nf,t)}var Mf=y("ZodISOTime",(t,e)=>{Od.init(t,e),ce.init(t,e)});function Xi(t){return Vp(Mf,t)}var jf=y("ZodISODuration",(t,e)=>{Ad.init(t,e),ce.init(t,e)});function Qi(t){return Hp(jf,t)}var pv=(t,e)=>{Pn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bi(t,r)},flatten:{value:r=>wi(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,br,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,br,2)}},isEmpty:{get(){return t.issues.length===0}}})};var qe=y("ZodError",pv,{Parent:Error});var Df=En(qe),qf=Tn(qe),Lf=io(qe),Uf=co(qe),Ff=hl(qe),Vf=ml(qe),Hf=gl(qe),Jf=_l(qe),Bf=yl(qe),Wf=vl(qe),Kf=wl(qe),Gf=bl(qe);var Yf=new WeakMap;function mo(t,e,r){let o=Object.getPrototypeOf(t),n=Yf.get(o);if(n||(n=new Set,Yf.set(o,n)),!n.has(e)){n.add(e);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var X=y("ZodType",(t,e)=>(G.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:fo(t,"input"),output:fo(t,"output")}}),t.toJSONSchema=cf(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,o)=>Df(t,r,o,{callee:t.parse}),t.safeParse=(r,o)=>Lf(t,r,o),t.parseAsync=async(r,o)=>qf(t,r,o,{callee:t.parseAsync}),t.safeParseAsync=async(r,o)=>Uf(t,r,o),t.spa=t.safeParseAsync,t.encode=(r,o)=>Ff(t,r,o),t.decode=(r,o)=>Vf(t,r,o),t.encodeAsync=async(r,o)=>Hf(t,r,o),t.decodeAsync=async(r,o)=>Jf(t,r,o),t.safeEncode=(r,o)=>Bf(t,r,o),t.safeDecode=(r,o)=>Wf(t,r,o),t.safeEncodeAsync=async(r,o)=>Kf(t,r,o),t.safeDecodeAsync=async(r,o)=>Gf(t,r,o),mo(t,"ZodType",{check(...r){let o=this.def;return this.clone(L.mergeDefs(o,{checks:[...o.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return Ue(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(ew(r,o))},superRefine(r,o){return this.check(tw(r,o))},overwrite(r){return this.check(At(r))},optional(){return le(this)},exactOptional(){return Uv(this)},nullable(){return th(this)},nullish(){return le(th(this))},nonoptional(r){return Wv(this,r)},array(){return S(this)},or(r){return oe([this,r])},and(r){return qn(this,r)},transform(r){return rh(this,ph(r))},default(r){return Hv(this,r)},prefault(r){return Bv(this,r)},catch(r){return Gv(this,r)},pipe(r){return rh(this,r)},readonly(){return Qv(this)},describe(r){let o=this.clone();return Ot.add(o,{description:r}),o},meta(...r){if(r.length===0)return Ot.get(this);let o=this.clone();return Ot.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ot.get(t)?.description},configurable:!0}),t)),oh=y("_ZodString",(t,e)=>{An.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>uf(t,o,n,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,mo(t,"_ZodString",{regex(...o){return this.check(Ni(...o))},includes(...o){return this.check(Zi(...o))},startsWith(...o){return this.check(Di(...o))},endsWith(...o){return this.check(qi(...o))},min(...o){return this.check(zr(...o))},max(...o){return this.check(Nn(...o))},length(...o){return this.check(Mn(...o))},nonempty(...o){return this.check(zr(1,...o))},lowercase(o){return this.check(Mi(o))},uppercase(o){return this.check(ji(o))},trim(){return this.check(Ui())},normalize(...o){return this.check(Li(...o))},toLowerCase(){return this.check(Fi())},toUpperCase(){return this.check(Vi())},slugify(){return this.check(Hi())}})}),ta=y("ZodString",(t,e)=>{An.init(t,e),oh.init(t,e),t.email=r=>t.check($p(hv,r)),t.url=r=>t.check(Ai(nh,r)),t.jwt=r=>t.check(Lp(Tv,r)),t.emoji=r=>t.check(Pp(mv,r)),t.guid=r=>t.check(Oi(Xf,r)),t.uuid=r=>t.check(Sp(Zn,r)),t.uuidv4=r=>t.check(xp(Zn,r)),t.uuidv6=r=>t.check(kp(Zn,r)),t.uuidv7=r=>t.check(zp(Zn,r)),t.nanoid=r=>t.check(Ep(gv,r)),t.guid=r=>t.check(Oi(Xf,r)),t.cuid=r=>t.check(Tp(_v,r)),t.cuid2=r=>t.check(Rp(yv,r)),t.ulid=r=>t.check(Ip(vv,r)),t.base64=r=>t.check(Zp(zv,r)),t.base64url=r=>t.check(Dp(Pv,r)),t.xid=r=>t.check(Cp(wv,r)),t.ksuid=r=>t.check(Op(bv,r)),t.ipv4=r=>t.check(Ap($v,r)),t.ipv6=r=>t.check(Np(Sv,r)),t.cidrv4=r=>t.check(Mp(xv,r)),t.cidrv6=r=>t.check(jp(kv,r)),t.e164=r=>t.check(qp(Ev,r)),t.datetime=r=>t.check(Gi(r)),t.date=r=>t.check(Yi(r)),t.time=r=>t.check(Xi(r)),t.duration=r=>t.check(Qi(r))});function m(t){return wp(ta,t)}var ce=y("ZodStringFormat",(t,e)=>{re.init(t,e),oh.init(t,e)}),hv=y("ZodEmail",(t,e)=>{$d.init(t,e),ce.init(t,e)});var Xf=y("ZodGUID",(t,e)=>{wd.init(t,e),ce.init(t,e)});var Zn=y("ZodUUID",(t,e)=>{bd.init(t,e),ce.init(t,e)});var nh=y("ZodURL",(t,e)=>{Sd.init(t,e),ce.init(t,e)});function sh(t){return Ai(nh,t)}var mv=y("ZodEmoji",(t,e)=>{xd.init(t,e),ce.init(t,e)});var gv=y("ZodNanoID",(t,e)=>{kd.init(t,e),ce.init(t,e)});var _v=y("ZodCUID",(t,e)=>{zd.init(t,e),ce.init(t,e)});var yv=y("ZodCUID2",(t,e)=>{Pd.init(t,e),ce.init(t,e)});var vv=y("ZodULID",(t,e)=>{Ed.init(t,e),ce.init(t,e)});var wv=y("ZodXID",(t,e)=>{Td.init(t,e),ce.init(t,e)});var bv=y("ZodKSUID",(t,e)=>{Rd.init(t,e),ce.init(t,e)});var $v=y("ZodIPv4",(t,e)=>{Nd.init(t,e),ce.init(t,e)});var Sv=y("ZodIPv6",(t,e)=>{Md.init(t,e),ce.init(t,e)});var xv=y("ZodCIDRv4",(t,e)=>{jd.init(t,e),ce.init(t,e)});var kv=y("ZodCIDRv6",(t,e)=>{Zd.init(t,e),ce.init(t,e)});var zv=y("ZodBase64",(t,e)=>{qd.init(t,e),ce.init(t,e)});var Pv=y("ZodBase64URL",(t,e)=>{Ld.init(t,e),ce.init(t,e)});var Ev=y("ZodE164",(t,e)=>{Ud.init(t,e),ce.init(t,e)});var Tv=y("ZodJWT",(t,e)=>{Fd.init(t,e),ce.init(t,e)});var Dn=y("ZodNumber",(t,e)=>{Ei.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>lf(t,o,n,s),mo(t,"ZodNumber",{gt(o,n){return this.check(kr(o,n))},gte(o,n){return this.check(Ye(o,n))},min(o,n){return this.check(Ye(o,n))},lt(o,n){return this.check(xr(o,n))},lte(o,n){return this.check(_t(o,n))},max(o,n){return this.check(_t(o,n))},int(o){return this.check(Qf(o))},safe(o){return this.check(Qf(o))},positive(o){return this.check(kr(0,o))},nonnegative(o){return this.check(Ye(0,o))},negative(o){return this.check(xr(0,o))},nonpositive(o){return this.check(_t(0,o))},multipleOf(o,n){return this.check(po(o,n))},step(o,n){return this.check(po(o,n))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function H(t){return Jp(Dn,t)}var Rv=y("ZodNumberFormat",(t,e)=>{Vd.init(t,e),Dn.init(t,e)});function Qf(t){return Wp(Rv,t)}var ra=y("ZodBoolean",(t,e)=>{Hd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>df(t,r,o,n)});function Q(t){return Kp(ra,t)}var ih=y("ZodBigInt",(t,e)=>{Jd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>pf(t,o,n,s),t.gte=(o,n)=>t.check(Ye(o,n)),t.min=(o,n)=>t.check(Ye(o,n)),t.gt=(o,n)=>t.check(kr(o,n)),t.gte=(o,n)=>t.check(Ye(o,n)),t.min=(o,n)=>t.check(Ye(o,n)),t.lt=(o,n)=>t.check(xr(o,n)),t.lte=(o,n)=>t.check(_t(o,n)),t.max=(o,n)=>t.check(_t(o,n)),t.positive=o=>t.check(kr(BigInt(0),o)),t.negative=o=>t.check(xr(BigInt(0),o)),t.nonpositive=o=>t.check(_t(BigInt(0),o)),t.nonnegative=o=>t.check(Ye(BigInt(0),o)),t.multipleOf=(o,n)=>t.check(po(o,n));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var Iv=y("ZodNull",(t,e)=>{Bd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ff(t,r,o,n)});function ah(t){return Xp(Iv,t)}var Cv=y("ZodAny",(t,e)=>{Wd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mf(t,r,o,n)});function ch(){return Qp(Cv)}var Ov=y("ZodUnknown",(t,e)=>{Kd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gf(t,r,o,n)});function ue(){return ef(Ov)}var Av=y("ZodNever",(t,e)=>{Gd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hf(t,r,o,n)});function Nv(t){return tf(Av,t)}var uh=y("ZodDate",(t,e)=>{Yd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>_f(t,o,n,s),t.min=(o,n)=>t.check(Ye(o,n)),t.max=(o,n)=>t.check(_t(o,n));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var Mv=y("ZodArray",(t,e)=>{Xd.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$f(t,r,o,n),t.element=e.element,mo(t,"ZodArray",{min(r,o){return this.check(zr(r,o))},nonempty(r){return this.check(zr(1,r))},max(r,o){return this.check(Nn(r,o))},length(r,o){return this.check(Mn(r,o))},unwrap(){return this.element}})});function S(t,e){return of(Mv,t,e)}var lh=y("ZodObject",(t,e)=>{tp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Sf(t,r,o,n),L.defineLazy(t,"shape",()=>e.shape),mo(t,"ZodObject",{keyof(){return Oe(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ue()})},loose(){return this.clone({...this._zod.def,catchall:ue()})},strict(){return this.clone({...this._zod.def,catchall:Nv()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return L.extend(this,r)},safeExtend(r){return L.safeExtend(this,r)},merge(r){return L.merge(this,r)},pick(r){return L.pick(this,r)},omit(r){return L.omit(this,r)},partial(...r){return L.partial(fh,this,r[0])},required(...r){return L.required(hh,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...L.normalizeParams(e)};return new lh(r)}function me(t,e){return new lh({type:"object",shape:t,catchall:ue(),...L.normalizeParams(e)})}var dh=y("ZodUnion",(t,e)=>{Ti.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xf(t,r,o,n),t.options=e.options});function oe(t,e){return new dh({type:"union",options:t,...L.normalizeParams(e)})}var jv=y("ZodDiscriminatedUnion",(t,e)=>{dh.init(t,e),rp.init(t,e)});function oa(t,e,r){return new jv({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var Zv=y("ZodIntersection",(t,e)=>{op.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kf(t,r,o,n)});function qn(t,e){return new Zv({type:"intersection",left:t,right:e})}var eh=y("ZodRecord",(t,e)=>{np.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zf(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function te(t,e,r){return!e||!e._zod?new eh({type:"record",keyType:m(),valueType:t,...L.normalizeParams(e)}):new eh({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var ea=y("ZodEnum",(t,e)=>{sp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(o,n,s)=>yf(t,o,n,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new ea({...e,checks:[],...L.normalizeParams(n),entries:s})},t.exclude=(o,n)=>{let s={...e.entries};for(let i of o)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new ea({...e,checks:[],...L.normalizeParams(n),entries:s})}});function Oe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new ea({type:"enum",entries:r,...L.normalizeParams(e)})}var Dv=y("ZodLiteral",(t,e)=>{ip.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vf(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function T(t,e){return new Dv({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var qv=y("ZodTransform",(t,e)=>{ap.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bf(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new vr(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(L.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(L.issue(i))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=n,r.fallback=!0,r)}});function ph(t){return new qv({type:"transform",transform:t})}var fh=y("ZodOptional",(t,e)=>{Ri.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ki(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function le(t){return new fh({type:"optional",innerType:t})}var Lv=y("ZodExactOptional",(t,e)=>{cp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ki(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Uv(t){return new Lv({type:"optional",innerType:t})}var Fv=y("ZodNullable",(t,e)=>{up.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Pf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function th(t){return new Fv({type:"nullable",innerType:t})}var Vv=y("ZodDefault",(t,e)=>{lp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Tf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Hv(t,e){return new Vv({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Jv=y("ZodPrefault",(t,e)=>{dp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Rf(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Bv(t,e){return new Jv({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var hh=y("ZodNonOptional",(t,e)=>{pp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Ef(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Wv(t,e){return new hh({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var Kv=y("ZodCatch",(t,e)=>{fp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>If(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Gv(t,e){return new Kv({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var mh=y("ZodPipe",(t,e)=>{Ii.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Cf(t,r,o,n),t.in=e.in,t.out=e.out});function rh(t,e){return new mh({type:"pipe",in:t,out:e})}var Yv=y("ZodPreprocess",(t,e)=>{mh.init(t,e),hp.init(t,e)}),Xv=y("ZodReadonly",(t,e)=>{mp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Of(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Qv(t){return new Xv({type:"readonly",innerType:t})}var gh=y("ZodCustom",(t,e)=>{gp.init(t,e),X.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wf(t,r,o,n)});function _h(t,e){return nf(gh,t??(()=>!0),e)}function ew(t,e={}){return sf(gh,t,e)}function tw(t,e){return af(t,e)}function na(t,e){return new Yv({type:"pipe",in:ph(t),out:e})}var vh={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"};var yh;yh||(yh={});var Ln={};wn(Ln,{bigint:()=>sw,boolean:()=>nw,date:()=>iw,number:()=>ow,string:()=>rw});function rw(t){return bp(ta,t)}function ow(t){return Bp(Dn,t)}function nw(t){return Gp(ra,t)}function sw(t){return Yp(ih,t)}function iw(t){return rf(uh,t)}Ce(_p());var Nt="2025-11-25";var Fn=[Nt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mt="io.modelcontextprotocol/related-task",Vn="2.0",ge=_h(t=>t!==null&&(typeof t=="object"||typeof t=="function")),wh=oe([m(),H().int()]),bh=m(),tR=me({ttl:H().optional(),pollInterval:H().optional()}),cw=x({ttl:H().optional()}),uw=x({taskId:m()}),ia=me({progressToken:wh.optional(),[Mt]:uw.optional()}),Le=x({_meta:ia.optional()}),go=Le.extend({task:cw.optional()}),$h=t=>go.safeParse(t).success,ye=x({method:m(),params:Le.loose().optional()}),Ve=x({_meta:ia.optional()}),He=x({method:m(),params:Ve.loose().optional()}),ve=me({_meta:ia.optional()}),Hn=oe([m(),H().int()]),Sh=x({jsonrpc:T(Vn),id:Hn,...ye.shape}).strict(),_o=t=>Sh.safeParse(t).success,xh=x({jsonrpc:T(Vn),...He.shape}).strict(),kh=t=>xh.safeParse(t).success,aa=x({jsonrpc:T(Vn),id:Hn,result:ve}).strict(),Qt=t=>aa.safeParse(t).success;var C;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(C||(C={}));var ca=x({jsonrpc:T(Vn),id:Hn.optional(),error:x({code:H().int(),message:m(),data:ue().optional()})}).strict();var zh=t=>ca.safeParse(t).success;var Ir=oe([Sh,xh,aa,ca]),rR=oe([aa,ca]),yt=ve.strict(),lw=Ve.extend({requestId:Hn.optional(),reason:m().optional()}),Jn=He.extend({method:T("notifications/cancelled"),params:lw}),dw=x({src:m(),mimeType:m().optional(),sizes:S(m()).optional(),theme:Oe(["light","dark"]).optional()}),yo=x({icons:S(dw).optional()}),Rr=x({name:m(),title:m().optional()}),Ph=Rr.extend({...Rr.shape,...yo.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),pw=qn(x({applyDefaults:Q().optional()}),te(m(),ue())),fw=na(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qn(x({form:pw.optional(),url:ge.optional()}),te(m(),ue()).optional())),hw=me({list:ge.optional(),cancel:ge.optional(),requests:me({sampling:me({createMessage:ge.optional()}).optional(),elicitation:me({create:ge.optional()}).optional()}).optional()}),mw=me({list:ge.optional(),cancel:ge.optional(),requests:me({tools:me({call:ge.optional()}).optional()}).optional()}),gw=x({experimental:te(m(),ge).optional(),sampling:x({context:ge.optional(),tools:ge.optional()}).optional(),elicitation:fw.optional(),roots:x({listChanged:Q().optional()}).optional(),tasks:hw.optional(),extensions:te(m(),ge).optional()}),_w=Le.extend({protocolVersion:m(),capabilities:gw,clientInfo:Ph}),ua=ye.extend({method:T("initialize"),params:_w});var yw=x({experimental:te(m(),ge).optional(),logging:ge.optional(),completions:ge.optional(),prompts:x({listChanged:Q().optional()}).optional(),resources:x({subscribe:Q().optional(),listChanged:Q().optional()}).optional(),tools:x({listChanged:Q().optional()}).optional(),tasks:mw.optional(),extensions:te(m(),ge).optional()}),la=ve.extend({protocolVersion:m(),capabilities:yw,serverInfo:Ph,instructions:m().optional()}),Bn=He.extend({method:T("notifications/initialized"),params:Ve.optional()}),Eh=t=>Bn.safeParse(t).success,Wn=ye.extend({method:T("ping"),params:Le.optional()}),vw=x({progress:H(),total:le(H()),message:le(m())}),ww=x({...Ve.shape,...vw.shape,progressToken:wh}),Kn=He.extend({method:T("notifications/progress"),params:ww}),bw=Le.extend({cursor:bh.optional()}),vo=ye.extend({params:bw.optional()}),wo=ve.extend({nextCursor:bh.optional()}),$w=Oe(["working","input_required","completed","failed","cancelled"]),bo=x({taskId:m(),status:$w,ttl:oe([H(),ah()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:le(H()),statusMessage:le(m())}),vt=ve.extend({task:bo}),Sw=Ve.merge(bo),$o=He.extend({method:T("notifications/tasks/status"),params:Sw}),Gn=ye.extend({method:T("tasks/get"),params:Le.extend({taskId:m()})}),Yn=ve.merge(bo),Xn=ye.extend({method:T("tasks/result"),params:Le.extend({taskId:m()})}),oR=ve.loose(),Qn=vo.extend({method:T("tasks/list")}),es=wo.extend({tasks:S(bo)}),ts=ye.extend({method:T("tasks/cancel"),params:Le.extend({taskId:m()})}),Th=ve.merge(bo),Rh=x({uri:m(),mimeType:le(m()),_meta:te(m(),ue()).optional()}),Ih=Rh.extend({text:m()}),da=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ch=Rh.extend({blob:da}),So=Oe(["user","assistant"]),Cr=x({audience:S(So).optional(),priority:H().min(0).max(1).optional(),lastModified:ho.datetime({offset:!0}).optional()}),Oh=x({...Rr.shape,...yo.shape,uri:m(),description:le(m()),mimeType:le(m()),size:le(H()),annotations:Cr.optional(),_meta:le(me({}))}),xw=x({...Rr.shape,...yo.shape,uriTemplate:m(),description:le(m()),mimeType:le(m()),annotations:Cr.optional(),_meta:le(me({}))}),pa=vo.extend({method:T("resources/list")}),fa=wo.extend({resources:S(Oh)}),ha=vo.extend({method:T("resources/templates/list")}),ma=wo.extend({resourceTemplates:S(xw)}),ga=Le.extend({uri:m()}),kw=ga,_a=ye.extend({method:T("resources/read"),params:kw}),ya=ve.extend({contents:S(oe([Ih,Ch]))}),va=He.extend({method:T("notifications/resources/list_changed"),params:Ve.optional()}),zw=ga,Pw=ye.extend({method:T("resources/subscribe"),params:zw}),Ew=ga,Tw=ye.extend({method:T("resources/unsubscribe"),params:Ew}),Rw=Ve.extend({uri:m()}),Iw=He.extend({method:T("notifications/resources/updated"),params:Rw}),Cw=x({name:m(),description:le(m()),required:le(Q())}),Ow=x({...Rr.shape,...yo.shape,description:le(m()),arguments:le(S(Cw)),_meta:le(me({}))}),wa=vo.extend({method:T("prompts/list")}),ba=wo.extend({prompts:S(Ow)}),Aw=Le.extend({name:m(),arguments:te(m(),m()).optional()}),$a=ye.extend({method:T("prompts/get"),params:Aw}),Sa=x({type:T("text"),text:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),xa=x({type:T("image"),data:da,mimeType:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),ka=x({type:T("audio"),data:da,mimeType:m(),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),Nw=x({type:T("tool_use"),name:m(),id:m(),input:te(m(),ue()),_meta:te(m(),ue()).optional()}),Mw=x({type:T("resource"),resource:oe([Ih,Ch]),annotations:Cr.optional(),_meta:te(m(),ue()).optional()}),jw=Oh.extend({type:T("resource_link")}),za=oe([Sa,xa,ka,jw,Mw]),Zw=x({role:So,content:za}),Pa=ve.extend({description:m().optional(),messages:S(Zw)}),Ea=He.extend({method:T("notifications/prompts/list_changed"),params:Ve.optional()}),Dw=x({title:m().optional(),readOnlyHint:Q().optional(),destructiveHint:Q().optional(),idempotentHint:Q().optional(),openWorldHint:Q().optional()}),qw=x({taskSupport:Oe(["required","optional","forbidden"]).optional()}),Ah=x({...Rr.shape,...yo.shape,description:m().optional(),inputSchema:x({type:T("object"),properties:te(m(),ge).optional(),required:S(m()).optional()}).catchall(ue()),outputSchema:x({type:T("object"),properties:te(m(),ge).optional(),required:S(m()).optional()}).catchall(ue()).optional(),annotations:Dw.optional(),execution:qw.optional(),_meta:te(m(),ue()).optional()}),Ta=vo.extend({method:T("tools/list")}),Ra=wo.extend({tools:S(Ah)}),jt=ve.extend({content:S(za).default([]),structuredContent:te(m(),ue()).optional(),isError:Q().optional()}),nR=jt.or(ve.extend({toolResult:ue()})),Lw=go.extend({name:m(),arguments:te(m(),ue()).optional()}),xo=ye.extend({method:T("tools/call"),params:Lw}),Ia=He.extend({method:T("notifications/tools/list_changed"),params:Ve.optional()}),Nh=x({autoRefresh:Q().default(!0),debounceMs:H().int().nonnegative().default(300)}),ko=Oe(["debug","info","notice","warning","error","critical","alert","emergency"]),Uw=Le.extend({level:ko}),Ca=ye.extend({method:T("logging/setLevel"),params:Uw}),Fw=Ve.extend({level:ko,logger:m().optional(),data:ue()}),Vw=He.extend({method:T("notifications/message"),params:Fw}),Hw=x({name:m().optional()}),Jw=x({hints:S(Hw).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Bw=x({mode:Oe(["auto","required","none"]).optional()}),Ww=x({type:T("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:S(za).default([]),structuredContent:x({}).loose().optional(),isError:Q().optional(),_meta:te(m(),ue()).optional()}),Kw=oa("type",[Sa,xa,ka]),Un=oa("type",[Sa,xa,ka,Nw,Ww]),Gw=x({role:So,content:oe([Un,S(Un)]),_meta:te(m(),ue()).optional()}),Yw=go.extend({messages:S(Gw),modelPreferences:Jw.optional(),systemPrompt:m().optional(),includeContext:Oe(["none","thisServer","allServers"]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:S(m()).optional(),metadata:ge.optional(),tools:S(Ah).optional(),toolChoice:Bw.optional()}),Oa=ye.extend({method:T("sampling/createMessage"),params:Yw}),er=ve.extend({model:m(),stopReason:le(Oe(["endTurn","stopSequence","maxTokens"]).or(m())),role:So,content:Kw}),zo=ve.extend({model:m(),stopReason:le(Oe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:So,content:oe([Un,S(Un)])}),Xw=x({type:T("boolean"),title:m().optional(),description:m().optional(),default:Q().optional()}),Qw=x({type:T("string"),title:m().optional(),description:m().optional(),minLength:H().optional(),maxLength:H().optional(),format:Oe(["email","uri","date","date-time"]).optional(),default:m().optional()}),eb=x({type:Oe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),tb=x({type:T("string"),title:m().optional(),description:m().optional(),enum:S(m()),default:m().optional()}),rb=x({type:T("string"),title:m().optional(),description:m().optional(),oneOf:S(x({const:m(),title:m()})),default:m().optional()}),ob=x({type:T("string"),title:m().optional(),description:m().optional(),enum:S(m()),enumNames:S(m()).optional(),default:m().optional()}),nb=oe([tb,rb]),sb=x({type:T("array"),title:m().optional(),description:m().optional(),minItems:H().optional(),maxItems:H().optional(),items:x({type:T("string"),enum:S(m())}),default:S(m()).optional()}),ib=x({type:T("array"),title:m().optional(),description:m().optional(),minItems:H().optional(),maxItems:H().optional(),items:x({anyOf:S(x({const:m(),title:m()}))}),default:S(m()).optional()}),ab=oe([sb,ib]),cb=oe([ob,nb,ab]),ub=oe([cb,Xw,Qw,eb]),lb=go.extend({mode:T("form").optional(),message:m(),requestedSchema:x({type:T("object"),properties:te(m(),ub),required:S(m()).optional()})}),db=go.extend({mode:T("url"),message:m(),elicitationId:m(),url:m().url()}),pb=oe([lb,db]),Aa=ye.extend({method:T("elicitation/create"),params:pb}),fb=Ve.extend({elicitationId:m()}),hb=He.extend({method:T("notifications/elicitation/complete"),params:fb}),Zt=ve.extend({action:Oe(["accept","decline","cancel"]),content:na(t=>t===null?void 0:t,te(m(),oe([m(),H(),Q(),S(m())])).optional())}),mb=x({type:T("ref/resource"),uri:m()});var gb=x({type:T("ref/prompt"),name:m()}),_b=Le.extend({ref:oe([gb,mb]),argument:x({name:m(),value:m()}),context:x({arguments:te(m(),m()).optional()}).optional()}),yb=ye.extend({method:T("completion/complete"),params:_b});var Na=ve.extend({completion:me({values:S(m()).max(100),total:le(H().int()),hasMore:le(Q())})}),vb=x({uri:m().startsWith("file://"),name:m().optional(),_meta:te(m(),ue()).optional()}),wb=ye.extend({method:T("roots/list"),params:Le.optional()}),Ma=ve.extend({roots:S(vb)}),bb=He.extend({method:T("notifications/roots/list_changed"),params:Ve.optional()}),sR=oe([Wn,ua,yb,Ca,$a,wa,pa,ha,_a,Pw,Tw,xo,Ta,Gn,Xn,Qn,ts]),iR=oe([Jn,Kn,Bn,bb,$o]),aR=oe([yt,er,zo,Zt,Ma,Yn,es,vt]),cR=oe([Wn,Oa,Aa,wb,Gn,Xn,Qn,ts]),uR=oe([Jn,Kn,Vw,Iw,va,Ia,Ea,$o,hb]),lR=oe([yt,la,Na,Pa,ba,fa,ma,ya,jt,Ra,Yn,es,vt]),P=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===C.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new sa(n.elicitations,r)}return new t(e,r,o)}},sa=class extends P{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dt(t){return t==="completed"||t==="failed"||t==="cancelled"}var FR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ja(t){let r=Er(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Tr(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Za(t,e){let r=Ee(t,e);if(!r.success)throw r.error;return r.data}var Pb=6e4,Or=class{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(Jn,r=>{this._oncancel(r)}),this.setNotificationHandler(Kn,r=>{this._onprogress(r)}),this.setRequestHandler(Wn,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gn,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new P(C.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Xn,async(r,o)=>{let n=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,o.sessionId))throw new P(C.InvalidParams,`Task not found: ${s}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new P(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let i=await this._taskStore.getTask(s,o.sessionId);if(!i)throw new P(C.InvalidParams,`Task not found: ${s}`);if(!Dt(i.status))return await this._waitForTaskUpdate(s,o.signal,o.sessionId),await n();if(Dt(i.status)){let a=await this._taskStore.getTaskResult(s,o.sessionId);return this._clearTaskQueue(s,o.sessionId),{...a,_meta:{...a._meta,[Mt]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Qn,async(r,o)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new P(C.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(ts,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new P(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(Dt(n.status))throw new P(C.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId,o.sessionId);let s=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!s)throw new P(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(n){throw n instanceof P?n:new P(C.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),P.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.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;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=s=>{o?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Qt(s)||zh(s)?this._onresponse(s):_o(s)?this._onrequest(s,i):kh(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=P.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[Mt]?.taskId,i=n?.sessionId,a=this._taskStore,c=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(s,i))throw new P(C.InvalidParams,`Task not found: ${s}`);c=!0})()),o===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:C.MethodNotFound,message:"Method not found"}};if(s&&u){let g={type:"error",message:h,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,g,i),()=>n?.send(h)).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:h,timestamp:Date.now()},n?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):n?.send(h).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=$h(e.params)?e.params.task:void 0,p=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,f={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(l.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(h,g)},sendRequest:async(h,g,_)=>{if(l.signal.aborted)throw new P(C.ConnectionClosed,"Request was cancelled");let w={..._,relatedRequestId:e.id};s&&!w.relatedTask&&(w.relatedTask={taskId:s});let b=w.relatedTask?.taskId??s;return b&&p&&await p.updateTaskStatus(b,"input_required"),await this.request(h,g,w)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new P(C.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,f)).then(async h=>{if(l.signal.aborted)return;let g={result:h,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},n?.sessionId):await n?.send(g)},async h=>{if(l.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:C.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},n?.sessionId):await n?.send(g)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Qt(e))o(e);else{let i=new P(e.error.code,e.error.message,e.error.data);o(i)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Qt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Qt(e))n(e);else{let i=P.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(i){yield{type:"error",error:i instanceof P?i:new P(C.InternalError,String(i))}}return}let s;try{let i=await this.request(e,vt,o);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new P(C.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},o);if(yield{type:"taskStatus",task:a},Dt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)}:a.status==="failed"?yield{type:"error",error:new P(C.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new P(C.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof P?i:new P(C.InternalError,String(i))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=b=>{l(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){d(b);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Mt]:c}});let h=b=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(b)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let z=b instanceof P?b:new P(C.RequestTimeout,String(b));l(z)};this._responseHandlers.set(p,b=>{if(!o?.signal?.aborted){if(b instanceof Error)return l(b);try{let z=Ee(r,b.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});let g=o?.timeout??Pb,_=()=>h(P.fromError(C.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,o?.maxTotalTimeout,_,o?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=z=>{let E=this._responseHandlers.get(p);E?E(z):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(p),l(z)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Yn,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},es,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Th,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let o=ja(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,s)=>{let i=Za(e,n);return Promise.resolve(r(i,s))})}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,r){let o=ja(e);this._notificationHandlers.set(o,n=>{let s=Za(e,n);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o??this._transport?.sessionId,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&_o(n.message)){let s=n.message.id,i=this._requestResolvers.get(s);i?(i(new P(C.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r,o){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,o);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new P(C.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new P(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let s=await o.getTask(n,r);if(!s)throw new P(C.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,i)=>{await o.storeTaskResult(n,s,i,r);let a=await o.getTask(n,r);if(a){let c=$o.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Dt(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,s,i)=>{let a=await o.getTask(n,r);if(!a)throw new P(C.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Dt(a.status))throw new P(C.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,s,i,r);let c=await o.getTask(n,r);if(c){let u=$o.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Dt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Mh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rs(t,e){let r={...t};for(let o in e){let n=o,s=e[n];if(s===void 0)continue;let i=r[n];Mh(i)&&Mh(s)?r[n]={...i,...s}:r[n]=s}return r}var $_=De(Su(),1),S_=De(b_(),1);function yz(){let t=new $_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,S_.default)(t),t}var Yr=class{constructor(e){this._ajv=e??yz()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Zs=class{constructor(e){this._client=e}async*callToolStream(e,r=jt,o){let n=this._client,s={...o,task:o?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},r,s),a=n.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new P(C.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new P(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof P){yield{type:"error",error:l};return}yield{type:"error",error:new P(C.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._client.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,o){return this._client.requestStream(e,r,o)}};function Ds(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function qs(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Ls(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,o=t.properties;for(let n of Object.keys(o)){let s=o[n];r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[n]=s.default),r[n]!==void 0&&Ls(s,r[n])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ls(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ls(r,e)}}function vz(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Us=class extends Or{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Yr,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ia,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ea,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",va,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Zs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rs(this._capabilities,e)}setRequestHandler(e,r){let n=Er(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s=Tr(n);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=Ee(Aa,c);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=vz(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new P(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new P(C.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(d.task){let b=Ee(vt,h);if(!b.success){let z=b.error instanceof Error?b.error.message:String(b.error);throw new P(C.InvalidParams,`Invalid task creation result: ${z}`)}return b.data}let g=Ee(Zt,h);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new P(C.InvalidParams,`Invalid elicitation result: ${b}`)}let _=g.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ls(w,_.content)}catch{}return _};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Ee(Oa,c);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let _=Ee(vt,p);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new P(C.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let h=d.tools||d.toolChoice?zo:er,g=Ee(h,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new P(C.InvalidParams,`Invalid sampling result: ${_}`)}return g.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:Nt,capabilities:this._capabilities,clientInfo:this._clientInfo}},la,r);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!Fn.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Ds(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&qs(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},yt,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Na,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},yt,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Pa,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ba,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},fa,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ma,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ya,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},yt,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},yt,r)}async callTool(e,r=jt,o){if(this.isToolTaskRequired(e.name))throw new P(C.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this.request({method:"tools/call",params:e},r,o),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new P(C.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let i=s(n.structuredContent);if(!i.valid)throw new P(C.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof P?i:new P(C.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}let o=r.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(r.name),o==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let o=await this.request({method:"tools/list",params:e},Ra,r);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(e,r,o,n){let s=Nh.safeParse(o);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=o,u=async()=>{if(!i){c(null,null);return}try{let d=await n();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var E_=De(P_(),1);function T_(t){if(t)try{return E_.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function Fs(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function R_(t=fetch,e){return e?async(r,o)=>{let n={...e,...o,headers:o?.headers?{...Fs(e.headers),...Fs(o.headers)}:e.headers};return t(r,n)}:t}var Ez=5,Tz=[301,302,303,307,308];function Rz(t,e){return t.protocol===e.protocol&&t.hostname===e.hostname&&t.port===e.port?!0:t.hostname===e.hostname&&t.protocol==="http:"&&t.port===""&&e.protocol==="https:"&&e.port===""}function I_(t,e){let r=Tz.includes(t.status)?t.headers.get("location"):null;try{return r?new URL(r,e):void 0}catch{return}}function Vs(t,e,r,o,n=0){let s=I_(o,e),i=o.status===307||o.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!s||n===Ez||!i)return;let a=new URL(e);if(!((s.username||s.password)&&(s.username!==a.username||s.password!==a.password)||!Rz(a,s)))return Promise.resolve(o.body?.cancel()).then(()=>t(s,{...r,redirect:"manual"})).then(u=>Vs(t,s,r,u,n+1)??u)}var C_=new WeakSet;function Cu(t){let e=(r,o)=>(t??fetch)(r,o);return C_.add(e),e}function dr(t=fetch){return C_.has(t)?t:(e,r)=>r?.redirect==="error"||r?.redirect==="manual"?t(e,r):Promise.resolve(t(e,{...r,redirect:"manual"})).then(o=>Vs(t,e,r,o)??o)}function Hs(t,e){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let r=t.url||e,o=I_(t,r);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(r).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var Ou;Ou=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function Iz(t){return(await Ou).getRandomValues(new Uint8Array(t))}async function Cz(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,o="";for(;o.length<t;){let n=await Iz(t-o.length);for(let s of n)s<r&&(o+=e[s%e.length])}return o}async function Oz(t){return await Cz(t)}async function Az(t){let e=await(await Ou).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Au(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Oz(t),r=await Az(e);return{code_verifier:e,code_challenge:r}}var Se=sh().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:vh.custom,message:"URL must be parseable",fatal:!0}),ci}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),A_=me({resource:m().url(),authorization_servers:S(Se).optional(),jwks_uri:m().url().optional(),scopes_supported:S(m()).optional(),bearer_methods_supported:S(m()).optional(),resource_signing_alg_values_supported:S(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:Q().optional(),authorization_details_types_supported:S(m()).optional(),dpop_signing_alg_values_supported:S(m()).optional(),dpop_bound_access_tokens_required:Q().optional()}),Nu=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,registration_endpoint:Se.optional(),scopes_supported:S(m()).optional(),response_types_supported:S(m()),response_modes_supported:S(m()).optional(),grant_types_supported:S(m()).optional(),token_endpoint_auth_methods_supported:S(m()).optional(),token_endpoint_auth_signing_alg_values_supported:S(m()).optional(),service_documentation:Se.optional(),revocation_endpoint:Se.optional(),revocation_endpoint_auth_methods_supported:S(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:S(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(m()).optional(),code_challenge_methods_supported:S(m()).optional(),client_id_metadata_document_supported:Q().optional()}),Nz=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,userinfo_endpoint:Se.optional(),jwks_uri:Se,registration_endpoint:Se.optional(),scopes_supported:S(m()).optional(),response_types_supported:S(m()),response_modes_supported:S(m()).optional(),grant_types_supported:S(m()).optional(),acr_values_supported:S(m()).optional(),subject_types_supported:S(m()),id_token_signing_alg_values_supported:S(m()),id_token_encryption_alg_values_supported:S(m()).optional(),id_token_encryption_enc_values_supported:S(m()).optional(),userinfo_signing_alg_values_supported:S(m()).optional(),userinfo_encryption_alg_values_supported:S(m()).optional(),userinfo_encryption_enc_values_supported:S(m()).optional(),request_object_signing_alg_values_supported:S(m()).optional(),request_object_encryption_alg_values_supported:S(m()).optional(),request_object_encryption_enc_values_supported:S(m()).optional(),token_endpoint_auth_methods_supported:S(m()).optional(),token_endpoint_auth_signing_alg_values_supported:S(m()).optional(),display_values_supported:S(m()).optional(),claim_types_supported:S(m()).optional(),claims_supported:S(m()).optional(),service_documentation:m().optional(),claims_locales_supported:S(m()).optional(),ui_locales_supported:S(m()).optional(),claims_parameter_supported:Q().optional(),request_parameter_supported:Q().optional(),request_uri_parameter_supported:Q().optional(),require_request_uri_registration:Q().optional(),op_policy_uri:Se.optional(),op_tos_uri:Se.optional(),client_id_metadata_document_supported:Q().optional()}),N_=x({...Nz.shape,...Nu.pick({code_challenge_methods_supported:!0}).shape}),M_=x({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:Ln.number().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:m().optional().catch(void 0)}).strip(),j_=x({error:m(),error_description:m().optional(),error_uri:m().optional()}),O_=Se.optional().or(T("").transform(()=>{})),Mz=x({redirect_uris:S(Se),token_endpoint_auth_method:m().optional(),grant_types:S(m()).optional(),response_types:S(m()).optional(),client_name:m().optional(),client_uri:Se.optional(),logo_uri:O_,scope:m().optional(),contacts:S(m()).optional(),tos_uri:O_,policy_uri:m().optional(),jwks_uri:Se.optional(),jwks:ch().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),jz=x({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional(),issuer:m().optional().catch(void 0)}).strip(),Z_=Mz.merge(jz),y1=x({error:m(),error_description:m().optional()}).strip(),v1=x({token:m(),token_type_hint:m().optional()}).strip();function D_(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function q_({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),o=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var he=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},on=class extends he{};on.errorCode="invalid_request";var pr=class extends he{};pr.errorCode="invalid_client";var fr=class extends he{};fr.errorCode="invalid_grant";var hr=class extends he{};hr.errorCode="unauthorized_client";var nn=class extends he{};nn.errorCode="unsupported_grant_type";var sn=class extends he{};sn.errorCode="invalid_scope";var an=class extends he{};an.errorCode="access_denied";var zt=class extends he{};zt.errorCode="server_error";var cn=class extends he{};cn.errorCode="temporarily_unavailable";var un=class extends he{};un.errorCode="unsupported_response_type";var ln=class extends he{};ln.errorCode="unsupported_token_type";var dn=class extends he{};dn.errorCode="invalid_token";var pn=class extends he{};pn.errorCode="method_not_allowed";var fn=class extends he{};fn.errorCode="too_many_requests";var mr=class extends he{};mr.errorCode="invalid_client_metadata";var hn=class extends he{};hn.errorCode="insufficient_scope";var mn=class extends he{};mn.errorCode="invalid_target";var L_={[on.errorCode]:on,[pr.errorCode]:pr,[fr.errorCode]:fr,[hr.errorCode]:hr,[nn.errorCode]:nn,[sn.errorCode]:sn,[an.errorCode]:an,[zt.errorCode]:zt,[cn.errorCode]:cn,[un.errorCode]:un,[ln.errorCode]:ln,[dn.errorCode]:dn,[pn.errorCode]:pn,[fn.errorCode]:fn,[mr.errorCode]:mr,[hn.errorCode]:hn,[mn.errorCode]:mn};var Pt=class extends Error{constructor(e){super(e??"Unauthorized")}};function Zz(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Mu="code",ju="S256";function Dz(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Zz(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function qz(t,e,r,o){let{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":Lz(n,s,r);return;case"client_secret_post":Uz(n,s,o);return;case"none":Fz(n,o);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Lz(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${o}`)}function Uz(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Fz(t,e){e.set("client_id",t)}async function F_(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let o=j_.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:i}=o,a=L_[n]||zt;return new a(s||"",i)}catch(o){let n=t instanceof Response?Hs(t,t.url):void 0,s=`${e?`HTTP ${e}: `:""}${n??`Invalid OAuth error response: ${o}. Raw body: ${r}`}`;return new zt(s)}}function Vz(t,e){let[r,o]=[t,e];try{[r,o]=[new URL(t).href,new URL(e).href]}catch{}return r===o||r.endsWith("/")&&r.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===r}function qu(t,e){if(t)return typeof t.issuer!="string"?t.issuer==null?t:{...t,issuer:void 0}:Vz(t.issuer,e)?t:void 0}var Hz=M_.omit({issuer:!0}),Jz=Z_.omit({issuer:!0});function V_(t,e){return new Error(`OAuth client information is bound to authorization server ${t.issuer} and is not presented to ${e}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function gn(t,e){try{return await Zu(t,e)}catch(r){if(r instanceof pr||r instanceof hr)return await t.invalidateCredentials?.("all"),await Zu(t,e);if(r instanceof fr)return await t.invalidateCredentials?.("tokens"),await Zu(t,e);throw r}}async function Zu(t,{serverUrl:e,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,l=n;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await J_(c,{fetchFn:s}),!a)try{a=await H_(e,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let j=await Qz(e,{resourceMetadataUrl:l,fetchFn:s});c=j.authorizationServerUrl,u=j.authorizationServerMetadata,a=j.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=String(c),p=await Wz(e,t,a),f=p&&a&&!t.validateResourceURL?a.resource:p,h=o||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,g=await Promise.resolve(t.clientInformation()),_=qu(g,d),w=t.saveClientInformation!==void 0&&!!t.redirectUrl;if(g&&!_&&!w)throw V_(g,d);let b=_?.issuer==null?_:void 0,z=async()=>{try{b&&await t.saveClientInformation?.({...b,issuer:d})}catch{}};if(!_){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let j=u?.client_id_metadata_document_supported===!0,ie=t.clientMetadataUrl;if(ie&&!Bz(ie))throw new mr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ie}`);if(j&&ie)_={client_id:ie,issuer:d},await t.saveClientInformation?.(_);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");_={...await nP(c,{metadata:u,clientMetadata:t.clientMetadata,scope:h,fetchFn:s}),issuer:d},await t.saveClientInformation(_)}}let E=!t.redirectUrl;if(r!==void 0||E){let j=await oP(t,c,{metadata:u,resource:f,authorizationCode:r,fetchFn:s});return await z(),await t.saveTokens({...j,issuer:d}),"AUTHORIZED"}let v=qu(await t.tokens(),d);if(v?.refresh_token&&v.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),v?.refresh_token)try{let j=await rP(c,{metadata:u,clientInformation:_,refreshToken:v.refresh_token,resource:f,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await z(),await t.saveTokens({...j,issuer:d}),"AUTHORIZED"}catch(j){if(!(!(j instanceof he)||j instanceof zt))throw j}let $=t.state?await t.state():void 0,{authorizationUrl:O,codeVerifier:K}=await eP(c,{metadata:u,clientInformation:_,state:$,redirectUrl:t.redirectUrl,scope:h,resource:f});return await t.saveCodeVerifier(K),await t.redirectToAuthorization(O),"REDIRECT"}function Bz(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Wz(t,e,r){let o=D_(t);if(e.validateResourceURL)return await e.validateResourceURL(o,r?.resource);if(r){if(!q_({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function Lu(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,o]=e.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Du(t,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=Du(t,"scope")||void 0,a=Du(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Du(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function H_(t,e,r=fetch){let o=await Yz(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return A_.parse(await o.json())}async function Uu(t,e,r=fetch){try{return await dr(r)(t,{headers:e})}catch(o){if(o instanceof TypeError)return e?Uu(t,void 0,r):void 0;throw o}}function Kz(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function U_(t,e,r=fetch){return await Uu(t,{"MCP-Protocol-Version":e},r)}function Gz(t,e){return!t||!t.ok&&t.status<500&&e!=="/"}async function Yz(t,e,r,o){let n=new URL(t),s=o?.protocolVersion??Nt,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let c=Kz(e,n.pathname);i=new URL(c,o?.metadataServerUrl??n),i.search=n.search}let a=await U_(i,s,r);if(!o?.metadataUrl&&Gz(a,n.pathname)){let c=new URL(`/.well-known/${e}`,n);a=await U_(c,s,r)}return a}function Xz(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),o;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),o}async function J_(t,{fetchFn:e=fetch,protocolVersion:r=Nt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=Xz(t);for(let{url:s,type:i}of n){let a=await Uu(s,o,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Nu.parse(await a.json()):N_.parse(await a.json())}}}async function Qz(t,e){let r,o;try{r=await H_(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",t)));let n=await J_(o,{fetchFn:e?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function B_(t){return typeof t=="string"?t:t.href}async function eP(t,{metadata:e,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Mu))throw new Error(`Incompatible auth server: does not support response type ${Mu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(ju))throw new Error(`Incompatible auth server: does not support code challenge method ${ju}`)}else a=new URL("/authorize",t);let c=await Au(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",Mu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",ju),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),n&&a.searchParams.set("scope",n),n?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",B_(i)),{authorizationUrl:a,codeVerifier:u}}function tP(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function W_(t,{metadata:e,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:i}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",B_(s)),n)await n(c,r,a,e);else if(o){let l=e?.token_endpoint_auth_methods_supported??[],d=Dz(o,l);qz(d,o,c,r)}let u=await dr(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await F_(u);return Hz.parse(await u.json())}async function rP(t,{metadata:e,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await W_(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:i});return{refresh_token:o,...c}}async function oP(t,e,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){let i=async()=>{let l=await t.clientInformation(),d=qu(l,String(e));if(l&&!d)throw V_(l,String(e));return d},a=await i(),c=t.clientMetadata.scope,u;if(t.prepareTokenRequest&&(u=await t.prepareTokenRequest(c)),!u){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await t.codeVerifier();u=tP(n,l,t.redirectUrl)}return a??(a=await i()),W_(e,{metadata:r,tokenRequestParams:u,clientInformation:a,addClientAuthentication:t.addClientAuthentication,resource:o,fetchFn:s})}async function nP(t,{metadata:e,clientMetadata:r,scope:o,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);let i=await dr(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!i.ok)throw await F_(i);return Jz.parse(await i.json())}var _n=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},K_=10,sP=13,gr=32;function Fu(t){}function X_(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Fu,onError:r=Fu,onRetry:o=Fu,onComment:n,maxBufferSize:s}=t,i=[],a=0,c=!0,u,l="",d=0,p,f=!1;function h(v){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){let K=_(v);K!==""&&(i.push(K),a=K.length),g();return}if(v.indexOf(`
|
|
95
95
|
`)===-1&&v.indexOf("\r")===-1){i.push(v),a+=v.length,g();return}i.push(v);let $=i.join("");i.length=0,a=0;let O=_($);O!==""&&(i.push(O),a=O.length),g()}function g(){s!==void 0&&(a+l.length<=s||(f=!0,i.length=0,a=0,u=void 0,l="",d=0,p=void 0,r(new _n(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function _(v){let $=0;if(v.indexOf("\r")===-1){let O=v.indexOf(`
|
|
96
96
|
`,$);for(;O!==-1;){if($===O){d>0&&e({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0,$=O+1,O=v.indexOf(`
|
|
97
97
|
`,$);continue}let K=v.charCodeAt($);if(G_(v,$,K)){let j=v.charCodeAt($+5)===gr?$+6:$+5,ie=v.slice(j,O);if(d===0&&v.charCodeAt(O+1)===K_){e({id:u,event:p,data:ie}),u=void 0,l="",p=void 0,$=O+2,O=v.indexOf(`
|
|
98
98
|
`,$);continue}l=d===0?ie:`${l}
|
|
99
99
|
${ie}`,d++}else Y_(v,$,K)?p=v.slice(v.charCodeAt($+6)===gr?$+7:$+6,O)||void 0:w(v,$,O);$=O+1,O=v.indexOf(`
|
|
100
100
|
`,$)}return v.slice($)}for(;$<v.length;){let O=v.indexOf("\r",$),K=v.indexOf(`
|
|
101
|
-
`,$),j=-1;if(O!==-1&&K!==-1?j=O<K?O:K:O!==-1?O===v.length-1?j=-1:j=O:K!==-1&&(j=K),j===-1)break;w(v,$,j),$=j+1,v.charCodeAt($-1)===
|
|
101
|
+
`,$),j=-1;if(O!==-1&&K!==-1?j=O<K?O:K:O!==-1?O===v.length-1?j=-1:j=O:K!==-1&&(j=K),j===-1)break;w(v,$,j),$=j+1,v.charCodeAt($-1)===sP&&v.charCodeAt($)===K_&&$++}return v.slice($)}function w(v,$,O){if($===O){z();return}let K=v.charCodeAt($);if(G_(v,$,K)){let Et=v.charCodeAt($+5)===gr?$+6:$+5,Bu=v.slice(Et,O);l=d===0?Bu:`${l}
|
|
102
102
|
${Bu}`,d++;return}if(Y_(v,$,K)){p=v.slice(v.charCodeAt($+6)===gr?$+7:$+6,O)||void 0;return}if(K===105&&v.charCodeAt($+1)===100&&v.charCodeAt($+2)===58){let Et=v.slice(v.charCodeAt($+3)===gr?$+4:$+3,O);u=Et.includes("\0")?void 0:Et;return}if(K===58){if(n){let Et=v.slice($,O);n(Et.slice(v.charCodeAt($+1)===gr?2:1))}return}let j=v.slice($,O),ie=j.indexOf(":");if(ie===-1){b(j,"",j);return}let dt=j.slice(0,ie),ae=j.charCodeAt(ie+1)===gr?2:1,Gt=j.slice(ie+ae);b(dt,Gt,j)}function b(v,$,O){switch(v){case"event":p=$||void 0;break;case"data":l=d===0?$:`${l}
|
|
103
|
-
${$}`,d++;break;case"id":u=$.includes("\0")?void 0:$;break;case"retry":/^\d+$/.test($)?o(parseInt($,10)):r(new _n(`Invalid \`retry\` value: "${$}"`,{type:"invalid-retry",value:$,line:O}));break;default:r(new _n(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:$,line:O}));break}}function z(){d>0&&e({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function E(v={}){if(v.consume&&i.length>0){let $=i.join("");w($,0,$.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:E}}function G_(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function Y_(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var Js=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:o,maxBufferSize:n}={}){let s;super({start(i){s=X_({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:o,maxBufferSize:n})},transform(i){s.feed(i)}})}};var sP={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Wt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Bs=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=R_(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Cu(this._fetch),this._fetchWithInit=Cu(this._fetchWithInit)),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??sP}_unfollowedRedirect(e,r){let o=Hs(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new Pt("No auth provider");let e;try{e=await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Pt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=Fs(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=this._fetch??fetch,s={method:"GET",headers:o,signal:this._abortController?.signal},i=await n(this._url,this._followRedirects?s:{...s,redirect:"manual"}),a=this._followRedirects?void 0:Vs(n,this._url,s,i);if(a&&(i=await a),!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Wt(i.status,`Failed to open SSE stream: ${this._unfollowedRedirect(i,this._url)??i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,e),n)}_scheduleReconnection(e,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},n)}_handleSseStream(e,r,o){if(!e)return;let{onresumptiontoken:n,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Js({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await l.read();if(h)break;if(f.id&&(i=f.id,a=!0,n?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let g=Ir.parse(JSON.parse(f.data));Qt(g)&&(c=!0,s!==void 0&&(g.id=s)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(o||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(o||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Pt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:_o(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await dr(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Wt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:g}=Lu(a);if(this._resourceMetadataUrl=h,this._scope=g,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:g,error:_}=Lu(a);if(_==="insufficient_scope"){let w=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Wt(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=w??void 0,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Pt;return this.send(e)}}throw new Wt(a.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(a,this._url)??f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Eh(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let l=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type"),p=T_(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:n},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(g=>Ir.parse(g)):[Ir.parse(f)];for(let g of h)this.onmessage?.(g)}else throw await a.body?.cancel(),new Wt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await dr(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new Wt(o.status,`Failed to terminate session: ${this._unfollowedRedirect(o,this._url)??o.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Ws=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},er,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Zt,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};var Ks=class extends Or{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ko.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let s=this._loggingLevels.get(n);return s?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Yr,this.setRequestHandler(ua,o=>this._oninitialize(o)),this.setNotificationHandler(Bn,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ca,async(o,n)=>{let s=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=o.params,a=ko.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ws(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rs(this._capabilities,e)}setRequestHandler(e,r){let n=Er(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s=Tr(n);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Ee(xo,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let h=Ee(vt,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new P(C.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let f=Ee(jt,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new P(C.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,a)}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})`);break;case"ping":break}}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})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}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})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){qs(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Ds(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Fn.includes(r)?r:Nt,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"},yt)}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){let o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],s=n.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))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},zo,r):this.request({method:"sampling/createMessage",params:e},er,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.");let n=e;return this.request({method:"elicitation/create",params:n},Zt,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},Zt,r);if(s.action==="accept"&&s.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!a.valid)throw new P(C.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof P?i:new P(C.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){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}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ma,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 Vu=De(require("process"),1);var iP=10*1024*1024,Gs=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??iP}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
104
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
105
|
-
`}var Ys=class{constructor(e=Vu.default.stdin,r=Vu.default.stdout,o){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new Gs({maxBufferSize:o?.maxBufferSize})}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{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let o=Q_(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var ey=De(require("path"));var N=De(require("fs")),Ze=De(require("path")),Xs=De(require("os")),yn=require("crypto"),Hu=class extends Error{constructor(e){super(e),this.name="VaultLockError"}},Ju=class extends Hu{lockPath;timeoutMs;constructor(e,r){super(`Timed out waiting to acquire credentials lock at "${e}" after ${r}ms.`),this.name="VaultLockTimeoutError",this.lockPath=e,this.timeoutMs=r}},
|
|
103
|
+
${$}`,d++;break;case"id":u=$.includes("\0")?void 0:$;break;case"retry":/^\d+$/.test($)?o(parseInt($,10)):r(new _n(`Invalid \`retry\` value: "${$}"`,{type:"invalid-retry",value:$,line:O}));break;default:r(new _n(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:$,line:O}));break}}function z(){d>0&&e({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function E(v={}){if(v.consume&&i.length>0){let $=i.join("");w($,0,$.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:E}}function G_(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function Y_(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var Js=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:o,maxBufferSize:n}={}){let s;super({start(i){s=X_({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:o,maxBufferSize:n})},transform(i){s.feed(i)}})}};var iP={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Wt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Bs=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=R_(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=Cu(this._fetch),this._fetchWithInit=Cu(this._fetchWithInit)),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??iP}_unfollowedRedirect(e,r){let o=Hs(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new Pt("No auth provider");let e;try{e=await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Pt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=Fs(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=this._fetch??fetch,s={method:"GET",headers:o,signal:this._abortController?.signal},i=await n(this._url,this._followRedirects?s:{...s,redirect:"manual"}),a=this._followRedirects?void 0:Vs(n,this._url,s,i);if(a&&(i=await a),!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Wt(i.status,`Failed to open SSE stream: ${this._unfollowedRedirect(i,this._url)??i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,e),n)}_scheduleReconnection(e,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},n)}_handleSseStream(e,r,o){if(!e)return;let{onresumptiontoken:n,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Js({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await l.read();if(h)break;if(f.id&&(i=f.id,a=!0,n?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let g=Ir.parse(JSON.parse(f.data));Qt(g)&&(c=!0,s!==void 0&&(g.id=s)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(o||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(o||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:n,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Pt("No auth provider");if(await gn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:_o(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await dr(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Wt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:g}=Lu(a);if(this._resourceMetadataUrl=h,this._scope=g,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:g,error:_}=Lu(a);if(_==="insufficient_scope"){let w=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Wt(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=w??void 0,await gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Pt;return this.send(e)}}throw new Wt(a.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(a,this._url)??f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Eh(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let l=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type"),p=T_(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:n},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(g=>Ir.parse(g)):[Ir.parse(f)];for(let g of h)this.onmessage?.(g)}else throw await a.body?.cancel(),new Wt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await dr(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new Wt(o.status,`Failed to terminate session: ${this._unfollowedRedirect(o,this._url)??o.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Ws=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},er,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Zt,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};var Ks=class extends Or{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ko.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let s=this._loggingLevels.get(n);return s?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Yr,this.setRequestHandler(ua,o=>this._oninitialize(o)),this.setNotificationHandler(Bn,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ca,async(o,n)=>{let s=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=o.params,a=ko.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ws(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rs(this._capabilities,e)}setRequestHandler(e,r){let n=Er(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s=Tr(n);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Ee(xo,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new P(C.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let h=Ee(vt,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new P(C.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let f=Ee(jt,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new P(C.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,a)}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})`);break;case"ping":break}}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})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}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})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){qs(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Ds(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Fn.includes(r)?r:Nt,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"},yt)}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){let o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],s=n.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))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},zo,r):this.request({method:"sampling/createMessage",params:e},er,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.");let n=e;return this.request({method:"elicitation/create",params:n},Zt,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},Zt,r);if(s.action==="accept"&&s.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!a.valid)throw new P(C.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof P?i:new P(C.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){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}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ma,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 Vu=De(require("process"),1);var aP=10*1024*1024,Gs=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??aP}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
104
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),cP(r)}clear(){this._buffer=void 0}};function cP(t){return Ir.parse(JSON.parse(t))}function Q_(t){return JSON.stringify(t)+`
|
|
105
|
+
`}var Ys=class{constructor(e=Vu.default.stdin,r=Vu.default.stdout,o){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new Gs({maxBufferSize:o?.maxBufferSize})}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{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let o=Q_(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var ey=De(require("path"));var N=De(require("fs")),Ze=De(require("path")),Xs=De(require("os")),yn=require("crypto"),Hu=class extends Error{constructor(e){super(e),this.name="VaultLockError"}},Ju=class extends Hu{lockPath;timeoutMs;constructor(e,r){super(`Timed out waiting to acquire credentials lock at "${e}" after ${r}ms.`),this.name="VaultLockTimeoutError",this.lockPath=e,this.timeoutMs=r}},uP=6e4,lP=6e4,dP=50;function pP(t){if(typeof t!="number"||!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){let r=e?.code;return r==="ESRCH"?!1:r==="EPERM"}}var Qs=class{lockPath;isCustomLockPath;timeoutMs;staleTimeoutMs;corruptLockGraceMs;retryIntervalMs;isProcessAlive;currentLockId=null;currentLockIno;constructor(e){if(e?.lockPath)this.lockPath=e.lockPath,this.isCustomLockPath=!0;else{let r=e?.configDir||process.env.XDG_CONFIG_HOME||Ze.default.join(Xs.default.homedir(),".config"),o=e?.configDir?e.configDir:Ze.default.join(r,"iwas");this.lockPath=Ze.default.join(o,"credentials.lock"),this.isCustomLockPath=!!e?.configDir}this.timeoutMs=e?.timeoutMs??uP,this.staleTimeoutMs=e?.staleTimeoutMs??lP,this.corruptLockGraceMs=e?.corruptLockGraceMs??Math.min(this.staleTimeoutMs,1e4),this.retryIntervalMs=e?.retryIntervalMs??dP,this.isProcessAlive=e?.isProcessAliveFn??pP}isHeld(){return this.currentLockId!==null}getCurrentLockId(){return this.currentLockId}async acquire(){if(this.currentLockId)return;let e=Ze.default.dirname(this.lockPath),r=!1;if(!N.default.existsSync(e))try{N.default.mkdirSync(e,{recursive:!0,mode:448}),r=!0}catch{}if(!this.isCustomLockPath||r)try{N.default.chmodSync(e,448)}catch{}let o=Date.now(),n=(0,yn.randomUUID)(),s=this.retryIntervalMs;for(;;){let i=null,a;try{i=N.default.openSync(this.lockPath,"wx",384),a=N.default.fstatSync(i).ino;let p={pid:process.pid,createdAt:Date.now(),lockId:n,hostname:Xs.default.hostname()};N.default.writeFileSync(i,JSON.stringify(p),"utf8"),N.default.closeSync(i),i=null,this.currentLockId=n,this.currentLockIno=a;return}catch(d){if(i!==null){try{N.default.closeSync(i)}catch{}try{let f=N.default.statSync(this.lockPath);(a===void 0||f.ino===a)&&f.size===0&&N.default.unlinkSync(this.lockPath)}catch{}}if(d?.code!=="EEXIST")throw d}if(this.tryCleanStaleLock(),Date.now()-o>=this.timeoutMs)throw new Ju(this.lockPath,this.timeoutMs);let u=Math.floor(Math.random()*25),l=Math.min(s+u,250);s=Math.min(s*1.5,200),await new Promise(d=>setTimeout(d,l))}}async release(){this.releaseSync()}releaseSync(){if(!this.currentLockId)return;let e=this.currentLockId,r=this.currentLockIno;this.currentLockId=null,this.currentLockIno=void 0;let o=Ze.default.dirname(this.lockPath),n=Ze.default.join(o,`.credentials.lock.release.${Date.now()}.${(0,yn.randomUUID)()}`),s=!1;try{if(!N.default.existsSync(this.lockPath))return;try{N.default.linkSync(this.lockPath,n),s=!0}catch{this.releaseSyncLoose(e,r);return}let i=N.default.statSync(n);if(r!==void 0&&i.ino!==r)return;let a=N.default.readFileSync(n,"utf8"),c=null;try{c=JSON.parse(a)}catch{return}if(c&&c.lockId===e&&c.pid===process.pid){let u=N.default.statSync(this.lockPath);if(u.ino===i.ino&&u.nlink>=2)try{N.default.unlinkSync(this.lockPath)}catch{}}}catch{}finally{if(s)try{N.default.unlinkSync(n)}catch{}}}releaseSyncLoose(e,r){try{if(!N.default.existsSync(this.lockPath))return;let o=N.default.statSync(this.lockPath);if(r!==void 0&&o.ino!==r)return;let n=N.default.readFileSync(this.lockPath,"utf8"),s=null;try{s=JSON.parse(n)}catch{return}if(s&&s.lockId===e&&s.pid===process.pid){let i=N.default.statSync(this.lockPath);if(i.ino===o.ino&&i.mtimeMs===o.mtimeMs)try{N.default.unlinkSync(this.lockPath)}catch{}}}catch{}}cleanOrphanGuards(){try{let e=Ze.default.dirname(this.lockPath);if(!N.default.existsSync(e))return;let o=`.${Ze.default.basename(this.lockPath)}.`,n=N.default.readdirSync(e),s=/^(release|stale|corrupt)\.(\d+)\.([0-9a-fA-F-]{36})$/,i=null;try{i=N.default.statSync(this.lockPath)}catch{}let a=Date.now();for(let c of n){if(!c.startsWith(o))continue;let u=s.exec(c.slice(o.length));if(!u)continue;let l=Number(u[2]),d=Ze.default.join(e,c);try{let p=N.default.statSync(d);if(!p.isFile()||p.nlink>1&&i&&p.ino===i.ino)continue;a-l>this.staleTimeoutMs&&N.default.unlinkSync(d)}catch{}}}catch{}}async withLock(e){await this.acquire();try{return await e()}finally{await this.release()}}tryCleanStaleLock(){try{if(this.cleanOrphanGuards(),!N.default.existsSync(this.lockPath))return;let e=N.default.statSync(this.lockPath),r=null;try{let i=N.default.readFileSync(this.lockPath,"utf8");r=JSON.parse(i)}catch{Date.now()-e.mtimeMs>this.corruptLockGraceMs&&this.reclaimCorruptLock(e);return}if(!r||typeof r.createdAt!="number")return;let o=Xs.default.hostname(),n=!r.hostname||r.hostname===o,s=!1;n?s=!(typeof r.pid=="number"&&this.isProcessAlive(r.pid)):s=Date.now()-r.createdAt>this.staleTimeoutMs,s&&this.reclaimStaleLock(r.lockId,e)}catch{}}reclaimStaleLock(e,r){let o=Ze.default.dirname(this.lockPath),n=Ze.default.join(o,`.credentials.lock.stale.${Date.now()}.${(0,yn.randomUUID)()}`);try{N.default.linkSync(this.lockPath,n);try{let s=N.default.readFileSync(n,"utf8");if(JSON.parse(s).lockId!==e)return;let a=N.default.statSync(this.lockPath);a.ino===r.ino&&a.nlink>=2&&N.default.unlinkSync(this.lockPath)}finally{try{N.default.unlinkSync(n)}catch{}}}catch{}}reclaimCorruptLock(e){let r=Ze.default.dirname(this.lockPath),o=Ze.default.join(r,`.credentials.lock.corrupt.${Date.now()}.${(0,yn.randomUUID)()}`);try{N.default.linkSync(this.lockPath,o);try{let n=N.default.statSync(o);if(n.ino!==e.ino||n.size!==e.size||n.mtimeMs!==e.mtimeMs)return;try{let i=N.default.readFileSync(o,"utf8");JSON.parse(i);return}catch{}let s=N.default.statSync(this.lockPath);s.ino===e.ino&&s.nlink>=2&&N.default.unlinkSync(this.lockPath)}finally{try{N.default.unlinkSync(o)}catch{}}}catch{}}};var Kt=class extends Error{profileKey;reason;terminalError;constructor(e,r,o){let n=o?` (${o})`:"";super(`Re-authentication required for profile "${e}": ${r}${n}`),this.name="ReauthenticationRequiredError",this.profileKey=e,this.reason=r,this.terminalError=o}},fP=60,hP=6e4,mP=6e4,ei=class{vault;safetyMarginSeconds;lockTimeoutMs;staleLockTimeoutMs;lockPath;fetchFn;logger;errorLogger;inFlightRefreshes=new Map;constructor(e){this.vault=e?.vault||new Ge,this.safetyMarginSeconds=e?.safetyMarginSeconds??fP,this.lockTimeoutMs=e?.lockTimeoutMs??hP,this.staleLockTimeoutMs=e?.staleLockTimeoutMs??e?.staleTimeoutMs??mP,this.lockPath=e?.lockPath,this.fetchFn=e?.fetchFn,this.logger=e?.logger,this.errorLogger=e?.errorLogger}async getValidAccessToken(e){return(await this.getValidCredentials(e)).accessToken}async getValidCredentials(e){let r=await this.vault.load(e);if(!r)throw new Kt(e,"No credentials found in vault.");return Qr(r,this.safetyMarginSeconds)?await this.refreshWithSingleFlight(e,!1):r}async refresh(e){let r=this.inFlightRefreshes.get(e);return r?await r:await this.refreshWithSingleFlight(e,!0)}async refreshWithSingleFlight(e,r){let o=this.inFlightRefreshes.get(e);if(o&&!r)return await o;let n=this.executeRefreshWithLock(e,r);this.inFlightRefreshes.set(e,n);try{return await n}finally{this.inFlightRefreshes.delete(e)}}async executeRefreshWithLock(e,r){let o=this.lockPath||ey.default.join(this.vault.getConfigDir(),"credentials.lock");return await new Qs({lockPath:o,timeoutMs:this.lockTimeoutMs,staleTimeoutMs:this.staleLockTimeoutMs}).withLock(async()=>{let s=await this.vault.load(e);if(!s)throw new Kt(e,"Credentials missing from vault.");return!r&&!Qr(s,this.safetyMarginSeconds)?(this.logger?.(`Token for profile "${e}" was already refreshed by another process.`),s):await this.performTokenExchange(e,s)})}async performTokenExchange(e,r){if(!r.refreshToken)throw new Kt(e,"Cannot refresh access token: No refresh token stored in credentials.");let o=`${r.serverUrl}/api/auth/oauth2/token`,n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",r.refreshToken),n.set("client_id",r.clientId),r.resource&&n.set("resource",r.resource);let s;try{let d=await Tt(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n,retries:1,fetchFn:this.fetchFn});if(!d.ok)throw new ot(`Token refresh request failed with HTTP ${d.status}`,d.status,d.data);s=d.data}catch(d){if(d instanceof ot){let p=d.data&&typeof d.data=="object"?d.data:{},f=typeof p.error=="string"?p.error:"",h=typeof p.error_description=="string"?p.error_description:d.message,g=f==="invalid_grant"||f==="invalid_client",_=pt(h,[r.refreshToken,r.accessToken]);if(this.errorLogger?.(`Token refresh rejected (${d.status}, ${f||"unknown"}): ${_}`),g){try{await this.vault.delete(e)}catch{}throw new Kt(e,`Refresh token rejected by authorization server: ${_}`,f)}throw new ot(`Token refresh rejected (${d.status}): ${_}`,d.status,d.data)}throw this.errorLogger?.(`Token refresh network/transient error for profile "${e}":
|
|
106
106
|
${d instanceof Error?d.message:String(d)}`),d}if(!s||!s.access_token){let d=s?.error||"unknown_error",p=s?.error_description||"Missing access_token in token response.",f=pt(p,[r.refreshToken,r.accessToken]);if(this.errorLogger?.(`Token response invalid for profile "${e}": ${f}`),d==="invalid_grant"||d==="invalid_client"){try{await this.vault.delete(e)}catch{}throw new Kt(e,f,d)}throw new Error(`Token refresh failed: ${f}`)}let i=ai(s.access_token),a;"organizationId"in i?typeof i.organizationId=="string"?a=i.organizationId:i.organizationId===null?a=null:a=r.organizationId??null:a=r.organizationId??null;let c=s.expires_in?Date.now()+s.expires_in*1e3:typeof i.exp=="number"?i.exp*1e3:Date.now()+3600*1e3,u=s.refresh_token||r.refreshToken,l={serverUrl:r.serverUrl,clientId:r.clientId,accessToken:s.access_token,refreshToken:u,tokenType:s.token_type||r.tokenType||"Bearer",scope:s.scope||r.scope,resource:r.resource,organizationId:a,expiresAt:c,updatedAt:Date.now()};try{await this.vault.save(e,l)}catch(d){try{await this.vault.delete(e)}catch{}let p=d instanceof Error?d.message:String(d);throw this.errorLogger?.(`Failed to persist refreshed credentials for profile "${e}": ${p}`),new Kt(e,`Failed to persist refreshed credentials to vault: ${p}`,"persistence_failure")}return this.logger?.(`Successfully refreshed credentials for profile "${e}"
|
|
107
|
-
(expires: ${new Date(c).toISOString()}).`),l}};var Ie="iwas",Xr="1.0.
|
|
108
|
-
`)),i=await n.load(o);if(!i)throw new Error(`No IWAS credentials for profile "${o}". Run \`${Ie} login --server ${e}\` first.`);let a=new ei({vault:n,fetchFn:t.fetchFn,logger:s,errorLogger:s}),c=
|
|
107
|
+
(expires: ${new Date(c).toISOString()}).`),l}};var Ie="iwas",Xr="1.0.2";var ty="iwas-mcp-bridge",gP=6e4;function _P(t){let{provider:e,profileKey:r}=t,o=t.baseFetch??fetch,n=t.now??Date.now,s=null,i=0,a=async c=>{if(!c&&s!==null&&n()<i-gP)return s;let u=c?await e.refresh(r):await e.getValidCredentials(r);return s=u.accessToken,i=u.expiresAt,u.accessToken};return async(c,u)=>{let l=async p=>{let f=new Headers(u?.headers);return f.set("Authorization",`Bearer ${p}`),o(c,{...u,headers:f})},d=await l(await a(!1));return d.status!==401?d:l(await a(!0))}}async function ry(t={}){let e=yr(t.server),r=(t.clientId||_r).trim(),o=Yt(e,r),n=t.vault||new Ge,s=t.logger||(b=>process.stderr.write(`${b}
|
|
108
|
+
`)),i=await n.load(o);if(!i)throw new Error(`No IWAS credentials for profile "${o}". Run \`${Ie} login --server ${e}\` first.`);let a=new ei({vault:n,fetchFn:t.fetchFn,logger:s,errorLogger:s}),c=_P({provider:a,profileKey:o,baseFetch:t.fetchFn}),u=t.resource||i.resource||ii(e),l=new Us({name:ty,version:Xr},{capabilities:{}}),d=new Bs(new URL(u),{fetch:c});try{await l.connect(d)}catch(b){throw await l.close().catch(()=>{}),b}let p=l.getServerCapabilities()??{},f={};p.tools&&(f.tools={}),p.resources&&(f.resources={}),p.prompts&&(f.prompts={});let h=new Ks({name:ty,version:Xr},{capabilities:f});f.tools&&(h.setRequestHandler(Ta,async b=>l.listTools(b.params)),h.setRequestHandler(xo,async b=>l.callTool(b.params))),f.resources&&(h.setRequestHandler(pa,async b=>l.listResources(b.params)),h.setRequestHandler(ha,async b=>l.listResourceTemplates(b.params)),h.setRequestHandler(_a,async b=>l.readResource(b.params))),f.prompts&&(h.setRequestHandler(wa,async b=>l.listPrompts(b.params)),h.setRequestHandler($a,async b=>l.getPrompt(b.params)));let g=t.serverTransport??new Ys;await h.connect(g);let _=!1,w=async()=>{_||(_=!0,await l.close().catch(()=>{}),await h.close().catch(()=>{}))};process.once("SIGINT",()=>{w().finally(()=>process.exit(0))}),process.once("SIGTERM",()=>{w().finally(()=>process.exit(0))})}function ny(t=e=>process.stdout.write(e)){let e=`
|
|
109
109
|
${Ie} \u2014 Intelligent WiFi Access & Presence Service (IWAS) MCP CLI
|
|
110
110
|
|
|
111
111
|
USAGE:
|
|
@@ -138,7 +138,7 @@ EXAMPLES:
|
|
|
138
138
|
${Ie} logout --force
|
|
139
139
|
${Ie} mcp
|
|
140
140
|
`;t(e.trimStart()+`
|
|
141
|
-
`)}async function sy(t=process.argv.slice(2),e){let r=e?.stdout||(_=>process.stdout.write(_)),o=e?.stderr||(_=>process.stderr.write(_)),n=e?.exit||(_=>process.exit(_)),s;try{s=(0,oy.parseArgs)({args:t,options:{server:{type:"string",short:"s"},resource:{type:"string",short:"r"},"client-id":{type:"string",short:"c"},scopes:{type:"string"},"no-browser":{type:"boolean",default:!1},json:{type:"boolean",default:!1},force:{type:"boolean",short:"f",default:!1},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1}},allowPositionals:!0,strict:!0})}catch(_){let w=_ instanceof Error?_.message:String(_);o(`Error: ${w}
|
|
141
|
+
`)}async function sy(t=process.argv.slice(2),e){let r=e?.stdout||(_=>process.stdout.write(_)),o=e?.stderr||(_=>process.stderr.write(_)),n=e?.exit||(_=>process.exit(_)),s;try{s=(0,oy.parseArgs)({args:t,options:{server:{type:"string",short:"s"},resource:{type:"string",short:"r"},"client-id":{type:"string",short:"c"},scopes:{type:"string"},"no-browser":{type:"boolean",default:!1},browser:{type:"boolean",default:!0},json:{type:"boolean",default:!1},force:{type:"boolean",short:"f",default:!1},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1}},allowPositionals:!0,strict:!0})}catch(_){let w=_ instanceof Error?_.message:String(_);o(`Error: ${w}
|
|
142
142
|
`),o(`Run \`${Ie} --help\` for usage.
|
|
143
143
|
`),n(1);return}let{values:i,positionals:a}=s;if(i.version){r(`${Ie} v${Xr}
|
|
144
144
|
`);return}let c=a[0]||"";if(i.help||!c||c==="help"){ny(r);return}let u=typeof i.server=="string"?i.server:void 0,l=typeof i.resource=="string"?i.resource:void 0,d=typeof i["client-id"]=="string"?i["client-id"]:void 0,p=typeof i.scopes=="string"?i.scopes:void 0,f=i["no-browser"]===!0,h=i.json===!0,g=e?.vault;try{switch(c){case"login":{await ol({server:u,resource:l,clientId:d,scopes:p,noBrowser:f,json:h,vault:g,logger:_=>r(`${_}
|