@reqvire-org/ads 0.3.33 → 0.3.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/behavior-libraries.mjs +93 -0
  2. package/dist/behaviors.mjs +0 -6
  3. package/dist/bootstrap-ds/ds.config.json +1 -0
  4. package/dist/capture.mjs +3 -3
  5. package/dist/check.mjs +2 -0
  6. package/dist/config.mjs +4 -0
  7. package/dist/lint-config.mjs +7 -0
  8. package/dist/mcp/build-status.mjs +1 -1
  9. package/dist/mcp/catalog.mjs +4 -2
  10. package/dist/mcp/draft-discovery.mjs +55 -0
  11. package/dist/mcp/drafts.mjs +135 -16
  12. package/dist/mcp/preview-watch.mjs +13 -2
  13. package/dist/mcp/preview-widget.bundle.js +14 -14
  14. package/dist/mcp/server.mjs +109 -27
  15. package/dist/scenario-inspector.mjs +5 -5
  16. package/dist/scenario-program.mjs +36 -0
  17. package/dist/scenario-registry.mjs +90 -0
  18. package/dist/scenarios-compiler.mjs +66 -22
  19. package/dist/scenarios.mjs +2 -1
  20. package/dist/showcase/client.bundle.js +39 -39
  21. package/dist/showcase/comparison.js +29 -5
  22. package/dist/showcase/draft-navigation.js +41 -0
  23. package/dist/showcase/index.html +1 -2
  24. package/dist/showcase/preview-state.js +19 -0
  25. package/dist/showcase/style.css +2 -2
  26. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  27. package/dist/skills/ads-break-ui/references/drafts.md +43 -4
  28. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  29. package/dist/skills/ads-designer/SKILL.md +7 -0
  30. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  31. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  32. package/dist/skills/ads-designer/references/drafts.md +43 -4
  33. package/dist/skills/ads-designer/references/validation.md +6 -0
  34. package/dist/skills/ads-import/SKILL.md +4 -0
  35. package/dist/skills/ads-import/references/behaviors.md +10 -0
  36. package/dist/skills/ads-import/references/drafts.md +43 -4
  37. package/dist/skills/ads-import/references/validation.md +6 -0
  38. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  39. package/dist/skills/ads-motion/references/drafts.md +43 -4
  40. package/dist/skills/ads-motion/references/validation.md +6 -0
  41. package/dist/skills/ads-port/SKILL.md +8 -1
  42. package/dist/skills/ads-port/references/behaviors.md +10 -0
  43. package/dist/skills/ads-port/references/drafts.md +43 -4
  44. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  45. package/dist/skills/ads-port/references/validation.md +6 -0
  46. package/dist/unit-contracts.mjs +2 -2
  47. package/dist/units.mjs +6 -0
  48. package/dist/verification/browser.d.mts +27 -0
  49. package/dist/verification.mjs +3 -0
  50. package/docs/ARCHITECTURE.md +82 -0
  51. package/docs/CHANGELOG.md +92 -0
  52. package/docs/GUIDE.md +29 -4
  53. package/docs/MCP.md +44 -4
  54. package/package.json +6 -4
@@ -1,49 +1,49 @@
1
- var yv=Object.defineProperty;var Bt=(e,t)=>{for(var r in t)yv(e,r,{get:t[r],enumerable:!0})};var vv=Object.create,xc=Object.defineProperty,zv=Object.getOwnPropertyDescriptor,Rv=Object.getOwnPropertyNames,wv=Object.getPrototypeOf,xv=Object.prototype.hasOwnProperty,nS=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sS=(e,t)=>{let r={};for(var o in e)xc(r,o,{get:e[o],enumerable:!0});return t&&xc(r,Symbol.toStringTag,{value:"Module"}),r},Pv=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var n=Rv(t),s=0,i=n.length,a;s<i;s++)a=n[s],!xv.call(e,a)&&a!==r&&xc(e,a,{get:(l=>t[l]).bind(null,a),enumerable:!(o=zv(t,a))||o.enumerable});return e},iS=(e,t,r)=>(r=e!=null?vv(wv(e)):{},Pv(t||!e||!e.__esModule?xc(r,"default",{value:e,enumerable:!0}):r,e));var Tv=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),aS=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Ev=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),kv=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function cS(e){return typeof e=="string"&&aS.has(e.replace(/#$/,""))}function lS(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(Tv.has(r))return"2020-12";if(aS.has(r))return"2019-09";if(Ev.has(r)||kv.has(r))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var p={};Bt(p,{$brand:()=>id,$input:()=>Em,$output:()=>Tm,NEVER:()=>Is,TimePrecision:()=>Im,ZodAny:()=>_f,ZodArray:()=>zf,ZodBase64:()=>Xl,ZodBase64URL:()=>Ql,ZodBigInt:()=>gn,ZodBigIntFormat:()=>ru,ZodBoolean:()=>fn,ZodCIDRv4:()=>Gl,ZodCIDRv6:()=>Yl,ZodCUID:()=>Fl,ZodCUID2:()=>Hl,ZodCatch:()=>Df,ZodCodec:()=>ai,ZodCustom:()=>ci,ZodCustomStringFormat:()=>mn,ZodDate:()=>oi,ZodDefault:()=>qf,ZodDiscriminatedUnion:()=>wf,ZodE164:()=>eu,ZodEmail:()=>Ll,ZodEmoji:()=>Zl,ZodEnum:()=>un,ZodError:()=>dR,ZodExactOptional:()=>Of,ZodFile:()=>Cf,ZodFirstPartyTypeKind:()=>eg,ZodFunction:()=>Yf,ZodGUID:()=>Qs,ZodIPv4:()=>Wl,ZodIPv6:()=>Kl,ZodISODate:()=>Ol,ZodISODateTime:()=>Il,ZodISODuration:()=>Al,ZodISOTime:()=>Nl,ZodIntersection:()=>xf,ZodIssueCode:()=>tg,ZodJWT:()=>tu,ZodKSUID:()=>Bl,ZodLazy:()=>Kf,ZodLiteral:()=>$f,ZodMAC:()=>hf,ZodMap:()=>Ef,ZodNaN:()=>Hf,ZodNanoID:()=>Dl,ZodNever:()=>yf,ZodNonOptional:()=>au,ZodNull:()=>Sf,ZodNullable:()=>Af,ZodNumber:()=>hn,ZodNumberFormat:()=>oo,ZodObject:()=>ni,ZodOptional:()=>iu,ZodPipe:()=>ii,ZodPrefault:()=>jf,ZodPreprocess:()=>Vf,ZodPromise:()=>Gf,ZodReadonly:()=>Jf,ZodRealError:()=>Ye,ZodRecord:()=>ln,ZodSet:()=>kf,ZodString:()=>dn,ZodStringFormat:()=>le,ZodSuccess:()=>Zf,ZodSymbol:()=>ff,ZodTemplateLiteral:()=>Wf,ZodTransform:()=>If,ZodTuple:()=>Pf,ZodType:()=>ee,ZodULID:()=>Vl,ZodURL:()=>ri,ZodUUID:()=>qt,ZodUndefined:()=>gf,ZodUnion:()=>si,ZodUnknown:()=>bf,ZodVoid:()=>vf,ZodXID:()=>Jl,ZodXor:()=>Rf,_ZodString:()=>jl,_default:()=>Mf,_function:()=>V_,any:()=>ou,array:()=>_,base64:()=>u_,base64url:()=>d_,bigint:()=>z_,boolean:()=>k,catch:()=>Ff,check:()=>J_,cidrv4:()=>c_,cidrv6:()=>l_,clone:()=>Ue,codec:()=>Z_,coerce:()=>li,config:()=>Se,core:()=>Gt,cuid:()=>e_,cuid2:()=>t_,custom:()=>B_,date:()=>E_,decode:()=>af,decodeAsync:()=>lf,describe:()=>W_,discriminatedUnion:()=>xr,e164:()=>p_,email:()=>Ul,emoji:()=>XS,encode:()=>sf,encodeAsync:()=>cf,endsWith:()=>Qo,enum:()=>K,exactOptional:()=>Nf,file:()=>M_,flattenError:()=>Us,float32:()=>__,float64:()=>b_,formatError:()=>Zs,fromJSONSchema:()=>eb,function:()=>V_,getErrorMap:()=>hR,globalRegistry:()=>xe,gt:()=>Nt,gte:()=>De,guid:()=>JS,hash:()=>S_,hex:()=>g_,hostname:()=>f_,httpUrl:()=>YS,includes:()=>Yo,instanceof:()=>G_,int:()=>ql,int32:()=>y_,int64:()=>R_,intersection:()=>bt,invertCodec:()=>D_,ipv4:()=>s_,ipv6:()=>a_,iso:()=>it,json:()=>X_,jwt:()=>m_,keyof:()=>k_,ksuid:()=>n_,lazy:()=>Pr,length:()=>to,literal:()=>b,locales:()=>Ws,looseObject:()=>U,looseRecord:()=>O_,lowercase:()=>Ko,lt:()=>Ot,lte:()=>st,mac:()=>i_,map:()=>N_,maxLength:()=>eo,maxSize:()=>vr,meta:()=>K_,mime:()=>en,minLength:()=>Kt,minSize:()=>At,multipleOf:()=>yr,nan:()=>U_,nanoid:()=>QS,nativeEnum:()=>q_,negative:()=>Rl,never:()=>nu,nonnegative:()=>xl,nonoptional:()=>Uf,nonpositive:()=>wl,normalize:()=>tn,null:()=>Mt,nullable:()=>ei,nullish:()=>j_,number:()=>R,object:()=>f,optional:()=>L,overwrite:()=>_t,parse:()=>rf,parseAsync:()=>of,partialRecord:()=>I_,pipe:()=>Ml,positive:()=>zl,prefault:()=>Lf,preprocess:()=>Yt,prettifyError:()=>yd,promise:()=>H_,property:()=>Pl,readonly:()=>Bf,record:()=>T,refine:()=>Xf,regex:()=>Wo,regexes:()=>nt,registry:()=>tl,safeDecode:()=>df,safeDecodeAsync:()=>mf,safeEncode:()=>uf,safeEncodeAsync:()=>pf,safeParse:()=>Xs,safeParseAsync:()=>nf,set:()=>A_,setErrorMap:()=>mR,size:()=>Qr,slugify:()=>sn,startsWith:()=>Xo,strictObject:()=>$_,string:()=>c,stringFormat:()=>h_,stringbool:()=>Y_,success:()=>L_,superRefine:()=>Qf,symbol:()=>x_,templateLiteral:()=>F_,toJSONSchema:()=>ro,toLowerCase:()=>on,toUpperCase:()=>nn,transform:()=>su,treeifyError:()=>bd,trim:()=>rn,tuple:()=>Tf,uint32:()=>v_,uint64:()=>w_,ulid:()=>r_,undefined:()=>P_,union:()=>C,unknown:()=>j,uppercase:()=>Go,url:()=>pn,util:()=>Y,uuid:()=>BS,uuidv4:()=>WS,uuidv6:()=>KS,uuidv7:()=>GS,void:()=>T_,xid:()=>o_,xor:()=>C_});var Gt={};Bt(Gt,{$ZodAny:()=>Kp,$ZodArray:()=>em,$ZodAsyncError:()=>St,$ZodBase64:()=>Lp,$ZodBase64URL:()=>Up,$ZodBigInt:()=>Kc,$ZodBigIntFormat:()=>Vp,$ZodBoolean:()=>Vs,$ZodCIDRv4:()=>qp,$ZodCIDRv6:()=>Mp,$ZodCUID:()=>wp,$ZodCUID2:()=>xp,$ZodCatch:()=>_m,$ZodCheck:()=>ue,$ZodCheckBigIntFormat:()=>ep,$ZodCheckEndsWith:()=>pp,$ZodCheckGreaterThan:()=>Fc,$ZodCheckIncludes:()=>up,$ZodCheckLengthEquals:()=>ip,$ZodCheckLessThan:()=>Dc,$ZodCheckLowerCase:()=>cp,$ZodCheckMaxLength:()=>np,$ZodCheckMaxSize:()=>tp,$ZodCheckMimeType:()=>hp,$ZodCheckMinLength:()=>sp,$ZodCheckMinSize:()=>rp,$ZodCheckMultipleOf:()=>Xd,$ZodCheckNumberFormat:()=>Qd,$ZodCheckOverwrite:()=>fp,$ZodCheckProperty:()=>mp,$ZodCheckRegex:()=>ap,$ZodCheckSizeEquals:()=>op,$ZodCheckStartsWith:()=>dp,$ZodCheckStringFormat:()=>Bo,$ZodCheckUpperCase:()=>lp,$ZodCodec:()=>Bs,$ZodCustom:()=>Pm,$ZodCustomStringFormat:()=>Fp,$ZodDate:()=>Qp,$ZodDefault:()=>hm,$ZodDiscriminatedUnion:()=>om,$ZodE164:()=>Zp,$ZodEmail:()=>yp,$ZodEmoji:()=>zp,$ZodEncodeError:()=>fr,$ZodEnum:()=>cm,$ZodError:()=>Ls,$ZodExactOptional:()=>pm,$ZodFile:()=>um,$ZodFunction:()=>Rm,$ZodGUID:()=>_p,$ZodIPv4:()=>Op,$ZodIPv6:()=>Np,$ZodISODate:()=>$p,$ZodISODateTime:()=>kp,$ZodISODuration:()=>Ip,$ZodISOTime:()=>Cp,$ZodIntersection:()=>nm,$ZodJWT:()=>Dp,$ZodKSUID:()=>Ep,$ZodLazy:()=>xm,$ZodLiteral:()=>lm,$ZodMAC:()=>Ap,$ZodMap:()=>im,$ZodNaN:()=>bm,$ZodNanoID:()=>Rp,$ZodNever:()=>Yp,$ZodNonOptional:()=>gm,$ZodNull:()=>Wp,$ZodNullable:()=>mm,$ZodNumber:()=>Wc,$ZodNumberFormat:()=>Hp,$ZodObject:()=>US,$ZodObjectJIT:()=>tm,$ZodOptional:()=>Yc,$ZodPipe:()=>Xc,$ZodPrefault:()=>fm,$ZodPreprocess:()=>ym,$ZodPromise:()=>wm,$ZodReadonly:()=>vm,$ZodRealError:()=>Ge,$ZodRecord:()=>sm,$ZodRegistry:()=>el,$ZodSet:()=>am,$ZodString:()=>Xr,$ZodStringFormat:()=>ce,$ZodSuccess:()=>Sm,$ZodSymbol:()=>Jp,$ZodTemplateLiteral:()=>zm,$ZodTransform:()=>dm,$ZodTuple:()=>Gc,$ZodType:()=>X,$ZodULID:()=>Pp,$ZodURL:()=>vp,$ZodUUID:()=>bp,$ZodUndefined:()=>Bp,$ZodUnion:()=>Js,$ZodUnknown:()=>Gp,$ZodVoid:()=>Xp,$ZodXID:()=>Tp,$ZodXor:()=>rm,$brand:()=>id,$constructor:()=>S,$input:()=>Em,$output:()=>Tm,Doc:()=>Hs,JSONSchema:()=>FS,JSONSchemaGenerator:()=>$l,NEVER:()=>Is,TimePrecision:()=>Im,_any:()=>Qm,_array:()=>ih,_base64:()=>_l,_base64url:()=>bl,_bigint:()=>Jm,_boolean:()=>Hm,_catch:()=>oR,_check:()=>DS,_cidrv4:()=>gl,_cidrv6:()=>Sl,_coercedBigint:()=>Bm,_coercedBoolean:()=>Vm,_coercedDate:()=>nh,_coercedNumber:()=>jm,_coercedString:()=>$m,_cuid:()=>ll,_cuid2:()=>ul,_custom:()=>ch,_date:()=>oh,_decode:()=>Oc,_decodeAsync:()=>Ac,_default:()=>eR,_discriminatedUnion:()=>Dz,_e164:()=>yl,_email:()=>rl,_emoji:()=>al,_encode:()=>Ic,_encodeAsync:()=>Nc,_endsWith:()=>Qo,_enum:()=>Wz,_file:()=>ah,_float32:()=>Um,_float64:()=>Zm,_gt:()=>Nt,_gte:()=>De,_guid:()=>Ks,_includes:()=>Yo,_int:()=>Lm,_int32:()=>Dm,_int64:()=>Wm,_intersection:()=>Fz,_ipv4:()=>hl,_ipv6:()=>fl,_isoDate:()=>Nm,_isoDateTime:()=>Om,_isoDuration:()=>qm,_isoTime:()=>Am,_jwt:()=>vl,_ksuid:()=>ml,_lazy:()=>aR,_length:()=>to,_literal:()=>Gz,_lowercase:()=>Ko,_lt:()=>Ot,_lte:()=>st,_mac:()=>Cm,_map:()=>Jz,_max:()=>st,_maxLength:()=>eo,_maxSize:()=>vr,_mime:()=>en,_min:()=>De,_minLength:()=>Kt,_minSize:()=>At,_multipleOf:()=>yr,_nan:()=>sh,_nanoid:()=>cl,_nativeEnum:()=>Kz,_negative:()=>Rl,_never:()=>th,_nonnegative:()=>xl,_nonoptional:()=>tR,_nonpositive:()=>wl,_normalize:()=>tn,_null:()=>Xm,_nullable:()=>Qz,_number:()=>Mm,_optional:()=>Xz,_overwrite:()=>_t,_parse:()=>Fo,_parseAsync:()=>Ho,_pipe:()=>nR,_positive:()=>zl,_promise:()=>cR,_property:()=>Pl,_readonly:()=>sR,_record:()=>Vz,_refine:()=>lh,_regex:()=>Wo,_safeDecode:()=>Mc,_safeDecodeAsync:()=>Lc,_safeEncode:()=>qc,_safeEncodeAsync:()=>jc,_safeParse:()=>Vo,_safeParseAsync:()=>Jo,_set:()=>Bz,_size:()=>Qr,_slugify:()=>sn,_startsWith:()=>Xo,_string:()=>km,_stringFormat:()=>an,_stringbool:()=>mh,_success:()=>rR,_superRefine:()=>uh,_symbol:()=>Gm,_templateLiteral:()=>iR,_toLowerCase:()=>on,_toUpperCase:()=>nn,_transform:()=>Yz,_trim:()=>rn,_tuple:()=>Hz,_uint32:()=>Fm,_uint64:()=>Km,_ulid:()=>dl,_undefined:()=>Ym,_union:()=>Uz,_unknown:()=>eh,_uppercase:()=>Go,_url:()=>Gs,_uuid:()=>ol,_uuidv4:()=>nl,_uuidv6:()=>sl,_uuidv7:()=>il,_void:()=>rh,_xid:()=>pl,_xor:()=>Zz,clone:()=>Ue,config:()=>Se,createStandardJSONSchemaMethod:()=>cn,createToJSONSchemaMethod:()=>hh,decode:()=>oz,decodeAsync:()=>sz,describe:()=>dh,encode:()=>rz,encodeAsync:()=>nz,extractDefs:()=>Rr,finalize:()=>wr,flattenError:()=>Us,formatError:()=>Zs,globalConfig:()=>Kr,globalRegistry:()=>xe,initializeContext:()=>zr,isValidBase64:()=>jp,isValidBase64URL:()=>qS,isValidJWT:()=>MS,locales:()=>Ws,meta:()=>ph,parse:()=>$c,parseAsync:()=>Cc,prettifyError:()=>yd,process:()=>se,regexes:()=>nt,registry:()=>tl,safeDecode:()=>az,safeDecodeAsync:()=>lz,safeEncode:()=>iz,safeEncodeAsync:()=>cz,safeParse:()=>vd,safeParseAsync:()=>zd,toDotPath:()=>fS,toJSONSchema:()=>ro,treeifyError:()=>bd,util:()=>Y,version:()=>gp});var uS,Is=Object.freeze({status:"aborted"});function S(e,t,r){function o(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let h=d[m];h in a||(a[h]=u[h].bind(a))}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var l;let u=r?.Parent?new s:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();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(e)}),Object.defineProperty(i,"name",{value:e}),i}var id=Symbol("zod_brand"),St=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},fr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(uS=globalThis).__zod_globalConfig??(uS.__zod_globalConfig={});var Kr=globalThis.__zod_globalConfig;function Se(e){return e&&Object.assign(Kr,e),Kr}var Y={};Bt(Y,{BIGINT_FORMAT_RANGES:()=>gd,Class:()=>cd,NUMBER_FORMAT_RANGES:()=>fd,aborted:()=>br,allowsEval:()=>dd,assert:()=>Nv,assertEqual:()=>$v,assertIs:()=>Iv,assertNever:()=>Ov,assertNotEqual:()=>Cv,assignProp:()=>Sr,base64ToUint8Array:()=>pS,base64urlToUint8Array:()=>Yv,cached:()=>Zo,captureStackTrace:()=>Ec,cleanEnum:()=>Gv,cleanRegex:()=>As,clone:()=>Ue,cloneDef:()=>qv,createTransparentProxy:()=>Dv,defineLazy:()=>re,esc:()=>Tc,escapeRegex:()=>pt,explicitlyAborted:()=>Sd,extend:()=>Vv,finalizeIssue:()=>Ze,floatSafeRemainder:()=>ld,getElementAtPath:()=>Mv,getEnumValues:()=>Ns,getLengthableOrigin:()=>js,getParsedType:()=>Zv,getSizableOrigin:()=>Ms,hexToUint8Array:()=>Qv,isObject:()=>Gr,isPlainObject:()=>_r,issue:()=>Do,joinValues:()=>Pc,jsonStringifyReplacer:()=>Uo,merge:()=>Bv,mergeDefs:()=>Wt,normalizeParams:()=>P,nullish:()=>gr,numKeys:()=>Uv,objectClone:()=>Av,omit:()=>Hv,optionalKeys:()=>hd,parsedType:()=>_d,partial:()=>Wv,pick:()=>Fv,prefixIssues:()=>Ke,primitiveTypes:()=>md,promiseAllObject:()=>jv,propertyKeyTypes:()=>qs,randomString:()=>Lv,required:()=>Kv,safeExtend:()=>Jv,shallowClone:()=>pd,slugify:()=>ud,stringifyPrimitive:()=>kc,uint8ArrayToBase64:()=>mS,uint8ArrayToBase64url:()=>Xv,uint8ArrayToHex:()=>ez,unwrapMessage:()=>Os});function $v(e){return e}function Cv(e){return e}function Iv(e){}function Ov(e){throw new Error("Unexpected value in exhaustive check")}function Nv(e){}function Ns(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Pc(e,t="|"){return e.map(r=>kc(r)).join(t)}function Uo(e,t){return typeof t=="bigint"?t.toString():t}function Zo(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function gr(e){return e==null}function As(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ld(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var dS=Symbol("evaluating");function re(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==dS)return o===void 0&&(o=dS,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Av(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Sr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function qv(e){return Wt(e._zod.def)}function Mv(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function jv(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let s=0;s<t.length;s++)n[t[s]]=o[s];return n})}function Lv(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Tc(e){return JSON.stringify(e)}function ud(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ec="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var dd=Zo(()=>{if(Kr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function _r(e){if(Gr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Gr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function pd(e){return _r(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Uv(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Zv=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},qs=new Set(["string","number","symbol"]),md=new Set(["string","number","bigint","boolean","symbol","undefined"]);function pt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function P(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Dv(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,s){return t??(t=e()),Reflect.set(t,o,n,s)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function kc(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function hd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var fd={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]},gd={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Fv(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=r.shape[a])}return Sr(this,"shape",i),i},checks:[]});return Ue(e,s)}function Hv(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return Sr(this,"shape",i),i},checks:[]});return Ue(e,s)}function Vv(e,t){if(!_r(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Sr(this,"shape",s),s}});return Ue(e,n)}function Jv(e,t){if(!_r(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Sr(this,"shape",o),o}});return Ue(e,r)}function Bv(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Sr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ue(e,r)}function Wv(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(l[u]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return Sr(this,"shape",l),l},checks:[]});return Ue(t,i)}function Kv(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._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 e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return Sr(this,"shape",s),s}});return Ue(t,o)}function br(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Sd(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ke(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function Os(e){return typeof e=="string"?e:e?.message}function Ze(e,t,r){let o=e.message?e.message:Os(e.inst?._zod.def?.error?.(e))??Os(t?.error?.(e))??Os(r.customError?.(e))??Os(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=i),a}function Ms(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function js(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _d(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Do(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function Gv(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pS(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function mS(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Yv(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return pS(t+r)}function Xv(e){return mS(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Qv(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function ez(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var cd=class{constructor(...t){}};var hS=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Uo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ls=S("$ZodError",hS),Ge=S("$ZodError",hS,{Parent:Error});function Us(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Zs(e,t=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(t(i));else{let l=r,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}}};return o(e),r}function bd(e,t=r=>r.message){let r={errors:[]},o=(n,s=[])=>{var i,a;for(let l of n.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(u=>o({issues:u},[...s,...l.path]));else if(l.code==="invalid_key")o({issues:l.issues},[...s,...l.path]);else if(l.code==="invalid_element")o({issues:l.issues},[...s,...l.path]);else{let u=[...s,...l.path];if(u.length===0){r.errors.push(t(l));continue}let d=r,m=0;for(;m<u.length;){let h=u[m],g=m===u.length-1;typeof h=="string"?(d.properties??(d.properties={}),(i=d.properties)[h]??(i[h]={errors:[]}),d=d.properties[h]):(d.items??(d.items=[]),(a=d.items)[h]??(a[h]={errors:[]}),d=d.items[h]),g&&d.errors.push(t(l)),m++}}};return o(e),r}function fS(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function yd(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${fS(o.path)}`);return t.join(`
2
- `)}var Fo=e=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new St;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map(l=>Ze(l,s,Se())));throw Ec(a,n?.callee),a}return i.value},$c=Fo(Ge),Ho=e=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(n?.Err??e)(i.issues.map(l=>Ze(l,s,Se())));throw Ec(a,n?.callee),a}return i.value},Cc=Ho(Ge),Vo=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new St;return s.issues.length?{success:!1,error:new(e??Ls)(s.issues.map(i=>Ze(i,n,Se())))}:{success:!0,data:s.value}},vd=Vo(Ge),Jo=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Ze(i,n,Se())))}:{success:!0,data:s.value}},zd=Jo(Ge),Ic=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Fo(e)(t,r,n)},rz=Ic(Ge),Oc=e=>(t,r,o)=>Fo(e)(t,r,o),oz=Oc(Ge),Nc=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ho(e)(t,r,n)},nz=Nc(Ge),Ac=e=>async(t,r,o)=>Ho(e)(t,r,o),sz=Ac(Ge),qc=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Vo(e)(t,r,n)},iz=qc(Ge),Mc=e=>(t,r,o)=>Vo(e)(t,r,o),az=Mc(Ge),jc=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Jo(e)(t,r,n)},cz=jc(Ge),Lc=e=>async(t,r,o)=>Jo(e)(t,r,o),lz=Lc(Ge);var nt={};Bt(nt,{base64:()=>jd,base64url:()=>Uc,bigint:()=>Vd,boolean:()=>Bd,browserEmail:()=>Sz,cidrv4:()=>qd,cidrv6:()=>Md,cuid:()=>Rd,cuid2:()=>wd,date:()=>Zd,datetime:()=>Fd,domain:()=>yz,duration:()=>kd,e164:()=>Ud,email:()=>Cd,emoji:()=>Id,extendedDuration:()=>uz,guid:()=>$d,hex:()=>vz,hostname:()=>bz,html5Email:()=>hz,httpProtocol:()=>Ld,idnEmail:()=>gz,integer:()=>Jd,ipv4:()=>Od,ipv6:()=>Nd,ksuid:()=>Td,lowercase:()=>Gd,mac:()=>Ad,md5_base64:()=>Rz,md5_base64url:()=>wz,md5_hex:()=>zz,nanoid:()=>Ed,null:()=>Wd,number:()=>Zc,rfc5322Email:()=>fz,sha1_base64:()=>Pz,sha1_base64url:()=>Tz,sha1_hex:()=>xz,sha256_base64:()=>kz,sha256_base64url:()=>$z,sha256_hex:()=>Ez,sha384_base64:()=>Iz,sha384_base64url:()=>Oz,sha384_hex:()=>Cz,sha512_base64:()=>Az,sha512_base64url:()=>qz,sha512_hex:()=>Nz,string:()=>Hd,time:()=>Dd,ulid:()=>xd,undefined:()=>Kd,unicodeEmail:()=>gS,uppercase:()=>Yd,uuid:()=>Yr,uuid4:()=>dz,uuid6:()=>pz,uuid7:()=>mz,xid:()=>Pd});var Rd=/^[cC][0-9a-z]{6,}$/,wd=/^[0-9a-z]+$/,xd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Pd=/^[0-9a-vA-V]{20}$/,Td=/^[A-Za-z0-9]{27}$/,Ed=/^[a-zA-Z0-9_-]{21}$/,kd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uz=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$d=/^([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})$/,Yr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,dz=Yr(4),pz=Yr(6),mz=Yr(7),Cd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,fz=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,gS=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,gz=gS,Sz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_z="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Id(){return new RegExp(_z,"u")}var Od=/^(?:(?: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])$/,Nd=/^(([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}|:))$/,Ad=e=>{let t=pt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},qd=/^((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])$/,Md=/^(([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])$/,jd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Uc=/^[A-Za-z0-9_-]*$/,bz=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,yz=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Ld=/^https?$/,Ud=/^\+[1-9]\d{6,14}$/,SS="(?:(?:\\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])))",Zd=new RegExp(`^${SS}$`);function _S(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Dd(e){return new RegExp(`^${_S(e)}$`)}function Fd(e){let t=_S({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${SS}T(?:${o})$`)}var Hd=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Vd=/^-?\d+n?$/,Jd=/^-?\d+$/,Zc=/^-?\d+(?:\.\d+)?$/,Bd=/^(?:true|false)$/i,Wd=/^null$/i;var Kd=/^undefined$/i;var Gd=/^[^A-Z]*$/,Yd=/^[^a-z]*$/,vz=/^[0-9a-fA-F]*$/;function Ds(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Fs(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var zz=/^[0-9a-fA-F]{32}$/,Rz=Ds(22,"=="),wz=Fs(22),xz=/^[0-9a-fA-F]{40}$/,Pz=Ds(27,"="),Tz=Fs(27),Ez=/^[0-9a-fA-F]{64}$/,kz=Ds(43,"="),$z=Fs(43),Cz=/^[0-9a-fA-F]{96}$/,Iz=Ds(64,""),Oz=Fs(64),Nz=/^[0-9a-fA-F]{128}$/,Az=Ds(86,"=="),qz=Fs(86);var ue=S("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),yS={number:"number",bigint:"bigint",object:"date"},Dc=S("$ZodCheckLessThan",(e,t)=>{ue.init(e,t);let r=yS[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fc=S("$ZodCheckGreaterThan",(e,t)=>{ue.init(e,t);let r=yS[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xd=S("$ZodCheckMultipleOf",(e,t)=>{ue.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ld(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Qd=S("$ZodCheckNumberFormat",(e,t)=>{ue.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=fd[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=n,a.maximum=s,r&&(a.pattern=Jd)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});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:e,origin:o,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}a<n&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),ep=S("$ZodCheckBigIntFormat",(e,t)=>{ue.init(e,t);let[r,o]=gd[t.format];e._zod.onattach.push(n=>{let s=n._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o}),e._zod.check=n=>{let s=n.value;s<r&&n.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>o&&n.issues.push({origin:"bigint",input:s,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),tp=S("$ZodCheckMaxSize",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:Ms(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),rp=S("$ZodCheckMinSize",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:Ms(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),op=S("$ZodCheckSizeEquals",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=o=>{let n=o.value,s=n.size;if(s===t.size)return;let i=s>t.size;o.issues.push({origin:Ms(n),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),np=S("$ZodCheckMaxLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let i=js(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),sp=S("$ZodCheckMinLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let i=js(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ip=S("$ZodCheckLengthEquals",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!gr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,s=n.length;if(s===t.length)return;let i=js(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Bo=S("$ZodCheckStringFormat",(e,t)=>{var r,o;ue.init(e,t),e._zod.onattach.push(n=>{let s=n._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),ap=S("$ZodCheckRegex",(e,t)=>{Bo.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),cp=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Gd),Bo.init(e,t)}),lp=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Yd),Bo.init(e,t)}),up=S("$ZodCheckIncludes",(e,t)=>{ue.init(e,t);let r=pt(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),dp=S("$ZodCheckStartsWith",(e,t)=>{ue.init(e,t);let r=new RegExp(`^${pt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),pp=S("$ZodCheckEndsWith",(e,t)=>{ue.init(e,t);let r=new RegExp(`.*${pt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function bS(e,t,r){e.issues.length&&t.issues.push(...Ke(r,e.issues))}var mp=S("$ZodCheckProperty",(e,t)=>{ue.init(e,t),e._zod.check=r=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>bS(n,r,t.property));bS(o,r,t.property)}}),hp=S("$ZodCheckMimeType",(e,t)=>{ue.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(o=>{o._zod.bag.mime=t.mime}),e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),fp=S("$ZodCheckOverwrite",(e,t)=>{ue.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Hs=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
1
+ var Mv=Object.defineProperty;var Jt=(e,t)=>{for(var r in t)Mv(e,r,{get:t[r],enumerable:!0})};var jv=Object.create,kc=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,Uv=Object.getOwnPropertyNames,Zv=Object.getPrototypeOf,Dv=Object.prototype.hasOwnProperty,fS=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gS=(e,t)=>{let r={};for(var o in e)kc(r,o,{get:e[o],enumerable:!0});return t&&kc(r,Symbol.toStringTag,{value:"Module"}),r},Fv=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var n=Uv(t),s=0,i=n.length,a;s<i;s++)a=n[s],!Dv.call(e,a)&&a!==r&&kc(e,a,{get:(c=>t[c]).bind(null,a),enumerable:!(o=Lv(t,a))||o.enumerable});return e},SS=(e,t,r)=>(r=e!=null?jv(Zv(e)):{},Fv(t||!e||!e.__esModule?kc(r,"default",{value:e,enumerable:!0}):r,e));var Hv=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),_S=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Vv=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Jv=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function bS(e){return typeof e=="string"&&_S.has(e.replace(/#$/,""))}function yS(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(Hv.has(r))return"2020-12";if(_S.has(r))return"2019-09";if(Vv.has(r)||Jv.has(r))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var p={};Jt(p,{$brand:()=>dd,$input:()=>Oh,$output:()=>Ih,NEVER:()=>Ns,TimePrecision:()=>Mh,ZodAny:()=>wf,ZodArray:()=>Tf,ZodBase64:()=>ru,ZodBase64URL:()=>ou,ZodBigInt:()=>mn,ZodBigIntFormat:()=>iu,ZodBoolean:()=>hn,ZodCIDRv4:()=>eu,ZodCIDRv6:()=>tu,ZodCUID:()=>Bl,ZodCUID2:()=>Wl,ZodCatch:()=>Bf,ZodCodec:()=>li,ZodCustom:()=>ui,ZodCustomStringFormat:()=>dn,ZodDate:()=>si,ZodDefault:()=>Zf,ZodDiscriminatedUnion:()=>kf,ZodE164:()=>nu,ZodEmail:()=>Fl,ZodEmoji:()=>Vl,ZodEnum:()=>cn,ZodError:()=>Ew,ZodExactOptional:()=>jf,ZodFile:()=>Af,ZodFirstPartyTypeKind:()=>sg,ZodFunction:()=>rg,ZodGUID:()=>ti,ZodIPv4:()=>Xl,ZodIPv6:()=>Ql,ZodISODate:()=>Ml,ZodISODateTime:()=>Al,ZodISODuration:()=>Ll,ZodISOTime:()=>jl,ZodIntersection:()=>$f,ZodIssueCode:()=>ig,ZodJWT:()=>su,ZodKSUID:()=>Yl,ZodLazy:()=>eg,ZodLiteral:()=>qf,ZodMAC:()=>bf,ZodMap:()=>Of,ZodNaN:()=>Kf,ZodNanoID:()=>Jl,ZodNever:()=>xf,ZodNonOptional:()=>du,ZodNull:()=>zf,ZodNullable:()=>Uf,ZodNumber:()=>pn,ZodNumberFormat:()=>ro,ZodObject:()=>ii,ZodOptional:()=>uu,ZodPipe:()=>ci,ZodPrefault:()=>Ff,ZodPreprocess:()=>Gf,ZodPromise:()=>tg,ZodReadonly:()=>Yf,ZodRealError:()=>We,ZodRecord:()=>an,ZodSet:()=>Nf,ZodString:()=>ln,ZodStringFormat:()=>ce,ZodSuccess:()=>Jf,ZodSymbol:()=>yf,ZodTemplateLiteral:()=>Qf,ZodTransform:()=>Mf,ZodTuple:()=>Cf,ZodType:()=>ee,ZodULID:()=>Kl,ZodURL:()=>ni,ZodUUID:()=>Nt,ZodUndefined:()=>vf,ZodUnion:()=>ai,ZodUnknown:()=>Rf,ZodVoid:()=>Pf,ZodXID:()=>Gl,ZodXor:()=>Ef,_ZodString:()=>Dl,_default:()=>Df,_function:()=>rb,any:()=>au,array:()=>_,base64:()=>v_,base64url:()=>z_,bigint:()=>O_,boolean:()=>$,catch:()=>Wf,check:()=>ob,cidrv4:()=>b_,cidrv6:()=>y_,clone:()=>Le,codec:()=>X_,coerce:()=>di,config:()=>ge,core:()=>Kt,cuid:()=>d_,cuid2:()=>p_,custom:()=>nb,date:()=>L_,decode:()=>pf,decodeAsync:()=>mf,describe:()=>sb,discriminatedUnion:()=>Rr,e164:()=>w_,email:()=>Hl,emoji:()=>l_,encode:()=>df,encodeAsync:()=>hf,endsWith:()=>Yo,enum:()=>K,exactOptional:()=>Lf,file:()=>W_,flattenError:()=>Ds,float32:()=>k_,float64:()=>$_,formatError:()=>Fs,fromJSONSchema:()=>db,function:()=>rb,getErrorMap:()=>Cw,globalRegistry:()=>Pe,gt:()=>It,gte:()=>Ze,guid:()=>o_,hash:()=>E_,hex:()=>T_,hostname:()=>P_,httpUrl:()=>c_,includes:()=>Ko,instanceof:()=>ab,int:()=>Ul,int32:()=>C_,int64:()=>N_,intersection:()=>St,invertCodec:()=>Q_,ipv4:()=>g_,ipv6:()=>__,iso:()=>ot,json:()=>lb,jwt:()=>R_,keyof:()=>U_,ksuid:()=>f_,lazy:()=>xr,length:()=>eo,literal:()=>b,locales:()=>Gs,looseObject:()=>Z,looseRecord:()=>H_,lowercase:()=>Bo,lt:()=>Ct,lte:()=>rt,mac:()=>S_,map:()=>V_,maxLength:()=>Qr,maxSize:()=>yr,meta:()=>ib,mime:()=>Xo,minLength:()=>Wt,minSize:()=>Ot,multipleOf:()=>br,nan:()=>Y_,nanoid:()=>u_,nativeEnum:()=>B_,negative:()=>Tl,never:()=>cu,nonnegative:()=>kl,nonoptional:()=>Vf,nonpositive:()=>El,normalize:()=>Qo,null:()=>qt,nullable:()=>ri,nullish:()=>K_,number:()=>R,object:()=>f,optional:()=>L,overwrite:()=>gt,parse:()=>cf,parseAsync:()=>lf,partialRecord:()=>F_,pipe:()=>Zl,positive:()=>Pl,prefault:()=>Hf,preprocess:()=>Gt,prettifyError:()=>xd,promise:()=>tb,property:()=>$l,readonly:()=>Xf,record:()=>E,refine:()=>og,regex:()=>Jo,regexes:()=>tt,registry:()=>sl,safeDecode:()=>gf,safeDecodeAsync:()=>_f,safeEncode:()=>ff,safeEncodeAsync:()=>Sf,safeParse:()=>ei,safeParseAsync:()=>uf,set:()=>J_,setErrorMap:()=>$w,size:()=>Xr,slugify:()=>on,startsWith:()=>Go,strictObject:()=>Z_,string:()=>l,stringFormat:()=>x_,stringbool:()=>cb,success:()=>G_,superRefine:()=>ng,symbol:()=>A_,templateLiteral:()=>eb,toJSONSchema:()=>to,toLowerCase:()=>tn,toUpperCase:()=>rn,transform:()=>lu,treeifyError:()=>Rd,trim:()=>en,tuple:()=>If,uint32:()=>I_,uint64:()=>q_,ulid:()=>h_,undefined:()=>M_,union:()=>I,unknown:()=>j,uppercase:()=>Wo,url:()=>un,util:()=>G,uuid:()=>n_,uuidv4:()=>s_,uuidv6:()=>i_,uuidv7:()=>a_,void:()=>j_,xid:()=>m_,xor:()=>D_});var Kt={};Jt(Kt,{$ZodAny:()=>eh,$ZodArray:()=>sh,$ZodAsyncError:()=>ft,$ZodBase64:()=>Hp,$ZodBase64URL:()=>Vp,$ZodBigInt:()=>Qc,$ZodBigIntFormat:()=>Gp,$ZodBoolean:()=>Bs,$ZodCIDRv4:()=>Zp,$ZodCIDRv6:()=>Dp,$ZodCUID:()=>kp,$ZodCUID2:()=>$p,$ZodCatch:()=>wh,$ZodCheck:()=>le,$ZodCheckBigIntFormat:()=>sp,$ZodCheckEndsWith:()=>Sp,$ZodCheckGreaterThan:()=>Bc,$ZodCheckIncludes:()=>fp,$ZodCheckLengthEquals:()=>dp,$ZodCheckLessThan:()=>Jc,$ZodCheckLowerCase:()=>hp,$ZodCheckMaxLength:()=>lp,$ZodCheckMaxSize:()=>ip,$ZodCheckMimeType:()=>bp,$ZodCheckMinLength:()=>up,$ZodCheckMinSize:()=>ap,$ZodCheckMultipleOf:()=>op,$ZodCheckNumberFormat:()=>np,$ZodCheckOverwrite:()=>yp,$ZodCheckProperty:()=>_p,$ZodCheckRegex:()=>pp,$ZodCheckSizeEquals:()=>cp,$ZodCheckStartsWith:()=>gp,$ZodCheckStringFormat:()=>Vo,$ZodCheckUpperCase:()=>mp,$ZodCodec:()=>Ks,$ZodCustom:()=>Ch,$ZodCustomStringFormat:()=>Wp,$ZodDate:()=>nh,$ZodDefault:()=>bh,$ZodDiscriminatedUnion:()=>ch,$ZodE164:()=>Jp,$ZodEmail:()=>xp,$ZodEmoji:()=>Tp,$ZodEncodeError:()=>mr,$ZodEnum:()=>hh,$ZodError:()=>Zs,$ZodExactOptional:()=>Sh,$ZodFile:()=>fh,$ZodFunction:()=>Eh,$ZodGUID:()=>wp,$ZodIPv4:()=>jp,$ZodIPv6:()=>Lp,$ZodISODate:()=>qp,$ZodISODateTime:()=>Np,$ZodISODuration:()=>Mp,$ZodISOTime:()=>Ap,$ZodIntersection:()=>lh,$ZodJWT:()=>Bp,$ZodKSUID:()=>Op,$ZodLazy:()=>$h,$ZodLiteral:()=>mh,$ZodMAC:()=>Up,$ZodMap:()=>dh,$ZodNaN:()=>Rh,$ZodNanoID:()=>Ep,$ZodNever:()=>rh,$ZodNonOptional:()=>vh,$ZodNull:()=>Qp,$ZodNullable:()=>_h,$ZodNumber:()=>Xc,$ZodNumberFormat:()=>Kp,$ZodObject:()=>YS,$ZodObjectJIT:()=>ih,$ZodOptional:()=>tl,$ZodPipe:()=>rl,$ZodPrefault:()=>yh,$ZodPreprocess:()=>xh,$ZodPromise:()=>kh,$ZodReadonly:()=>Ph,$ZodRealError:()=>Be,$ZodRecord:()=>uh,$ZodRegistry:()=>nl,$ZodSet:()=>ph,$ZodString:()=>Yr,$ZodStringFormat:()=>ae,$ZodSuccess:()=>zh,$ZodSymbol:()=>Yp,$ZodTemplateLiteral:()=>Th,$ZodTransform:()=>gh,$ZodTuple:()=>el,$ZodType:()=>Y,$ZodULID:()=>Cp,$ZodURL:()=>Pp,$ZodUUID:()=>Rp,$ZodUndefined:()=>Xp,$ZodUnion:()=>Ws,$ZodUnknown:()=>th,$ZodVoid:()=>oh,$ZodXID:()=>Ip,$ZodXor:()=>ah,$brand:()=>dd,$constructor:()=>S,$input:()=>Oh,$output:()=>Ih,Doc:()=>Js,JSONSchema:()=>e_,JSONSchemaGenerator:()=>Nl,NEVER:()=>Ns,TimePrecision:()=>Mh,_any:()=>nm,_array:()=>dm,_base64:()=>zl,_base64url:()=>wl,_bigint:()=>Yh,_boolean:()=>Kh,_catch:()=>yw,_check:()=>QS,_cidrv4:()=>yl,_cidrv6:()=>vl,_coercedBigint:()=>Xh,_coercedBoolean:()=>Gh,_coercedDate:()=>lm,_coercedNumber:()=>Fh,_coercedString:()=>qh,_cuid:()=>hl,_cuid2:()=>ml,_custom:()=>hm,_date:()=>cm,_decode:()=>Mc,_decodeAsync:()=>Lc,_default:()=>Sw,_discriminatedUnion:()=>sw,_e164:()=>Rl,_email:()=>il,_emoji:()=>dl,_encode:()=>Ac,_encodeAsync:()=>jc,_endsWith:()=>Yo,_enum:()=>dw,_file:()=>pm,_float32:()=>Vh,_float64:()=>Jh,_gt:()=>It,_gte:()=>Ze,_guid:()=>Ys,_includes:()=>Ko,_int:()=>Hh,_int32:()=>Bh,_int64:()=>Qh,_intersection:()=>iw,_ipv4:()=>_l,_ipv6:()=>bl,_isoDate:()=>Lh,_isoDateTime:()=>jh,_isoDuration:()=>Zh,_isoTime:()=>Uh,_jwt:()=>xl,_ksuid:()=>Sl,_lazy:()=>Rw,_length:()=>eo,_literal:()=>hw,_lowercase:()=>Bo,_lt:()=>Ct,_lte:()=>rt,_mac:()=>Ah,_map:()=>lw,_max:()=>rt,_maxLength:()=>Qr,_maxSize:()=>yr,_mime:()=>Xo,_min:()=>Ze,_minLength:()=>Wt,_minSize:()=>Ot,_multipleOf:()=>br,_nan:()=>um,_nanoid:()=>pl,_nativeEnum:()=>pw,_negative:()=>Tl,_never:()=>im,_nonnegative:()=>kl,_nonoptional:()=>_w,_nonpositive:()=>El,_normalize:()=>Qo,_null:()=>om,_nullable:()=>gw,_number:()=>Dh,_optional:()=>fw,_overwrite:()=>gt,_parse:()=>Zo,_parseAsync:()=>Do,_pipe:()=>vw,_positive:()=>Pl,_promise:()=>xw,_property:()=>$l,_readonly:()=>zw,_record:()=>cw,_refine:()=>mm,_regex:()=>Jo,_safeDecode:()=>Zc,_safeDecodeAsync:()=>Fc,_safeEncode:()=>Uc,_safeEncodeAsync:()=>Dc,_safeParse:()=>Fo,_safeParseAsync:()=>Ho,_set:()=>uw,_size:()=>Xr,_slugify:()=>on,_startsWith:()=>Go,_string:()=>Nh,_stringFormat:()=>nn,_stringbool:()=>_m,_success:()=>bw,_superRefine:()=>fm,_symbol:()=>tm,_templateLiteral:()=>ww,_toLowerCase:()=>tn,_toUpperCase:()=>rn,_transform:()=>mw,_trim:()=>en,_tuple:()=>aw,_uint32:()=>Wh,_uint64:()=>em,_ulid:()=>fl,_undefined:()=>rm,_union:()=>ow,_unknown:()=>sm,_uppercase:()=>Wo,_url:()=>Xs,_uuid:()=>al,_uuidv4:()=>cl,_uuidv6:()=>ll,_uuidv7:()=>ul,_void:()=>am,_xid:()=>gl,_xor:()=>nw,clone:()=>Le,config:()=>ge,createStandardJSONSchemaMethod:()=>sn,createToJSONSchemaMethod:()=>bm,decode:()=>yz,decodeAsync:()=>zz,describe:()=>gm,encode:()=>bz,encodeAsync:()=>vz,extractDefs:()=>zr,finalize:()=>wr,flattenError:()=>Ds,formatError:()=>Fs,globalConfig:()=>Wr,globalRegistry:()=>Pe,initializeContext:()=>vr,isValidBase64:()=>Fp,isValidBase64URL:()=>BS,isValidJWT:()=>WS,locales:()=>Gs,meta:()=>Sm,parse:()=>Nc,parseAsync:()=>qc,prettifyError:()=>xd,process:()=>ne,regexes:()=>tt,registry:()=>sl,safeDecode:()=>Rz,safeDecodeAsync:()=>Pz,safeEncode:()=>wz,safeEncodeAsync:()=>xz,safeParse:()=>Pd,safeParseAsync:()=>Td,toDotPath:()=>PS,toJSONSchema:()=>to,treeifyError:()=>Rd,util:()=>G,version:()=>vp});var vS,Ns=Object.freeze({status:"aborted"});function S(e,t,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(e))return;a._zod.traits.add(e),t(a,c);let u=i.prototype,d=Object.keys(u);for(let h=0;h<d.length;h++){let m=d[h];m in a||(a[m]=u[m].bind(a))}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let u=r?.Parent?new s:this;o(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();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(e)}),Object.defineProperty(i,"name",{value:e}),i}var dd=Symbol("zod_brand"),ft=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},mr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(vS=globalThis).__zod_globalConfig??(vS.__zod_globalConfig={});var Wr=globalThis.__zod_globalConfig;function ge(e){return e&&Object.assign(Wr,e),Wr}var G={};Jt(G,{BIGINT_FORMAT_RANGES:()=>vd,Class:()=>hd,NUMBER_FORMAT_RANGES:()=>yd,aborted:()=>_r,allowsEval:()=>gd,assert:()=>Yv,assertEqual:()=>Bv,assertIs:()=>Kv,assertNever:()=>Gv,assertNotEqual:()=>Wv,assignProp:()=>gr,base64ToUint8Array:()=>wS,base64urlToUint8Array:()=>mz,cached:()=>Lo,captureStackTrace:()=>Ic,cleanEnum:()=>hz,cleanRegex:()=>Ms,clone:()=>Le,cloneDef:()=>Qv,createTransparentProxy:()=>sz,defineLazy:()=>re,esc:()=>Cc,escapeRegex:()=>lt,explicitlyAborted:()=>zd,extend:()=>cz,finalizeIssue:()=>Ue,floatSafeRemainder:()=>md,getElementAtPath:()=>ez,getEnumValues:()=>As,getLengthableOrigin:()=>Us,getParsedType:()=>nz,getSizableOrigin:()=>Ls,hexToUint8Array:()=>gz,isObject:()=>Kr,isPlainObject:()=>Sr,issue:()=>Uo,joinValues:()=>$c,jsonStringifyReplacer:()=>jo,merge:()=>uz,mergeDefs:()=>Bt,normalizeParams:()=>P,nullish:()=>fr,numKeys:()=>oz,objectClone:()=>Xv,omit:()=>az,optionalKeys:()=>bd,parsedType:()=>wd,partial:()=>dz,pick:()=>iz,prefixIssues:()=>Je,primitiveTypes:()=>_d,promiseAllObject:()=>tz,propertyKeyTypes:()=>js,randomString:()=>rz,required:()=>pz,safeExtend:()=>lz,shallowClone:()=>Sd,slugify:()=>fd,stringifyPrimitive:()=>Oc,uint8ArrayToBase64:()=>RS,uint8ArrayToBase64url:()=>fz,uint8ArrayToHex:()=>Sz,unwrapMessage:()=>qs});function Bv(e){return e}function Wv(e){return e}function Kv(e){}function Gv(e){throw new Error("Unexpected value in exhaustive check")}function Yv(e){}function As(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function $c(e,t="|"){return e.map(r=>Oc(r)).join(t)}function jo(e,t){return typeof t=="bigint"?t.toString():t}function Lo(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function fr(e){return e==null}function Ms(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function md(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var zS=Symbol("evaluating");function re(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==zS)return o===void 0&&(o=zS,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Xv(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function gr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Qv(e){return Bt(e._zod.def)}function ez(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function tz(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let s=0;s<t.length;s++)n[t[s]]=o[s];return n})}function rz(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Cc(e){return JSON.stringify(e)}function fd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ic="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var gd=Lo(()=>{if(Wr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Sr(e){if(Kr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Kr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Sd(e){return Sr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function oz(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var nz=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},js=new Set(["string","number","symbol"]),_d=new Set(["string","number","bigint","boolean","symbol","undefined"]);function lt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Le(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function P(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function sz(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,s){return t??(t=e()),Reflect.set(t,o,n,s)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Oc(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function bd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var yd={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]},vd={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function iz(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Bt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=r.shape[a])}return gr(this,"shape",i),i},checks:[]});return Le(e,s)}function az(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Bt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return gr(this,"shape",i),i},checks:[]});return Le(e,s)}function cz(e,t){if(!Sr(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Bt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return gr(this,"shape",s),s}});return Le(e,n)}function lz(e,t){if(!Sr(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Bt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return gr(this,"shape",o),o}});return Le(e,r)}function uz(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Bt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return gr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Le(e,r)}function dz(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Bt(t._zod.def,{get shape(){let a=t._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]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return gr(this,"shape",c),c},checks:[]});return Le(t,i)}function pz(e,t,r){let o=Bt(t._zod.def,{get shape(){let n=t._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 e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return gr(this,"shape",s),s}});return Le(t,o)}function _r(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function zd(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Je(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function qs(e){return typeof e=="string"?e:e?.message}function Ue(e,t,r){let o=e.message?e.message:qs(e.inst?._zod.def?.error?.(e))??qs(t?.error?.(e))??qs(r.customError?.(e))??qs(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=i),a}function Ls(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Us(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function wd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Uo(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function hz(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function wS(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function RS(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function mz(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return wS(t+r)}function fz(e){return RS(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gz(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function Sz(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var hd=class{constructor(...t){}};var xS=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Zs=S("$ZodError",xS),Be=S("$ZodError",xS,{Parent:Error});function Ds(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Fs(e,t=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(t(i));else{let c=r,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return o(e),r}function Rd(e,t=r=>r.message){let r={errors:[]},o=(n,s=[])=>{var i,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>o({issues:u},[...s,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...s,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...s,...c.path]);else{let u=[...s,...c.path];if(u.length===0){r.errors.push(t(c));continue}let d=r,h=0;for(;h<u.length;){let m=u[h],g=h===u.length-1;typeof m=="string"?(d.properties??(d.properties={}),(i=d.properties)[m]??(i[m]={errors:[]}),d=d.properties[m]):(d.items??(d.items=[]),(a=d.items)[m]??(a[m]={errors:[]}),d=d.items[m]),g&&d.errors.push(t(c)),h++}}};return o(e),r}function PS(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function xd(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${PS(o.path)}`);return t.join(`
2
+ `)}var Zo=e=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new ft;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map(c=>Ue(c,s,ge())));throw Ic(a,n?.callee),a}return i.value},Nc=Zo(Be),Do=e=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(n?.Err??e)(i.issues.map(c=>Ue(c,s,ge())));throw Ic(a,n?.callee),a}return i.value},qc=Do(Be),Fo=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new ft;return s.issues.length?{success:!1,error:new(e??Zs)(s.issues.map(i=>Ue(i,n,ge())))}:{success:!0,data:s.value}},Pd=Fo(Be),Ho=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Ue(i,n,ge())))}:{success:!0,data:s.value}},Td=Ho(Be),Ac=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Zo(e)(t,r,n)},bz=Ac(Be),Mc=e=>(t,r,o)=>Zo(e)(t,r,o),yz=Mc(Be),jc=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Do(e)(t,r,n)},vz=jc(Be),Lc=e=>async(t,r,o)=>Do(e)(t,r,o),zz=Lc(Be),Uc=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Fo(e)(t,r,n)},wz=Uc(Be),Zc=e=>(t,r,o)=>Fo(e)(t,r,o),Rz=Zc(Be),Dc=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ho(e)(t,r,n)},xz=Dc(Be),Fc=e=>async(t,r,o)=>Ho(e)(t,r,o),Pz=Fc(Be);var tt={};Jt(tt,{base64:()=>Fd,base64url:()=>Hc,bigint:()=>Gd,boolean:()=>Xd,browserEmail:()=>Nz,cidrv4:()=>Zd,cidrv6:()=>Dd,cuid:()=>Ed,cuid2:()=>kd,date:()=>Jd,datetime:()=>Wd,domain:()=>Mz,duration:()=>Nd,e164:()=>Vd,email:()=>Ad,emoji:()=>Md,extendedDuration:()=>Tz,guid:()=>qd,hex:()=>jz,hostname:()=>Az,html5Email:()=>Cz,httpProtocol:()=>Hd,idnEmail:()=>Oz,integer:()=>Yd,ipv4:()=>jd,ipv6:()=>Ld,ksuid:()=>Id,lowercase:()=>tp,mac:()=>Ud,md5_base64:()=>Uz,md5_base64url:()=>Zz,md5_hex:()=>Lz,nanoid:()=>Od,null:()=>Qd,number:()=>Vc,rfc5322Email:()=>Iz,sha1_base64:()=>Fz,sha1_base64url:()=>Hz,sha1_hex:()=>Dz,sha256_base64:()=>Jz,sha256_base64url:()=>Bz,sha256_hex:()=>Vz,sha384_base64:()=>Kz,sha384_base64url:()=>Gz,sha384_hex:()=>Wz,sha512_base64:()=>Xz,sha512_base64url:()=>Qz,sha512_hex:()=>Yz,string:()=>Kd,time:()=>Bd,ulid:()=>$d,undefined:()=>ep,unicodeEmail:()=>TS,uppercase:()=>rp,uuid:()=>Gr,uuid4:()=>Ez,uuid6:()=>kz,uuid7:()=>$z,xid:()=>Cd});var Ed=/^[cC][0-9a-z]{6,}$/,kd=/^[0-9a-z]+$/,$d=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Cd=/^[0-9a-vA-V]{20}$/,Id=/^[A-Za-z0-9]{27}$/,Od=/^[a-zA-Z0-9_-]{21}$/,Nd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Tz=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qd=/^([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})$/,Gr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ez=Gr(4),kz=Gr(6),$z=Gr(7),Ad=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Iz=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,TS=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Oz=TS,Nz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,qz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Md(){return new RegExp(qz,"u")}var jd=/^(?:(?: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])$/,Ld=/^(([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}|:))$/,Ud=e=>{let t=lt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Zd=/^((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])$/,Dd=/^(([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])$/,Fd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hc=/^[A-Za-z0-9_-]*$/,Az=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Mz=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Hd=/^https?$/,Vd=/^\+[1-9]\d{6,14}$/,ES="(?:(?:\\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])))",Jd=new RegExp(`^${ES}$`);function kS(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Bd(e){return new RegExp(`^${kS(e)}$`)}function Wd(e){let t=kS({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${ES}T(?:${o})$`)}var Kd=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Gd=/^-?\d+n?$/,Yd=/^-?\d+$/,Vc=/^-?\d+(?:\.\d+)?$/,Xd=/^(?:true|false)$/i,Qd=/^null$/i;var ep=/^undefined$/i;var tp=/^[^A-Z]*$/,rp=/^[^a-z]*$/,jz=/^[0-9a-fA-F]*$/;function Hs(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Vs(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Lz=/^[0-9a-fA-F]{32}$/,Uz=Hs(22,"=="),Zz=Vs(22),Dz=/^[0-9a-fA-F]{40}$/,Fz=Hs(27,"="),Hz=Vs(27),Vz=/^[0-9a-fA-F]{64}$/,Jz=Hs(43,"="),Bz=Vs(43),Wz=/^[0-9a-fA-F]{96}$/,Kz=Hs(64,""),Gz=Vs(64),Yz=/^[0-9a-fA-F]{128}$/,Xz=Hs(86,"=="),Qz=Vs(86);var le=S("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),CS={number:"number",bigint:"bigint",object:"date"},Jc=S("$ZodCheckLessThan",(e,t)=>{le.init(e,t);let r=CS[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bc=S("$ZodCheckGreaterThan",(e,t)=>{le.init(e,t);let r=CS[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),op=S("$ZodCheckMultipleOf",(e,t)=>{le.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):md(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),np=S("$ZodCheckNumberFormat",(e,t)=>{le.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=yd[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=n,a.maximum=s,r&&(a.pattern=Yd)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});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:e,origin:o,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}a<n&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),sp=S("$ZodCheckBigIntFormat",(e,t)=>{le.init(e,t);let[r,o]=vd[t.format];e._zod.onattach.push(n=>{let s=n._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o}),e._zod.check=n=>{let s=n.value;s<r&&n.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>o&&n.issues.push({origin:"bigint",input:s,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),ip=S("$ZodCheckMaxSize",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:Ls(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ap=S("$ZodCheckMinSize",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:Ls(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),cp=S("$ZodCheckSizeEquals",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=o=>{let n=o.value,s=n.size;if(s===t.size)return;let i=s>t.size;o.issues.push({origin:Ls(n),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),lp=S("$ZodCheckMaxLength",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let i=Us(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),up=S("$ZodCheckMinLength",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let i=Us(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),dp=S("$ZodCheckLengthEquals",(e,t)=>{var r;le.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!fr(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,s=n.length;if(s===t.length)return;let i=Us(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Vo=S("$ZodCheckStringFormat",(e,t)=>{var r,o;le.init(e,t),e._zod.onattach.push(n=>{let s=n._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),pp=S("$ZodCheckRegex",(e,t)=>{Vo.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tp),Vo.init(e,t)}),mp=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=rp),Vo.init(e,t)}),fp=S("$ZodCheckIncludes",(e,t)=>{le.init(e,t);let r=lt(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),gp=S("$ZodCheckStartsWith",(e,t)=>{le.init(e,t);let r=new RegExp(`^${lt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Sp=S("$ZodCheckEndsWith",(e,t)=>{le.init(e,t);let r=new RegExp(`.*${lt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function $S(e,t,r){e.issues.length&&t.issues.push(...Je(r,e.issues))}var _p=S("$ZodCheckProperty",(e,t)=>{le.init(e,t),e._zod.check=r=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>$S(n,r,t.property));$S(o,r,t.property)}}),bp=S("$ZodCheckMimeType",(e,t)=>{le.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(o=>{o._zod.bag.mime=t.mime}),e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),yp=S("$ZodCheckOverwrite",(e,t)=>{le.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Js=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
3
3
  `).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 t=Function,r=this?.args,n=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,n.join(`
4
- `))}};var gp={major:4,minor:4,patch:3};var X=S("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=gp;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,l)=>{let u=br(i),d;for(let m of a){if(m._zod.def.when){if(Sd(i)||!m._zod.def.when(i))continue}else if(u)continue;let h=i.issues.length,g=m._zod.check(i);if(g instanceof Promise&&l?.async===!1)throw new St;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await g,i.issues.length!==h&&(u||(u=br(i,h)))});else{if(i.issues.length===h)continue;u||(u=br(i,h))}}return d?d.then(()=>i):i},s=(i,a,l)=>{if(br(i))return i.aborted=!0,i;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new St;return u.then(d=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new St;return l.then(u=>n(u,o,a))}return n(l,o,a)}}re(e,"~standard",()=>({validate:n=>{try{let s=vd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return zd(e,n).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Xr=S("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Hd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.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:e}),r}}),ce=S("$ZodStringFormat",(e,t)=>{Bo.init(e,t),Xr.init(e,t)}),_p=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=$d),ce.init(e,t)}),bp=S("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Yr(o))}else t.pattern??(t.pattern=Yr());ce.init(e,t)}),yp=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Cd),ce.init(e,t)}),vp=S("$ZodURL",(e,t)=>{ce.init(e,t),e._zod.check=r=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Ld.source&&!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let n=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),zp=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Id()),ce.init(e,t)}),Rp=S("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ed),ce.init(e,t)}),wp=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rd),ce.init(e,t)}),xp=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=wd),ce.init(e,t)}),Pp=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=xd),ce.init(e,t)}),Tp=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Pd),ce.init(e,t)}),Ep=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Td),ce.init(e,t)}),kp=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Fd(t)),ce.init(e,t)}),$p=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Zd),ce.init(e,t)}),Cp=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Dd(t)),ce.init(e,t)}),Ip=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=kd),ce.init(e,t)}),Op=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Od),ce.init(e,t),e._zod.bag.format="ipv4"}),Np=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Nd),ce.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ap=S("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Ad(t.delimiter)),ce.init(e,t),e._zod.bag.format="mac"}),qp=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=qd),ce.init(e,t)}),Mp=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Md),ce.init(e,t),e._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:e,continue:!t.abort})}}});function jp(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Lp=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=jd),ce.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{jp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function qS(e){if(!Uc.test(e))return!1;let t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return jp(r)}var Up=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Uc),ce.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{qS(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Zp=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ud),ce.init(e,t)});function MS(e,t=null){try{let r=e.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||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}var Dp=S("$ZodJWT",(e,t)=>{ce.init(e,t),e._zod.check=r=>{MS(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Fp=S("$ZodCustomStringFormat",(e,t)=>{ce.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Wc=S("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=e._zod.bag.pattern??Zc,e._zod.parse=(r,o)=>{if(t.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:e,...s?{received:s}:{}}),r}}),Hp=S("$ZodNumberFormat",(e,t)=>{Qd.init(e,t),Wc.init(e,t)}),Vs=S("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=Bd,e._zod.parse=(r,o)=>{if(t.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:e}),r}}),Kc=S("$ZodBigInt",(e,t)=>{X.init(e,t),e._zod.pattern=Vd,e._zod.parse=(r,o)=>{if(t.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:e}),r}}),Vp=S("$ZodBigIntFormat",(e,t)=>{ep.init(e,t),Kc.init(e,t)}),Jp=S("$ZodSymbol",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),Bp=S("$ZodUndefined",(e,t)=>{X.init(e,t),e._zod.pattern=Kd,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),Wp=S("$ZodNull",(e,t)=>{X.init(e,t),e._zod.pattern=Wd,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),Kp=S("$ZodAny",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),Gp=S("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=r=>r}),Yp=S("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),Xp=S("$ZodVoid",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),Qp=S("$ZodDate",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{if(t.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:e}),r}});function zS(e,t,r){e.issues.length&&t.issues.push(...Ke(r,e.issues)),t.value[r]=e.value}var em=S("$ZodArray",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],l=t.element._zod.run({value:a,issues:[]},o);l instanceof Promise?s.push(l.then(u=>zS(u,r,i))):zS(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Bc(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Ke(r,e.issues))}if(!i&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?i&&(t.value[r]=void 0):t.value[r]=e.value}function jS(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=hd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function LS(e,t,r,o,n,s){let i=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let h in t){if(h==="__proto__"||a.has(h))continue;if(u==="never"){i.push(h);continue}let g=l.run({value:t[h],issues:[]},o);g instanceof Promise?e.push(g.then(v=>Bc(v,r,h,t,d,m))):Bc(g,r,h,t,d,m)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var US=S("$ZodObject",(e,t)=>{if(X.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=Zo(()=>jS(t));re(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=Gr,s=t.catchall,i;e._zod.parse=(a,l)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=i.shape;for(let h of i.keys){let g=m[h],v=g._zod.optin==="optional",w=g._zod.optout==="optional",y=g._zod.run({value:u[h],issues:[]},l);y instanceof Promise?d.push(y.then(D=>Bc(D,a,h,u,v,w))):Bc(y,a,h,u,v,w)}return s?LS(d,u,a,l,o.value,e):d.length?Promise.all(d).then(()=>a):a}}),tm=S("$ZodObjectJIT",(e,t)=>{US.init(e,t);let r=e._zod.parse,o=Zo(()=>jS(t)),n=h=>{let g=new Hs(["shape","payload","ctx"]),v=o.value,w=N=>{let F=Tc(N);return`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`};g.write("const input = payload.value;");let y=Object.create(null),D=0;for(let N of v.keys)y[N]=`key_${D++}`;g.write("const newResult = {};");for(let N of v.keys){let F=y[N],x=Tc(N),z=h[N],Z=z?._zod?.optin==="optional",oe=z?._zod?.optout==="optional";g.write(`const ${F} = ${w(N)};`),Z&&oe?g.write(`
5
- if (${F}.issues.length) {
4
+ `))}};var vp={major:4,minor:4,patch:3};var Y=S("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vp;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,c)=>{let u=_r(i),d;for(let h of a){if(h._zod.def.when){if(zd(i)||!h._zod.def.when(i))continue}else if(u)continue;let m=i.issues.length,g=h._zod.check(i);if(g instanceof Promise&&c?.async===!1)throw new ft;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await g,i.issues.length!==m&&(u||(u=_r(i,m)))});else{if(i.issues.length===m)continue;u||(u=_r(i,m))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(_r(i))return i.aborted=!0,i;let u=n(a,o,c);if(u instanceof Promise){if(c.async===!1)throw new ft;return u.then(d=>e._zod.parse(d,c))}return e._zod.parse(u,c)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=e._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new ft;return c.then(u=>n(u,o,a))}return n(c,o,a)}}re(e,"~standard",()=>({validate:n=>{try{let s=Pd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Td(e,n).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Yr=S("$ZodString",(e,t)=>{Y.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Kd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.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:e}),r}}),ae=S("$ZodStringFormat",(e,t)=>{Vo.init(e,t),Yr.init(e,t)}),wp=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=qd),ae.init(e,t)}),Rp=S("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gr(o))}else t.pattern??(t.pattern=Gr());ae.init(e,t)}),xp=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ad),ae.init(e,t)}),Pp=S("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=r=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Hd.source&&!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let n=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Tp=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Md()),ae.init(e,t)}),Ep=S("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Od),ae.init(e,t)}),kp=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ed),ae.init(e,t)}),$p=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=kd),ae.init(e,t)}),Cp=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=$d),ae.init(e,t)}),Ip=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Cd),ae.init(e,t)}),Op=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Id),ae.init(e,t)}),Np=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Wd(t)),ae.init(e,t)}),qp=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Jd),ae.init(e,t)}),Ap=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Bd(t)),ae.init(e,t)}),Mp=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Nd),ae.init(e,t)}),jp=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=jd),ae.init(e,t),e._zod.bag.format="ipv4"}),Lp=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ld),ae.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Up=S("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Ud(t.delimiter)),ae.init(e,t),e._zod.bag.format="mac"}),Zp=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Zd),ae.init(e,t)}),Dp=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Dd),ae.init(e,t),e._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:e,continue:!t.abort})}}});function Fp(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Hp=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Fd),ae.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Fp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function BS(e){if(!Hc.test(e))return!1;let t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Fp(r)}var Vp=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hc),ae.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{BS(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Jp=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vd),ae.init(e,t)});function WS(e,t=null){try{let r=e.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||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}var Bp=S("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=r=>{WS(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Wp=S("$ZodCustomStringFormat",(e,t)=>{ae.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Xc=S("$ZodNumber",(e,t)=>{Y.init(e,t),e._zod.pattern=e._zod.bag.pattern??Vc,e._zod.parse=(r,o)=>{if(t.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:e,...s?{received:s}:{}}),r}}),Kp=S("$ZodNumberFormat",(e,t)=>{np.init(e,t),Xc.init(e,t)}),Bs=S("$ZodBoolean",(e,t)=>{Y.init(e,t),e._zod.pattern=Xd,e._zod.parse=(r,o)=>{if(t.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:e}),r}}),Qc=S("$ZodBigInt",(e,t)=>{Y.init(e,t),e._zod.pattern=Gd,e._zod.parse=(r,o)=>{if(t.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:e}),r}}),Gp=S("$ZodBigIntFormat",(e,t)=>{sp.init(e,t),Qc.init(e,t)}),Yp=S("$ZodSymbol",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),Xp=S("$ZodUndefined",(e,t)=>{Y.init(e,t),e._zod.pattern=ep,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),Qp=S("$ZodNull",(e,t)=>{Y.init(e,t),e._zod.pattern=Qd,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),eh=S("$ZodAny",(e,t)=>{Y.init(e,t),e._zod.parse=r=>r}),th=S("$ZodUnknown",(e,t)=>{Y.init(e,t),e._zod.parse=r=>r}),rh=S("$ZodNever",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),oh=S("$ZodVoid",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),nh=S("$ZodDate",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{if(t.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:e}),r}});function OS(e,t,r){e.issues.length&&t.issues.push(...Je(r,e.issues)),t.value[r]=e.value}var sh=S("$ZodArray",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=t.element._zod.run({value:a,issues:[]},o);c instanceof Promise?s.push(c.then(u=>OS(u,r,i))):OS(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Yc(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Je(r,e.issues))}if(!i&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?i&&(t.value[r]=void 0):t.value[r]=e.value}function KS(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=bd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function GS(e,t,r,o,n,s){let i=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,d=c.optin==="optional",h=c.optout==="optional";for(let m in t){if(m==="__proto__"||a.has(m))continue;if(u==="never"){i.push(m);continue}let g=c.run({value:t[m],issues:[]},o);g instanceof Promise?e.push(g.then(y=>Yc(y,r,m,t,d,h))):Yc(g,r,m,t,d,h)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var YS=S("$ZodObject",(e,t)=>{if(Y.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let o=Lo(()=>KS(t));re(e._zod,"propValues",()=>{let a=t.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let h of d.values)c[u].add(h)}}return c});let n=Kr,s=t.catchall,i;e._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:e}),a;a.value={};let d=[],h=i.shape;for(let m of i.keys){let g=h[m],y=g._zod.optin==="optional",v=g._zod.optout==="optional",z=g._zod.run({value:u[m],issues:[]},c);z instanceof Promise?d.push(z.then(U=>Yc(U,a,m,u,y,v))):Yc(z,a,m,u,y,v)}return s?GS(d,u,a,c,o.value,e):d.length?Promise.all(d).then(()=>a):a}}),ih=S("$ZodObjectJIT",(e,t)=>{YS.init(e,t);let r=e._zod.parse,o=Lo(()=>KS(t)),n=m=>{let g=new Js(["shape","payload","ctx"]),y=o.value,v=T=>{let D=Cc(T);return`shape[${D}]._zod.run({ value: input[${D}], issues: [] }, ctx)`};g.write("const input = payload.value;");let z=Object.create(null),U=0;for(let T of y.keys)z[T]=`key_${U++}`;g.write("const newResult = {};");for(let T of y.keys){let D=z[T],x=Cc(T),w=m[T],F=w?._zod?.optin==="optional",oe=w?._zod?.optout==="optional";g.write(`const ${D} = ${v(T)};`),F&&oe?g.write(`
5
+ if (${D}.issues.length) {
6
6
  if (${x} in input) {
7
- payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
7
+ payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
8
8
  ...iss,
9
9
  path: iss.path ? [${x}, ...iss.path] : [${x}]
10
10
  })));
11
11
  }
12
12
  }
13
13
 
14
- if (${F}.value === undefined) {
14
+ if (${D}.value === undefined) {
15
15
  if (${x} in input) {
16
16
  newResult[${x}] = undefined;
17
17
  }
18
18
  } else {
19
- newResult[${x}] = ${F}.value;
19
+ newResult[${x}] = ${D}.value;
20
20
  }
21
21
 
22
- `):Z?g.write(`
23
- if (${F}.issues.length) {
24
- payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
22
+ `):F?g.write(`
23
+ if (${D}.issues.length) {
24
+ payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
25
25
  ...iss,
26
26
  path: iss.path ? [${x}, ...iss.path] : [${x}]
27
27
  })));
28
28
  }
29
29
 
30
- if (${F}.value === undefined) {
30
+ if (${D}.value === undefined) {
31
31
  if (${x} in input) {
32
32
  newResult[${x}] = undefined;
33
33
  }
34
34
  } else {
35
- newResult[${x}] = ${F}.value;
35
+ newResult[${x}] = ${D}.value;
36
36
  }
37
37
 
38
38
  `):g.write(`
39
- const ${F}_present = ${x} in input;
40
- if (${F}.issues.length) {
41
- payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
39
+ const ${D}_present = ${x} in input;
40
+ if (${D}.issues.length) {
41
+ payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
42
42
  ...iss,
43
43
  path: iss.path ? [${x}, ...iss.path] : [${x}]
44
44
  })));
45
45
  }
46
- if (!${F}_present && !${F}.issues.length) {
46
+ if (!${D}_present && !${D}.issues.length) {
47
47
  payload.issues.push({
48
48
  code: "invalid_type",
49
49
  expected: "nonoptional",
@@ -52,29 +52,29 @@ var yv=Object.defineProperty;var Bt=(e,t)=>{for(var r in t)yv(e,r,{get:t[r],enum
52
52
  });
53
53
  }
54
54
 
55
- if (${F}_present) {
56
- if (${F}.value === undefined) {
55
+ if (${D}_present) {
56
+ if (${D}.value === undefined) {
57
57
  newResult[${x}] = undefined;
58
58
  } else {
59
- newResult[${x}] = ${F}.value;
59
+ newResult[${x}] = ${D}.value;
60
60
  }
61
61
  }
62
62
 
63
- `)}g.write("payload.value = newResult;"),g.write("return payload;");let W=g.compile();return(N,F)=>W(h,N,F)},s,i=Gr,a=!Kr.jitless,u=a&&dd.value,d=t.catchall,m;e._zod.parse=(h,g)=>{m??(m=o.value);let v=h.value;return i(v)?a&&u&&g?.async===!1&&g.jitless!==!0?(s||(s=n(t.shape)),h=s(h,g),d?LS([],v,h,g,m,e):h):r(h,g):(h.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),h)}});function RS(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter(s=>!br(s));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Ze(i,o,Se())))}),t)}var Js=S("$ZodUnion",(e,t)=>{X.init(e,t),re(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),re(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),re(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),re(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${o.map(n=>As(n.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}return s?Promise.all(i).then(a=>RS(a,o,e,n)):RS(i,o,e,n)}});function wS(e,t,r,o){let n=e.filter(s=>s.issues.length===0);return n.length===1?(t.value=n[0].value,t):(n.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Ze(i,o,Se())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}var rm=S("$ZodXor",(e,t)=>{Js.init(e,t),t.inclusive=!1;let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);l instanceof Promise?(i.push(l),s=!0):i.push(l)}return s?Promise.all(i).then(a=>wS(a,o,e,n)):wS(i,o,e,n)}}),om=S("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Js.init(e,t);let r=e._zod.parse;re(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,l]of Object.entries(i)){n[a]||(n[a]=new Set);for(let u of l)n[a].add(u)}}return n});let o=Zo(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let l of a){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(n,s)=>{let i=n.value;if(!Gr(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);return a?a._zod.run(n,s):t.unionFallback||s.direction==="backward"?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n)}}),nm=S("$ZodIntersection",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,u])=>xS(r,l,u)):xS(r,s,i)}});function Sp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(_r(e)&&_r(t)){let r=Object.keys(t),o=Object.keys(e).filter(s=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=Sp(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=Sp(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 xS(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys)o.has(l)||o.set(l,{}),o.get(l).l=!0}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys)o.has(l)||o.set(l,{}),o.get(l).r=!0;else e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n&&e.issues.push({...n,keys:s}),br(e))return e;let i=Sp(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var Gc=S("$ZodTuple",(e,t)=>{X.init(e,t);let r=t.items;e._zod.parse=(o,n)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];let i=[],a=PS(r,"optin"),l=PS(r,"optout");if(!t.rest){if(s.length<a)return o.issues.push({code:"too_small",minimum:a,inclusive:!0,input:s,inst:e,origin:"array"}),o;s.length>r.length&&o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:s,inst:e,origin:"array"})}let u=new Array(r.length);for(let d=0;d<r.length;d++){let m=r[d]._zod.run({value:s[d],issues:[]},n);m instanceof Promise?i.push(m.then(h=>{u[d]=h})):u[d]=m}if(t.rest){let d=r.length-1,m=s.slice(r.length);for(let h of m){d++;let g=t.rest._zod.run({value:h,issues:[]},n);g instanceof Promise?i.push(g.then(v=>TS(v,o,d))):TS(g,o,d)}}return i.length?Promise.all(i).then(()=>ES(u,o,r,s,l)):ES(u,o,r,s,l)}});function PS(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function TS(e,t,r){e.issues.length&&t.issues.push(...Ke(r,e.issues)),t.value[r]=e.value}function ES(e,t,r,o,n){for(let s=0;s<r.length;s++){let i=e[s],a=s<o.length;if(i.issues.length){if(!a&&s>=n){t.value.length=s;break}t.issues.push(...Ke(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=o.length&&(r[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}var sm=S("$ZodRecord",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!_r(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.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 d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>Ze(g,o,Se())),input:u,path:[u],inst:e});continue}let m=d.value,h=t.valueType._zod.run({value:n[u],issues:[]},o);h instanceof Promise?s.push(h.then(g=>{g.issues.length&&r.issues.push(...Ke(u,g.issues)),r.value[m]=g.value})):(h.issues.length&&r.issues.push(...Ke(u,h.issues)),r.value[m]=h.value)}let l;for(let u in n)a.has(u)||(l=l??[],l.push(u));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Zc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");m.issues.length===0&&(l=m)}if(l.issues.length){t.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>Ze(m,o,Se())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);d instanceof Promise?s.push(d.then(m=>{m.issues.length&&r.issues.push(...Ke(a,m.issues)),r.value[l.value]=m.value})):(d.issues.length&&r.issues.push(...Ke(a,d.issues)),r.value[l.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}}),im=S("$ZodMap",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;let s=[];r.value=new Map;for(let[i,a]of n){let l=t.keyType._zod.run({value:i,issues:[]},o),u=t.valueType._zod.run({value:a,issues:[]},o);l instanceof Promise||u instanceof Promise?s.push(Promise.all([l,u]).then(([d,m])=>{kS(d,m,r,i,n,e,o)})):kS(l,u,r,i,n,e,o)}return s.length?Promise.all(s).then(()=>r):r}});function kS(e,t,r,o,n,s,i){e.issues.length&&(qs.has(typeof o)?r.issues.push(...Ke(o,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:s,issues:e.issues.map(a=>Ze(a,i,Se()))})),t.issues.length&&(qs.has(typeof o)?r.issues.push(...Ke(o,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:s,key:o,issues:t.issues.map(a=>Ze(a,i,Se()))})),r.value.set(e.value,t.value)}var am=S("$ZodSet",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let i of n){let a=t.valueType._zod.run({value:i,issues:[]},o);a instanceof Promise?s.push(a.then(l=>$S(l,r))):$S(a,r)}return s.length?Promise.all(s).then(()=>r):r}});function $S(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var cm=S("$ZodEnum",(e,t)=>{X.init(e,t);let r=Ns(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>qs.has(typeof n)).map(n=>typeof n=="string"?pt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;return o.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),lm=S("$ZodLiteral",(e,t)=>{if(X.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(o=>typeof o=="string"?pt(o):o?pt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}}),um=S("$ZodFile",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return n instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),r}}),dm=S("$ZodTransform",(e,t)=>{X.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new fr(e.constructor.name);let n=t.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 St;return r.value=n,r.fallback=!0,r}});function CS(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Yc=S("$ZodOptional",(e,t)=>{X.init(e,t),e._zod.optin="optional",e._zod.optout="optional",re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),re(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${As(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);return s instanceof Promise?s.then(i=>CS(i,n)):CS(s,n)}return r.value===void 0?r:t.innerType._zod.run(r,o)}}),pm=S("$ZodExactOptional",(e,t)=>{Yc.init(e,t),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),mm=S("$ZodNullable",(e,t)=>{X.init(e,t),re(e._zod,"optin",()=>t.innerType._zod.optin),re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${As(r.source)}|null)$`):void 0}),re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),hm=S("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>IS(s,t)):IS(n,t)}});function IS(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var fm=S("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(o.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),gm=S("$ZodNonOptional",(e,t)=>{X.init(e,t),re(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>OS(s,e)):OS(n,e)}});function OS(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Sm=S("$ZodSuccess",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new fr("ZodSuccess");let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.issues.length===0,r)):(r.value=n.issues.length===0,r)}}),_m=S("$ZodCatch",(e,t)=>{X.init(e,t),e._zod.optin="optional",re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>Ze(i,o,Se()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(s=>Ze(s,o,Se()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),bm=S("$ZodNaN",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),Xc=S("$ZodPipe",(e,t)=>{X.init(e,t),re(e._zod,"values",()=>t.in._zod.values),re(e._zod,"optin",()=>t.in._zod.optin),re(e._zod,"optout",()=>t.out._zod.optout),re(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Hc(i,t.in,o)):Hc(s,t.in,o)}let n=t.in._zod.run(r,o);return n instanceof Promise?n.then(s=>Hc(s,t.out,o)):Hc(n,t.out,o)}});function Hc(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var Bs=S("$ZodCodec",(e,t)=>{X.init(e,t),re(e._zod,"values",()=>t.in._zod.values),re(e._zod,"optin",()=>t.in._zod.optin),re(e._zod,"optout",()=>t.out._zod.optout),re(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if((o.direction||"forward")==="forward"){let s=t.in._zod.run(r,o);return s instanceof Promise?s.then(i=>Vc(i,t,o)):Vc(s,t,o)}else{let s=t.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Vc(i,t,o)):Vc(s,t,o)}}});function Vc(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let n=t.transform(e.value,e);return n instanceof Promise?n.then(s=>Jc(e,s,t.out,r)):Jc(e,n,t.out,r)}else{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(s=>Jc(e,s,t.in,r)):Jc(e,n,t.in,r)}}function Jc(e,t,r,o){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},o)}var ym=S("$ZodPreprocess",(e,t)=>{Xc.init(e,t)}),vm=S("$ZodReadonly",(e,t)=>{X.init(e,t),re(e._zod,"propValues",()=>t.innerType._zod.propValues),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"optin",()=>t.innerType?._zod?.optin),re(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(NS):NS(n)}});function NS(e){return e.value=Object.freeze(e.value),e}var zm=S("$ZodTemplateLiteral",(e,t)=>{X.init(e,t);let r=[];for(let o of t.parts)if(typeof o=="object"&&o!==null){if(!o._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);let n=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!n)throw new Error(`Invalid template literal part: ${o._zod.traits}`);let s=n.startsWith("^")?1:0,i=n.endsWith("$")?n.length-1:n.length;r.push(n.slice(s,i))}else if(o===null||md.has(typeof o))r.push(pt(`${o}`));else throw new Error(`Invalid template literal part: ${o}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(o,n)=>typeof o.value!="string"?(o.issues.push({input:o.value,inst:e,expected:"string",code:"invalid_type"}),o):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(o.value)||o.issues.push({input:o.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),o)}),Rm=S("$ZodFunction",(e,t)=>(X.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...o){let n=e._def.input?$c(e._def.input,o):o,s=Reflect.apply(r,this,n);return e._def.output?$c(e._def.output,s):s}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...o){let n=e._def.input?await Cc(e._def.input,o):o,s=await Reflect.apply(r,this,n);return e._def.output?await Cc(e._def.output,s):s}},e._zod.parse=(r,o)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let o=e.constructor;return Array.isArray(r[0])?new o({type:"function",input:new Gc({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new o({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let o=e.constructor;return new o({type:"function",input:e._def.input,output:r})},e)),wm=S("$ZodPromise",(e,t)=>{X.init(e,t),e._zod.parse=(r,o)=>Promise.resolve(r.value).then(n=>t.innerType._zod.run({value:n,issues:[]},o))}),xm=S("$ZodLazy",(e,t)=>{X.init(e,t),re(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),re(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),re(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),re(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),re(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),Pm=S("$ZodCustom",(e,t)=>{ue.init(e,t),X.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(s=>AS(s,r,o,e));AS(n,r,o,e)}});function AS(e,t,r,o){if(!e){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),t.issues.push(Do(n))}}var Ws={};Bt(Ws,{en:()=>Qc});var jz=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[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=_d(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return n.values.length===1?`Invalid input: expected ${kc(n.values[0])}`:`Invalid option: expected one of ${Pc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(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=t(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":""}: ${Pc(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 Qc(){return{localeError:jz()}}var ZS,Tm=Symbol("ZodOutput"),Em=Symbol("ZodInput"),el=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let o=r[0];return this._map.set(t,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let o={...this.get(r)??{}};delete o.id;let n={...o,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function tl(){return new el}(ZS=globalThis).__zod_globalRegistry??(ZS.__zod_globalRegistry=tl());var xe=globalThis.__zod_globalRegistry;function km(e,t){return new e({type:"string",...P(t)})}function $m(e,t){return new e({type:"string",coerce:!0,...P(t)})}function rl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Ks(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function ol(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function nl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function sl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function il(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Gs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function al(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function cl(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function ll(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function ul(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function dl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function pl(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function ml(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function hl(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function fl(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Cm(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...P(t)})}function gl(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function Sl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function _l(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function bl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function yl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function vl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}var Im={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Om(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Nm(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function Am(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function qm(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Mm(e,t){return new e({type:"number",checks:[],...P(t)})}function jm(e,t){return new e({type:"number",coerce:!0,checks:[],...P(t)})}function Lm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Um(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...P(t)})}function Zm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...P(t)})}function Dm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...P(t)})}function Fm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...P(t)})}function Hm(e,t){return new e({type:"boolean",...P(t)})}function Vm(e,t){return new e({type:"boolean",coerce:!0,...P(t)})}function Jm(e,t){return new e({type:"bigint",...P(t)})}function Bm(e,t){return new e({type:"bigint",coerce:!0,...P(t)})}function Wm(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...P(t)})}function Km(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...P(t)})}function Gm(e,t){return new e({type:"symbol",...P(t)})}function Ym(e,t){return new e({type:"undefined",...P(t)})}function Xm(e,t){return new e({type:"null",...P(t)})}function Qm(e){return new e({type:"any"})}function eh(e){return new e({type:"unknown"})}function th(e,t){return new e({type:"never",...P(t)})}function rh(e,t){return new e({type:"void",...P(t)})}function oh(e,t){return new e({type:"date",...P(t)})}function nh(e,t){return new e({type:"date",coerce:!0,...P(t)})}function sh(e,t){return new e({type:"nan",...P(t)})}function Ot(e,t){return new Dc({check:"less_than",...P(t),value:e,inclusive:!1})}function st(e,t){return new Dc({check:"less_than",...P(t),value:e,inclusive:!0})}function Nt(e,t){return new Fc({check:"greater_than",...P(t),value:e,inclusive:!1})}function De(e,t){return new Fc({check:"greater_than",...P(t),value:e,inclusive:!0})}function zl(e){return Nt(0,e)}function Rl(e){return Ot(0,e)}function wl(e){return st(0,e)}function xl(e){return De(0,e)}function yr(e,t){return new Xd({check:"multiple_of",...P(t),value:e})}function vr(e,t){return new tp({check:"max_size",...P(t),maximum:e})}function At(e,t){return new rp({check:"min_size",...P(t),minimum:e})}function Qr(e,t){return new op({check:"size_equals",...P(t),size:e})}function eo(e,t){return new np({check:"max_length",...P(t),maximum:e})}function Kt(e,t){return new sp({check:"min_length",...P(t),minimum:e})}function to(e,t){return new ip({check:"length_equals",...P(t),length:e})}function Wo(e,t){return new ap({check:"string_format",format:"regex",...P(t),pattern:e})}function Ko(e){return new cp({check:"string_format",format:"lowercase",...P(e)})}function Go(e){return new lp({check:"string_format",format:"uppercase",...P(e)})}function Yo(e,t){return new up({check:"string_format",format:"includes",...P(t),includes:e})}function Xo(e,t){return new dp({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Qo(e,t){return new pp({check:"string_format",format:"ends_with",...P(t),suffix:e})}function Pl(e,t,r){return new mp({check:"property",property:e,schema:t,...P(r)})}function en(e,t){return new hp({check:"mime_type",mime:e,...P(t)})}function _t(e){return new fp({check:"overwrite",tx:e})}function tn(e){return _t(t=>t.normalize(e))}function rn(){return _t(e=>e.trim())}function on(){return _t(e=>e.toLowerCase())}function nn(){return _t(e=>e.toUpperCase())}function sn(){return _t(e=>ud(e))}function ih(e,t,r){return new e({type:"array",element:t,...P(r)})}function Uz(e,t,r){return new e({type:"union",options:t,...P(r)})}function Zz(e,t,r){return new e({type:"union",options:t,inclusive:!1,...P(r)})}function Dz(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...P(o)})}function Fz(e,t,r){return new e({type:"intersection",left:t,right:r})}function Hz(e,t,r,o){let n=r instanceof X,s=n?o:r,i=n?r:null;return new e({type:"tuple",items:t,rest:i,...P(s)})}function Vz(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...P(o)})}function Jz(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...P(o)})}function Bz(e,t,r){return new e({type:"set",valueType:t,...P(r)})}function Wz(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...P(r)})}function Kz(e,t,r){return new e({type:"enum",entries:t,...P(r)})}function Gz(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...P(r)})}function ah(e,t){return new e({type:"file",...P(t)})}function Yz(e,t){return new e({type:"transform",transform:t})}function Xz(e,t){return new e({type:"optional",innerType:t})}function Qz(e,t){return new e({type:"nullable",innerType:t})}function eR(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():pd(r)}})}function tR(e,t,r){return new e({type:"nonoptional",innerType:t,...P(r)})}function rR(e,t){return new e({type:"success",innerType:t})}function oR(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function nR(e,t,r){return new e({type:"pipe",in:t,out:r})}function sR(e,t){return new e({type:"readonly",innerType:t})}function iR(e,t,r){return new e({type:"template_literal",parts:t,...P(r)})}function aR(e,t){return new e({type:"lazy",getter:t})}function cR(e,t){return new e({type:"promise",innerType:t})}function ch(e,t,r){let o=P(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function lh(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function uh(e,t){let r=DS(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Do(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(Do(s))}},e(o.value,o)),t);return r}function DS(e,t){let r=new ue({check:"custom",...P(t)});return r._zod.check=e,r}function dh(e){let t=new ue({check:"describe"});return t._zod.onattach=[r=>{let o=xe.get(r)??{};xe.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function ph(e){let t=new ue({check:"meta"});return t._zod.onattach=[r=>{let o=xe.get(r)??{};xe.add(r,{...o,...e})}],t._zod.check=()=>{},t}function mh(e,t){let r=P(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(g=>typeof g=="string"?g.toLowerCase():g),n=n.map(g=>typeof g=="string"?g.toLowerCase():g));let s=new Set(o),i=new Set(n),a=e.Codec??Bs,l=e.Boolean??Vs,u=e.String??Xr,d=new u({type:"string",error:r.error}),m=new l({type:"boolean",error:r.error}),h=new a({type:"pipe",in:d,out:m,transform:((g,v)=>{let w=g;return r.case!=="sensitive"&&(w=w.toLowerCase()),s.has(w)?!0:i.has(w)?!1:(v.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:v.value,inst:h,continue:!1}),{})}),reverseTransform:((g,v)=>g===!0?o[0]||"true":n[0]||"false"),error:r.error});return h}function an(e,t,r,o={}){let n=P(o),s={...P(o),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(s.pattern=r),new e(s)}function zr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??xe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function se(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let h=i.schema,g=t.processors[n.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);g(e,t,h,d)}let m=e._zod.parent;m&&(i.ref||(i.ref=m),se(m,t,d),t.seen.get(m).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&Fe(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((o=i.schema).default??(o.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Rr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let l=o.get(a);if(l&&l!==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=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,h=e.external.uri??(v=>v);if(m)return{ref:h(m)};let g=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=g,{defId:g,ref:`${h("__shared")}#/${a}/${g}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:l,defId:u}=n(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
+ `)}g.write("payload.value = newResult;"),g.write("return payload;");let H=g.compile();return(T,D)=>H(m,T,D)},s,i=Kr,a=!Wr.jitless,u=a&&gd.value,d=t.catchall,h;e._zod.parse=(m,g)=>{h??(h=o.value);let y=m.value;return i(y)?a&&u&&g?.async===!1&&g.jitless!==!0?(s||(s=n(t.shape)),m=s(m,g),d?GS([],y,m,g,h,e):m):r(m,g):(m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m)}});function NS(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter(s=>!_r(s));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Ue(i,o,ge())))}),t)}var Ws=S("$ZodUnion",(e,t)=>{Y.init(e,t),re(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),re(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),re(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),re(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${o.map(n=>Ms(n.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.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=>NS(a,o,e,n)):NS(i,o,e,n)}});function qS(e,t,r,o){let n=e.filter(s=>s.issues.length===0);return n.length===1?(t.value=n[0].value,t):(n.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Ue(i,o,ge())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}var ah=S("$ZodXor",(e,t)=>{Ws.init(e,t),t.inclusive=!1;let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:o.value,issues:[]},n);c instanceof Promise?(i.push(c),s=!0):i.push(c)}return s?Promise.all(i).then(a=>qS(a,o,e,n)):qS(i,o,e,n)}}),ch=S("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ws.init(e,t);let r=e._zod.parse;re(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.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=Lo(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.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});e._zod.parse=(n,s)=>{let i=n.value;if(!Kr(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);return a?a._zod.run(n,s):t.unionFallback||s.direction==="backward"?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n)}}),lh=S("$ZodIntersection",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>AS(r,c,u)):AS(r,s,i)}});function zp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Sr(e)&&Sr(t)){let r=Object.keys(t),o=Object.keys(e).filter(s=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=zp(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=zp(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 AS(e,t,r){let o=new Map,n;for(let a of t.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 e.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 e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n&&e.issues.push({...n,keys:s}),_r(e))return e;let i=zp(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var el=S("$ZodTuple",(e,t)=>{Y.init(e,t);let r=t.items;e._zod.parse=(o,n)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];let i=[],a=MS(r,"optin"),c=MS(r,"optout");if(!t.rest){if(s.length<a)return o.issues.push({code:"too_small",minimum:a,inclusive:!0,input:s,inst:e,origin:"array"}),o;s.length>r.length&&o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:s,inst:e,origin:"array"})}let u=new Array(r.length);for(let d=0;d<r.length;d++){let h=r[d]._zod.run({value:s[d],issues:[]},n);h instanceof Promise?i.push(h.then(m=>{u[d]=m})):u[d]=h}if(t.rest){let d=r.length-1,h=s.slice(r.length);for(let m of h){d++;let g=t.rest._zod.run({value:m,issues:[]},n);g instanceof Promise?i.push(g.then(y=>jS(y,o,d))):jS(g,o,d)}}return i.length?Promise.all(i).then(()=>LS(u,o,r,s,c)):LS(u,o,r,s,c)}});function MS(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function jS(e,t,r){e.issues.length&&t.issues.push(...Je(r,e.issues)),t.value[r]=e.value}function LS(e,t,r,o,n){for(let s=0;s<r.length;s++){let i=e[s],a=s<o.length;if(i.issues.length){if(!a&&s>=n){t.value.length=s;break}t.issues.push(...Je(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=o.length&&(r[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}var uh=S("$ZodRecord",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Sr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.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 d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>Ue(g,o,ge())),input:u,path:[u],inst:e});continue}let h=d.value,m=t.valueType._zod.run({value:n[u],issues:[]},o);m instanceof Promise?s.push(m.then(g=>{g.issues.length&&r.issues.push(...Je(u,g.issues)),r.value[h]=g.value})):(m.issues.length&&r.issues.push(...Je(u,m.issues)),r.value[h]=m.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:e,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Vc.test(a)&&c.issues.length){let h=t.keyType._zod.run({value:Number(a),issues:[]},o);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(c=h)}if(c.issues.length){t.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(h=>Ue(h,o,ge())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);d instanceof Promise?s.push(d.then(h=>{h.issues.length&&r.issues.push(...Je(a,h.issues)),r.value[c.value]=h.value})):(d.issues.length&&r.issues.push(...Je(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}}),dh=S("$ZodMap",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;let s=[];r.value=new Map;for(let[i,a]of n){let c=t.keyType._zod.run({value:i,issues:[]},o),u=t.valueType._zod.run({value:a,issues:[]},o);c instanceof Promise||u instanceof Promise?s.push(Promise.all([c,u]).then(([d,h])=>{US(d,h,r,i,n,e,o)})):US(c,u,r,i,n,e,o)}return s.length?Promise.all(s).then(()=>r):r}});function US(e,t,r,o,n,s,i){e.issues.length&&(js.has(typeof o)?r.issues.push(...Je(o,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:s,issues:e.issues.map(a=>Ue(a,i,ge()))})),t.issues.length&&(js.has(typeof o)?r.issues.push(...Je(o,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:s,key:o,issues:t.issues.map(a=>Ue(a,i,ge()))})),r.value.set(e.value,t.value)}var ph=S("$ZodSet",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let i of n){let a=t.valueType._zod.run({value:i,issues:[]},o);a instanceof Promise?s.push(a.then(c=>ZS(c,r))):ZS(a,r)}return s.length?Promise.all(s).then(()=>r):r}});function ZS(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var hh=S("$ZodEnum",(e,t)=>{Y.init(e,t);let r=As(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>js.has(typeof n)).map(n=>typeof n=="string"?lt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;return o.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),mh=S("$ZodLiteral",(e,t)=>{if(Y.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(o=>typeof o=="string"?lt(o):o?lt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}}),fh=S("$ZodFile",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return n instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),r}}),gh=S("$ZodTransform",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new mr(e.constructor.name);let n=t.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 ft;return r.value=n,r.fallback=!0,r}});function DS(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var tl=S("$ZodOptional",(e,t)=>{Y.init(e,t),e._zod.optin="optional",e._zod.optout="optional",re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),re(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ms(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);return s instanceof Promise?s.then(i=>DS(i,n)):DS(s,n)}return r.value===void 0?r:t.innerType._zod.run(r,o)}}),Sh=S("$ZodExactOptional",(e,t)=>{tl.init(e,t),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),_h=S("$ZodNullable",(e,t)=>{Y.init(e,t),re(e._zod,"optin",()=>t.innerType._zod.optin),re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ms(r.source)}|null)$`):void 0}),re(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),bh=S("$ZodDefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>FS(s,t)):FS(n,t)}});function FS(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var yh=S("$ZodPrefault",(e,t)=>{Y.init(e,t),e._zod.optin="optional",re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(o.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),vh=S("$ZodNonOptional",(e,t)=>{Y.init(e,t),re(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>HS(s,e)):HS(n,e)}});function HS(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var zh=S("$ZodSuccess",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new mr("ZodSuccess");let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.issues.length===0,r)):(r.value=n.issues.length===0,r)}}),wh=S("$ZodCatch",(e,t)=>{Y.init(e,t),e._zod.optin="optional",re(e._zod,"optout",()=>t.innerType._zod.optout),re(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>Ue(i,o,ge()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(s=>Ue(s,o,ge()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),Rh=S("$ZodNaN",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),rl=S("$ZodPipe",(e,t)=>{Y.init(e,t),re(e._zod,"values",()=>t.in._zod.values),re(e._zod,"optin",()=>t.in._zod.optin),re(e._zod,"optout",()=>t.out._zod.optout),re(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Wc(i,t.in,o)):Wc(s,t.in,o)}let n=t.in._zod.run(r,o);return n instanceof Promise?n.then(s=>Wc(s,t.out,o)):Wc(n,t.out,o)}});function Wc(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var Ks=S("$ZodCodec",(e,t)=>{Y.init(e,t),re(e._zod,"values",()=>t.in._zod.values),re(e._zod,"optin",()=>t.in._zod.optin),re(e._zod,"optout",()=>t.out._zod.optout),re(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if((o.direction||"forward")==="forward"){let s=t.in._zod.run(r,o);return s instanceof Promise?s.then(i=>Kc(i,t,o)):Kc(s,t,o)}else{let s=t.out._zod.run(r,o);return s instanceof Promise?s.then(i=>Kc(i,t,o)):Kc(s,t,o)}}});function Kc(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let n=t.transform(e.value,e);return n instanceof Promise?n.then(s=>Gc(e,s,t.out,r)):Gc(e,n,t.out,r)}else{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(s=>Gc(e,s,t.in,r)):Gc(e,n,t.in,r)}}function Gc(e,t,r,o){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},o)}var xh=S("$ZodPreprocess",(e,t)=>{rl.init(e,t)}),Ph=S("$ZodReadonly",(e,t)=>{Y.init(e,t),re(e._zod,"propValues",()=>t.innerType._zod.propValues),re(e._zod,"values",()=>t.innerType._zod.values),re(e._zod,"optin",()=>t.innerType?._zod?.optin),re(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(VS):VS(n)}});function VS(e){return e.value=Object.freeze(e.value),e}var Th=S("$ZodTemplateLiteral",(e,t)=>{Y.init(e,t);let r=[];for(let o of t.parts)if(typeof o=="object"&&o!==null){if(!o._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);let n=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!n)throw new Error(`Invalid template literal part: ${o._zod.traits}`);let s=n.startsWith("^")?1:0,i=n.endsWith("$")?n.length-1:n.length;r.push(n.slice(s,i))}else if(o===null||_d.has(typeof o))r.push(lt(`${o}`));else throw new Error(`Invalid template literal part: ${o}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(o,n)=>typeof o.value!="string"?(o.issues.push({input:o.value,inst:e,expected:"string",code:"invalid_type"}),o):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(o.value)||o.issues.push({input:o.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),o)}),Eh=S("$ZodFunction",(e,t)=>(Y.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...o){let n=e._def.input?Nc(e._def.input,o):o,s=Reflect.apply(r,this,n);return e._def.output?Nc(e._def.output,s):s}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...o){let n=e._def.input?await qc(e._def.input,o):o,s=await Reflect.apply(r,this,n);return e._def.output?await qc(e._def.output,s):s}},e._zod.parse=(r,o)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let o=e.constructor;return Array.isArray(r[0])?new o({type:"function",input:new el({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new o({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let o=e.constructor;return new o({type:"function",input:e._def.input,output:r})},e)),kh=S("$ZodPromise",(e,t)=>{Y.init(e,t),e._zod.parse=(r,o)=>Promise.resolve(r.value).then(n=>t.innerType._zod.run({value:n,issues:[]},o))}),$h=S("$ZodLazy",(e,t)=>{Y.init(e,t),re(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),re(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),re(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),re(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),re(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),Ch=S("$ZodCustom",(e,t)=>{le.init(e,t),Y.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(s=>JS(s,r,o,e));JS(n,r,o,e)}});function JS(e,t,r,o){if(!e){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),t.issues.push(Uo(n))}}var Gs={};Jt(Gs,{en:()=>ol});var tw=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[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=wd(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return n.values.length===1?`Invalid input: expected ${Oc(n.values[0])}`:`Invalid option: expected one of ${$c(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(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=t(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":""}: ${$c(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 ol(){return{localeError:tw()}}var XS,Ih=Symbol("ZodOutput"),Oh=Symbol("ZodInput"),nl=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let o=r[0];return this._map.set(t,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let o={...this.get(r)??{}};delete o.id;let n={...o,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function sl(){return new nl}(XS=globalThis).__zod_globalRegistry??(XS.__zod_globalRegistry=sl());var Pe=globalThis.__zod_globalRegistry;function Nh(e,t){return new e({type:"string",...P(t)})}function qh(e,t){return new e({type:"string",coerce:!0,...P(t)})}function il(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Ys(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function al(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function cl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function ll(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function ul(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function Xs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function dl(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function pl(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function hl(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function ml(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function fl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function gl(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function Sl(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function _l(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function bl(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function Ah(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...P(t)})}function yl(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function vl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function zl(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function wl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function Rl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function xl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}var Mh={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function jh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function Lh(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function Uh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function Zh(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Dh(e,t){return new e({type:"number",checks:[],...P(t)})}function Fh(e,t){return new e({type:"number",coerce:!0,checks:[],...P(t)})}function Hh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Vh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...P(t)})}function Jh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...P(t)})}function Bh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...P(t)})}function Wh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...P(t)})}function Kh(e,t){return new e({type:"boolean",...P(t)})}function Gh(e,t){return new e({type:"boolean",coerce:!0,...P(t)})}function Yh(e,t){return new e({type:"bigint",...P(t)})}function Xh(e,t){return new e({type:"bigint",coerce:!0,...P(t)})}function Qh(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...P(t)})}function em(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...P(t)})}function tm(e,t){return new e({type:"symbol",...P(t)})}function rm(e,t){return new e({type:"undefined",...P(t)})}function om(e,t){return new e({type:"null",...P(t)})}function nm(e){return new e({type:"any"})}function sm(e){return new e({type:"unknown"})}function im(e,t){return new e({type:"never",...P(t)})}function am(e,t){return new e({type:"void",...P(t)})}function cm(e,t){return new e({type:"date",...P(t)})}function lm(e,t){return new e({type:"date",coerce:!0,...P(t)})}function um(e,t){return new e({type:"nan",...P(t)})}function Ct(e,t){return new Jc({check:"less_than",...P(t),value:e,inclusive:!1})}function rt(e,t){return new Jc({check:"less_than",...P(t),value:e,inclusive:!0})}function It(e,t){return new Bc({check:"greater_than",...P(t),value:e,inclusive:!1})}function Ze(e,t){return new Bc({check:"greater_than",...P(t),value:e,inclusive:!0})}function Pl(e){return It(0,e)}function Tl(e){return Ct(0,e)}function El(e){return rt(0,e)}function kl(e){return Ze(0,e)}function br(e,t){return new op({check:"multiple_of",...P(t),value:e})}function yr(e,t){return new ip({check:"max_size",...P(t),maximum:e})}function Ot(e,t){return new ap({check:"min_size",...P(t),minimum:e})}function Xr(e,t){return new cp({check:"size_equals",...P(t),size:e})}function Qr(e,t){return new lp({check:"max_length",...P(t),maximum:e})}function Wt(e,t){return new up({check:"min_length",...P(t),minimum:e})}function eo(e,t){return new dp({check:"length_equals",...P(t),length:e})}function Jo(e,t){return new pp({check:"string_format",format:"regex",...P(t),pattern:e})}function Bo(e){return new hp({check:"string_format",format:"lowercase",...P(e)})}function Wo(e){return new mp({check:"string_format",format:"uppercase",...P(e)})}function Ko(e,t){return new fp({check:"string_format",format:"includes",...P(t),includes:e})}function Go(e,t){return new gp({check:"string_format",format:"starts_with",...P(t),prefix:e})}function Yo(e,t){return new Sp({check:"string_format",format:"ends_with",...P(t),suffix:e})}function $l(e,t,r){return new _p({check:"property",property:e,schema:t,...P(r)})}function Xo(e,t){return new bp({check:"mime_type",mime:e,...P(t)})}function gt(e){return new yp({check:"overwrite",tx:e})}function Qo(e){return gt(t=>t.normalize(e))}function en(){return gt(e=>e.trim())}function tn(){return gt(e=>e.toLowerCase())}function rn(){return gt(e=>e.toUpperCase())}function on(){return gt(e=>fd(e))}function dm(e,t,r){return new e({type:"array",element:t,...P(r)})}function ow(e,t,r){return new e({type:"union",options:t,...P(r)})}function nw(e,t,r){return new e({type:"union",options:t,inclusive:!1,...P(r)})}function sw(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...P(o)})}function iw(e,t,r){return new e({type:"intersection",left:t,right:r})}function aw(e,t,r,o){let n=r instanceof Y,s=n?o:r,i=n?r:null;return new e({type:"tuple",items:t,rest:i,...P(s)})}function cw(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...P(o)})}function lw(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...P(o)})}function uw(e,t,r){return new e({type:"set",valueType:t,...P(r)})}function dw(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...P(r)})}function pw(e,t,r){return new e({type:"enum",entries:t,...P(r)})}function hw(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...P(r)})}function pm(e,t){return new e({type:"file",...P(t)})}function mw(e,t){return new e({type:"transform",transform:t})}function fw(e,t){return new e({type:"optional",innerType:t})}function gw(e,t){return new e({type:"nullable",innerType:t})}function Sw(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Sd(r)}})}function _w(e,t,r){return new e({type:"nonoptional",innerType:t,...P(r)})}function bw(e,t){return new e({type:"success",innerType:t})}function yw(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function vw(e,t,r){return new e({type:"pipe",in:t,out:r})}function zw(e,t){return new e({type:"readonly",innerType:t})}function ww(e,t,r){return new e({type:"template_literal",parts:t,...P(r)})}function Rw(e,t){return new e({type:"lazy",getter:t})}function xw(e,t){return new e({type:"promise",innerType:t})}function hm(e,t,r){let o=P(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function mm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function fm(e,t){let r=QS(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Uo(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(Uo(s))}},e(o.value,o)),t);return r}function QS(e,t){let r=new le({check:"custom",...P(t)});return r._zod.check=e,r}function gm(e){let t=new le({check:"describe"});return t._zod.onattach=[r=>{let o=Pe.get(r)??{};Pe.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function Sm(e){let t=new le({check:"meta"});return t._zod.onattach=[r=>{let o=Pe.get(r)??{};Pe.add(r,{...o,...e})}],t._zod.check=()=>{},t}function _m(e,t){let r=P(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(g=>typeof g=="string"?g.toLowerCase():g),n=n.map(g=>typeof g=="string"?g.toLowerCase():g));let s=new Set(o),i=new Set(n),a=e.Codec??Ks,c=e.Boolean??Bs,u=e.String??Yr,d=new u({type:"string",error:r.error}),h=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:d,out:h,transform:((g,y)=>{let v=g;return r.case!=="sensitive"&&(v=v.toLowerCase()),s.has(v)?!0:i.has(v)?!1:(y.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:y.value,inst:m,continue:!1}),{})}),reverseTransform:((g,y)=>g===!0?o[0]||"true":n[0]||"false"),error:r.error});return m}function nn(e,t,r,o={}){let n=P(o),s={...P(o),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(s.pattern=r),new e(s)}function vr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Pe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ne(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let m=i.schema,g=t.processors[n.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);g(e,t,m,d)}let h=e._zod.parent;h&&(i.ref||(i.ref=h),ne(h,t,d),t.seen.get(h).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&De(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((o=i.schema).default??(o.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function zr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.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=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let h=e.external.registry.get(i[0])?.id,m=e.external.uri??(y=>y);if(h)return{ref:m(h)};let g=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=g,{defId:g,ref:`${m("__shared")}#/${a}/${g}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},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 d=a.schema;for(let h in d)delete d[h];d.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
64
64
 
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function wr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let g=e.seen.get(m),v=g.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(v)):Object.assign(u,v),Object.assign(u,d),a._zod.parent===m)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(v.$ref&&g.def)for(let y in u)y==="$ref"||y==="allOf"||y in g.def&&JSON.stringify(u[y])===JSON.stringify(g.def[y])&&delete u[y]}let h=a._zod.parent;if(h&&h!==m){o(h);let g=e.seen.get(h);if(g?.schema.$ref&&(u.$ref=g.schema.$ref,g.def))for(let v in u)v==="$ref"||v==="allOf"||v in g.def&&JSON.stringify(u[v])===JSON.stringify(g.def[v])&&delete u[v]}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&n.id===s&&delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,i[l.defId]=l.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:cn(t,"input",e.processors),output:cn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fe(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Fe(o.element,r);if(o.type==="set")return Fe(o.valueType,r);if(o.type==="lazy")return Fe(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 Fe(o.innerType,r);if(o.type==="intersection")return Fe(o.left,r)||Fe(o.right,r);if(o.type==="record"||o.type==="map")return Fe(o.keyType,r)||Fe(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Fe(o.in,r)||Fe(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Fe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Fe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Fe(n,r))return!0;return!!(o.rest&&Fe(o.rest,r))}return!1}var hh=(e,t={})=>r=>{let o=zr({...r,processors:t});return se(e,o),Rr(o,e),wr(o,e)},cn=(e,t,r={})=>o=>{let{libraryOptions:n,target:s}=o??{},i=zr({...n??{},target:s,io:t,processors:r});return se(e,i),Rr(i,e),wr(i,e)};var lR={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},fh=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(n.minLength=s),typeof i=="number"&&(n.maxLength=i),a&&(n.format=lR[a]??a,n.format===""&&delete n.format,a==="time"&&delete n.format),u&&(n.contentEncoding=u),l&&l.size>0){let d=[...l];d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},gh=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof a=="string"&&a.includes("int")?n.type="integer":n.type="number";let m=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";m?g?(n.minimum=d,n.exclusiveMinimum=!0):n.exclusiveMinimum=d:typeof s=="number"&&(n.minimum=s),h?g?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof i=="number"&&(n.maximum=i),typeof l=="number"&&(n.multipleOf=l)},Sh=(e,t,r,o)=>{r.type="boolean"},_h=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},bh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},yh=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},vh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},zh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Rh=(e,t,r,o)=>{r.not={}},wh=(e,t,r,o)=>{},xh=(e,t,r,o)=>{},Ph=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Th=(e,t,r,o)=>{let n=e._zod.def,s=Ns(n.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Eh=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.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,t.target==="draft-04"||t.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},kh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},$h=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},Ch=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;i!==void 0&&(s.minLength=i),a!==void 0&&(s.maxLength=a),l?l.length===1?(s.contentMediaType=l[0],Object.assign(n,s)):(Object.assign(n,s),n.anyOf=l.map(u=>({contentMediaType:u}))):Object.assign(n,s)},Ih=(e,t,r,o)=>{r.type="boolean"},Oh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Nh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Ah=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},qh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Mh=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},jh=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(n.minItems=i),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=se(s.element,t,{...o,path:[...o.path,"items"]})},Lh=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=se(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),l=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));l.size>0&&(n.required=Array.from(l)),s.catchall?._zod.def.type==="never"?n.additionalProperties=!1:s.catchall?s.catchall&&(n.additionalProperties=se(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},El=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,l)=>se(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));s?r.oneOf=i:r.anyOf=i},Uh=(e,t,r,o)=>{let n=e._zod.def,s=se(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=se(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},Zh=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((h,g)=>se(h,t,{...o,path:[...o.path,i,g]})),u=s.rest?se(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(n.prefixItems=l,u&&(n.items=u)):t.target==="openapi-3.0"?(n.items={anyOf:l},u&&n.items.anyOf.push(u),n.minItems=l.length,u||(n.maxItems=l.length)):(n.items=l,u&&(n.additionalItems=u));let{minimum:d,maximum:m}=e._zod.bag;typeof d=="number"&&(n.minItems=d),typeof m=="number"&&(n.maxItems=m)},Dh=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=se(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(n.propertyNames=se(s.keyType,t,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=se(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(n.required=d)}},Fh=(e,t,r,o)=>{let n=e._zod.def,s=se(n.innerType,t,o),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Hh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Vh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Jh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},Bh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);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},Wh=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;se(i,t,o);let a=t.seen.get(e);a.ref=i},Kh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},Gh=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},kl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Yh=(e,t,r,o)=>{let n=e._zod.innerType;se(n,t,o);let s=t.seen.get(e);s.ref=n},Tl={string:fh,number:gh,boolean:Sh,bigint:_h,symbol:bh,null:yh,undefined:vh,void:zh,never:Rh,any:wh,unknown:xh,date:Ph,enum:Th,literal:Eh,nan:kh,template_literal:$h,file:Ch,success:Ih,custom:Oh,function:Nh,transform:Ah,map:qh,set:Mh,array:jh,object:Lh,union:El,intersection:Uh,tuple:Zh,record:Dh,nullable:Fh,nonoptional:Hh,default:Vh,prefault:Jh,catch:Bh,pipe:Wh,readonly:Kh,promise:Gh,optional:kl,lazy:Yh};function ro(e,t){if("_idmap"in e){let o=e,n=zr({...t,processors:Tl}),s={};for(let l of o._idmap.entries()){let[u,d]=l;se(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Rr(n,d),i[u]=wr(n,d)}if(Object.keys(s).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}let r=zr({...t,processors:Tl});return se(e,r),Rr(r,e),wr(r,e)}var $l=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=zr({processors:Tl,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return se(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),Rr(this.ctx,t);let o=wr(this.ctx,t),{"~standard":n,...s}=o;return s}};var FS={};var Ys={};Bt(Ys,{ZodAny:()=>_f,ZodArray:()=>zf,ZodBase64:()=>Xl,ZodBase64URL:()=>Ql,ZodBigInt:()=>gn,ZodBigIntFormat:()=>ru,ZodBoolean:()=>fn,ZodCIDRv4:()=>Gl,ZodCIDRv6:()=>Yl,ZodCUID:()=>Fl,ZodCUID2:()=>Hl,ZodCatch:()=>Df,ZodCodec:()=>ai,ZodCustom:()=>ci,ZodCustomStringFormat:()=>mn,ZodDate:()=>oi,ZodDefault:()=>qf,ZodDiscriminatedUnion:()=>wf,ZodE164:()=>eu,ZodEmail:()=>Ll,ZodEmoji:()=>Zl,ZodEnum:()=>un,ZodExactOptional:()=>Of,ZodFile:()=>Cf,ZodFunction:()=>Yf,ZodGUID:()=>Qs,ZodIPv4:()=>Wl,ZodIPv6:()=>Kl,ZodIntersection:()=>xf,ZodJWT:()=>tu,ZodKSUID:()=>Bl,ZodLazy:()=>Kf,ZodLiteral:()=>$f,ZodMAC:()=>hf,ZodMap:()=>Ef,ZodNaN:()=>Hf,ZodNanoID:()=>Dl,ZodNever:()=>yf,ZodNonOptional:()=>au,ZodNull:()=>Sf,ZodNullable:()=>Af,ZodNumber:()=>hn,ZodNumberFormat:()=>oo,ZodObject:()=>ni,ZodOptional:()=>iu,ZodPipe:()=>ii,ZodPrefault:()=>jf,ZodPreprocess:()=>Vf,ZodPromise:()=>Gf,ZodReadonly:()=>Jf,ZodRecord:()=>ln,ZodSet:()=>kf,ZodString:()=>dn,ZodStringFormat:()=>le,ZodSuccess:()=>Zf,ZodSymbol:()=>ff,ZodTemplateLiteral:()=>Wf,ZodTransform:()=>If,ZodTuple:()=>Pf,ZodType:()=>ee,ZodULID:()=>Vl,ZodURL:()=>ri,ZodUUID:()=>qt,ZodUndefined:()=>gf,ZodUnion:()=>si,ZodUnknown:()=>bf,ZodVoid:()=>vf,ZodXID:()=>Jl,ZodXor:()=>Rf,_ZodString:()=>jl,_default:()=>Mf,_function:()=>V_,any:()=>ou,array:()=>_,base64:()=>u_,base64url:()=>d_,bigint:()=>z_,boolean:()=>k,catch:()=>Ff,check:()=>J_,cidrv4:()=>c_,cidrv6:()=>l_,codec:()=>Z_,cuid:()=>e_,cuid2:()=>t_,custom:()=>B_,date:()=>E_,describe:()=>W_,discriminatedUnion:()=>xr,e164:()=>p_,email:()=>Ul,emoji:()=>XS,enum:()=>K,exactOptional:()=>Nf,file:()=>M_,float32:()=>__,float64:()=>b_,function:()=>V_,guid:()=>JS,hash:()=>S_,hex:()=>g_,hostname:()=>f_,httpUrl:()=>YS,instanceof:()=>G_,int:()=>ql,int32:()=>y_,int64:()=>R_,intersection:()=>bt,invertCodec:()=>D_,ipv4:()=>s_,ipv6:()=>a_,json:()=>X_,jwt:()=>m_,keyof:()=>k_,ksuid:()=>n_,lazy:()=>Pr,literal:()=>b,looseObject:()=>U,looseRecord:()=>O_,mac:()=>i_,map:()=>N_,meta:()=>K_,nan:()=>U_,nanoid:()=>QS,nativeEnum:()=>q_,never:()=>nu,nonoptional:()=>Uf,null:()=>Mt,nullable:()=>ei,nullish:()=>j_,number:()=>R,object:()=>f,optional:()=>L,partialRecord:()=>I_,pipe:()=>Ml,prefault:()=>Lf,preprocess:()=>Yt,promise:()=>H_,readonly:()=>Bf,record:()=>T,refine:()=>Xf,set:()=>A_,strictObject:()=>$_,string:()=>c,stringFormat:()=>h_,stringbool:()=>Y_,success:()=>L_,superRefine:()=>Qf,symbol:()=>x_,templateLiteral:()=>F_,transform:()=>su,tuple:()=>Tf,uint32:()=>v_,uint64:()=>w_,ulid:()=>r_,undefined:()=>P_,union:()=>C,unknown:()=>j,url:()=>pn,uuid:()=>BS,uuidv4:()=>WS,uuidv6:()=>KS,uuidv7:()=>GS,void:()=>T_,xid:()=>o_,xor:()=>C_});var Cl={};Bt(Cl,{endsWith:()=>Qo,gt:()=>Nt,gte:()=>De,includes:()=>Yo,length:()=>to,lowercase:()=>Ko,lt:()=>Ot,lte:()=>st,maxLength:()=>eo,maxSize:()=>vr,mime:()=>en,minLength:()=>Kt,minSize:()=>At,multipleOf:()=>yr,negative:()=>Rl,nonnegative:()=>xl,nonpositive:()=>wl,normalize:()=>tn,overwrite:()=>_t,positive:()=>zl,property:()=>Pl,regex:()=>Wo,size:()=>Qr,slugify:()=>sn,startsWith:()=>Xo,toLowerCase:()=>on,toUpperCase:()=>nn,trim:()=>rn,uppercase:()=>Go});var it={};Bt(it,{ZodISODate:()=>Ol,ZodISODateTime:()=>Il,ZodISODuration:()=>Al,ZodISOTime:()=>Nl,date:()=>Qh,datetime:()=>Xh,duration:()=>tf,time:()=>ef});var Il=S("ZodISODateTime",(e,t)=>{kp.init(e,t),le.init(e,t)});function Xh(e){return Om(Il,e)}var Ol=S("ZodISODate",(e,t)=>{$p.init(e,t),le.init(e,t)});function Qh(e){return Nm(Ol,e)}var Nl=S("ZodISOTime",(e,t)=>{Cp.init(e,t),le.init(e,t)});function ef(e){return Am(Nl,e)}var Al=S("ZodISODuration",(e,t)=>{Ip.init(e,t),le.init(e,t)});function tf(e){return qm(Al,e)}var HS=(e,t)=>{Ls.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Zs(e,r)},flatten:{value:r=>Us(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Uo,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Uo,2)}},isEmpty:{get(){return e.issues.length===0}}})},dR=S("ZodError",HS),Ye=S("ZodError",HS,{Parent:Error});var rf=Fo(Ye),of=Ho(Ye),Xs=Vo(Ye),nf=Jo(Ye),sf=Ic(Ye),af=Oc(Ye),cf=Nc(Ye),lf=Ac(Ye),uf=qc(Ye),df=Mc(Ye),pf=jc(Ye),mf=Lc(Ye);var VS=new WeakMap;function ti(e,t,r){let o=Object.getPrototypeOf(e),n=VS.get(o);if(n||(n=new Set,VS.set(o,n)),!n.has(t)){n.add(t);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 ee=S("ZodType",(e,t)=>(X.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:cn(e,"input"),output:cn(e,"output")}}),e.toJSONSchema=hh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>rf(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Xs(e,r,o),e.parseAsync=async(r,o)=>of(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>nf(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>sf(e,r,o),e.decode=(r,o)=>af(e,r,o),e.encodeAsync=async(r,o)=>cf(e,r,o),e.decodeAsync=async(r,o)=>lf(e,r,o),e.safeEncode=(r,o)=>uf(e,r,o),e.safeDecode=(r,o)=>df(e,r,o),e.safeEncodeAsync=async(r,o)=>pf(e,r,o),e.safeDecodeAsync=async(r,o)=>mf(e,r,o),ti(e,"ZodType",{check(...r){let o=this.def;return this.clone(Y.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(Xf(r,o))},superRefine(r,o){return this.check(Qf(r,o))},overwrite(r){return this.check(_t(r))},optional(){return L(this)},exactOptional(){return Nf(this)},nullable(){return ei(this)},nullish(){return L(ei(this))},nonoptional(r){return Uf(this,r)},array(){return _(this)},or(r){return C([this,r])},and(r){return bt(this,r)},transform(r){return Ml(this,su(r))},default(r){return Mf(this,r)},prefault(r){return Lf(this,r)},catch(r){return Ff(this,r)},pipe(r){return Ml(this,r)},readonly(){return Bf(this)},describe(r){let o=this.clone();return xe.add(o,{description:r}),o},meta(...r){if(r.length===0)return xe.get(this);let o=this.clone();return xe.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(e,"description",{get(){return xe.get(e)?.description},configurable:!0}),e)),jl=S("_ZodString",(e,t)=>{Xr.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>fh(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,ti(e,"_ZodString",{regex(...o){return this.check(Wo(...o))},includes(...o){return this.check(Yo(...o))},startsWith(...o){return this.check(Xo(...o))},endsWith(...o){return this.check(Qo(...o))},min(...o){return this.check(Kt(...o))},max(...o){return this.check(eo(...o))},length(...o){return this.check(to(...o))},nonempty(...o){return this.check(Kt(1,...o))},lowercase(o){return this.check(Ko(o))},uppercase(o){return this.check(Go(o))},trim(){return this.check(rn())},normalize(...o){return this.check(tn(...o))},toLowerCase(){return this.check(on())},toUpperCase(){return this.check(nn())},slugify(){return this.check(sn())}})}),dn=S("ZodString",(e,t)=>{Xr.init(e,t),jl.init(e,t),e.email=r=>e.check(rl(Ll,r)),e.url=r=>e.check(Gs(ri,r)),e.jwt=r=>e.check(vl(tu,r)),e.emoji=r=>e.check(al(Zl,r)),e.guid=r=>e.check(Ks(Qs,r)),e.uuid=r=>e.check(ol(qt,r)),e.uuidv4=r=>e.check(nl(qt,r)),e.uuidv6=r=>e.check(sl(qt,r)),e.uuidv7=r=>e.check(il(qt,r)),e.nanoid=r=>e.check(cl(Dl,r)),e.guid=r=>e.check(Ks(Qs,r)),e.cuid=r=>e.check(ll(Fl,r)),e.cuid2=r=>e.check(ul(Hl,r)),e.ulid=r=>e.check(dl(Vl,r)),e.base64=r=>e.check(_l(Xl,r)),e.base64url=r=>e.check(bl(Ql,r)),e.xid=r=>e.check(pl(Jl,r)),e.ksuid=r=>e.check(ml(Bl,r)),e.ipv4=r=>e.check(hl(Wl,r)),e.ipv6=r=>e.check(fl(Kl,r)),e.cidrv4=r=>e.check(gl(Gl,r)),e.cidrv6=r=>e.check(Sl(Yl,r)),e.e164=r=>e.check(yl(eu,r)),e.datetime=r=>e.check(Xh(r)),e.date=r=>e.check(Qh(r)),e.time=r=>e.check(ef(r)),e.duration=r=>e.check(tf(r))});function c(e){return km(dn,e)}var le=S("ZodStringFormat",(e,t)=>{ce.init(e,t),jl.init(e,t)}),Ll=S("ZodEmail",(e,t)=>{yp.init(e,t),le.init(e,t)});function Ul(e){return rl(Ll,e)}var Qs=S("ZodGUID",(e,t)=>{_p.init(e,t),le.init(e,t)});function JS(e){return Ks(Qs,e)}var qt=S("ZodUUID",(e,t)=>{bp.init(e,t),le.init(e,t)});function BS(e){return ol(qt,e)}function WS(e){return nl(qt,e)}function KS(e){return sl(qt,e)}function GS(e){return il(qt,e)}var ri=S("ZodURL",(e,t)=>{vp.init(e,t),le.init(e,t)});function pn(e){return Gs(ri,e)}function YS(e){return Gs(ri,{protocol:nt.httpProtocol,hostname:nt.domain,...Y.normalizeParams(e)})}var Zl=S("ZodEmoji",(e,t)=>{zp.init(e,t),le.init(e,t)});function XS(e){return al(Zl,e)}var Dl=S("ZodNanoID",(e,t)=>{Rp.init(e,t),le.init(e,t)});function QS(e){return cl(Dl,e)}var Fl=S("ZodCUID",(e,t)=>{wp.init(e,t),le.init(e,t)});function e_(e){return ll(Fl,e)}var Hl=S("ZodCUID2",(e,t)=>{xp.init(e,t),le.init(e,t)});function t_(e){return ul(Hl,e)}var Vl=S("ZodULID",(e,t)=>{Pp.init(e,t),le.init(e,t)});function r_(e){return dl(Vl,e)}var Jl=S("ZodXID",(e,t)=>{Tp.init(e,t),le.init(e,t)});function o_(e){return pl(Jl,e)}var Bl=S("ZodKSUID",(e,t)=>{Ep.init(e,t),le.init(e,t)});function n_(e){return ml(Bl,e)}var Wl=S("ZodIPv4",(e,t)=>{Op.init(e,t),le.init(e,t)});function s_(e){return hl(Wl,e)}var hf=S("ZodMAC",(e,t)=>{Ap.init(e,t),le.init(e,t)});function i_(e){return Cm(hf,e)}var Kl=S("ZodIPv6",(e,t)=>{Np.init(e,t),le.init(e,t)});function a_(e){return fl(Kl,e)}var Gl=S("ZodCIDRv4",(e,t)=>{qp.init(e,t),le.init(e,t)});function c_(e){return gl(Gl,e)}var Yl=S("ZodCIDRv6",(e,t)=>{Mp.init(e,t),le.init(e,t)});function l_(e){return Sl(Yl,e)}var Xl=S("ZodBase64",(e,t)=>{Lp.init(e,t),le.init(e,t)});function u_(e){return _l(Xl,e)}var Ql=S("ZodBase64URL",(e,t)=>{Up.init(e,t),le.init(e,t)});function d_(e){return bl(Ql,e)}var eu=S("ZodE164",(e,t)=>{Zp.init(e,t),le.init(e,t)});function p_(e){return yl(eu,e)}var tu=S("ZodJWT",(e,t)=>{Dp.init(e,t),le.init(e,t)});function m_(e){return vl(tu,e)}var mn=S("ZodCustomStringFormat",(e,t)=>{Fp.init(e,t),le.init(e,t)});function h_(e,t,r={}){return an(mn,e,t,r)}function f_(e){return an(mn,"hostname",nt.hostname,e)}function g_(e){return an(mn,"hex",nt.hex,e)}function S_(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=nt[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return an(mn,o,n,t)}var hn=S("ZodNumber",(e,t)=>{Wc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>gh(e,o,n,s),ti(e,"ZodNumber",{gt(o,n){return this.check(Nt(o,n))},gte(o,n){return this.check(De(o,n))},min(o,n){return this.check(De(o,n))},lt(o,n){return this.check(Ot(o,n))},lte(o,n){return this.check(st(o,n))},max(o,n){return this.check(st(o,n))},int(o){return this.check(ql(o))},safe(o){return this.check(ql(o))},positive(o){return this.check(Nt(0,o))},nonnegative(o){return this.check(De(0,o))},negative(o){return this.check(Ot(0,o))},nonpositive(o){return this.check(st(0,o))},multipleOf(o,n){return this.check(yr(o,n))},step(o,n){return this.check(yr(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function R(e){return Mm(hn,e)}var oo=S("ZodNumberFormat",(e,t)=>{Hp.init(e,t),hn.init(e,t)});function ql(e){return Lm(oo,e)}function __(e){return Um(oo,e)}function b_(e){return Zm(oo,e)}function y_(e){return Dm(oo,e)}function v_(e){return Fm(oo,e)}var fn=S("ZodBoolean",(e,t)=>{Vs.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Sh(e,r,o,n)});function k(e){return Hm(fn,e)}var gn=S("ZodBigInt",(e,t)=>{Kc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>_h(e,o,n,s),e.gte=(o,n)=>e.check(De(o,n)),e.min=(o,n)=>e.check(De(o,n)),e.gt=(o,n)=>e.check(Nt(o,n)),e.gte=(o,n)=>e.check(De(o,n)),e.min=(o,n)=>e.check(De(o,n)),e.lt=(o,n)=>e.check(Ot(o,n)),e.lte=(o,n)=>e.check(st(o,n)),e.max=(o,n)=>e.check(st(o,n)),e.positive=o=>e.check(Nt(BigInt(0),o)),e.negative=o=>e.check(Ot(BigInt(0),o)),e.nonpositive=o=>e.check(st(BigInt(0),o)),e.nonnegative=o=>e.check(De(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(yr(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function z_(e){return Jm(gn,e)}var ru=S("ZodBigIntFormat",(e,t)=>{Vp.init(e,t),gn.init(e,t)});function R_(e){return Wm(ru,e)}function w_(e){return Km(ru,e)}var ff=S("ZodSymbol",(e,t)=>{Jp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bh(e,r,o,n)});function x_(e){return Gm(ff,e)}var gf=S("ZodUndefined",(e,t)=>{Bp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vh(e,r,o,n)});function P_(e){return Ym(gf,e)}var Sf=S("ZodNull",(e,t)=>{Wp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yh(e,r,o,n)});function Mt(e){return Xm(Sf,e)}var _f=S("ZodAny",(e,t)=>{Kp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wh(e,r,o,n)});function ou(){return Qm(_f)}var bf=S("ZodUnknown",(e,t)=>{Gp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xh(e,r,o,n)});function j(){return eh(bf)}var yf=S("ZodNever",(e,t)=>{Yp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rh(e,r,o,n)});function nu(e){return th(yf,e)}var vf=S("ZodVoid",(e,t)=>{Xp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zh(e,r,o,n)});function T_(e){return rh(vf,e)}var oi=S("ZodDate",(e,t)=>{Qp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Ph(e,o,n,s),e.min=(o,n)=>e.check(De(o,n)),e.max=(o,n)=>e.check(st(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function E_(e){return oh(oi,e)}var zf=S("ZodArray",(e,t)=>{em.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jh(e,r,o,n),e.element=t.element,ti(e,"ZodArray",{min(r,o){return this.check(Kt(r,o))},nonempty(r){return this.check(Kt(1,r))},max(r,o){return this.check(eo(r,o))},length(r,o){return this.check(to(r,o))},unwrap(){return this.element}})});function _(e,t){return ih(zf,e,t)}function k_(e){let t=e._zod.def.shape;return K(Object.keys(t))}var ni=S("ZodObject",(e,t)=>{tm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Lh(e,r,o,n),Y.defineLazy(e,"shape",()=>t.shape),ti(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:j()})},loose(){return this.clone({...this._zod.def,catchall:j()})},strict(){return this.clone({...this._zod.def,catchall:nu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Y.extend(this,r)},safeExtend(r){return Y.safeExtend(this,r)},merge(r){return Y.merge(this,r)},pick(r){return Y.pick(this,r)},omit(r){return Y.omit(this,r)},partial(...r){return Y.partial(iu,this,r[0])},required(...r){return Y.required(au,this,r[0])}})});function f(e,t){let r={type:"object",shape:e??{},...Y.normalizeParams(t)};return new ni(r)}function $_(e,t){return new ni({type:"object",shape:e,catchall:nu(),...Y.normalizeParams(t)})}function U(e,t){return new ni({type:"object",shape:e,catchall:j(),...Y.normalizeParams(t)})}var si=S("ZodUnion",(e,t)=>{Js.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.options=t.options});function C(e,t){return new si({type:"union",options:e,...Y.normalizeParams(t)})}var Rf=S("ZodXor",(e,t)=>{si.init(e,t),rm.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.options=t.options});function C_(e,t){return new Rf({type:"union",options:e,inclusive:!1,...Y.normalizeParams(t)})}var wf=S("ZodDiscriminatedUnion",(e,t)=>{si.init(e,t),om.init(e,t)});function xr(e,t,r){return new wf({type:"union",options:t,discriminator:e,...Y.normalizeParams(r)})}var xf=S("ZodIntersection",(e,t)=>{nm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Uh(e,r,o,n)});function bt(e,t){return new xf({type:"intersection",left:e,right:t})}var Pf=S("ZodTuple",(e,t)=>{Gc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zh(e,r,o,n),e.rest=r=>e.clone({...e._zod.def,rest:r})});function Tf(e,t,r){let o=t instanceof X,n=o?r:t,s=o?t:null;return new Pf({type:"tuple",items:e,rest:s,...Y.normalizeParams(n)})}var ln=S("ZodRecord",(e,t)=>{sm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dh(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,r){return!t||!t._zod?new ln({type:"record",keyType:c(),valueType:e,...Y.normalizeParams(t)}):new ln({type:"record",keyType:e,valueType:t,...Y.normalizeParams(r)})}function I_(e,t,r){let o=Ue(e);return o._zod.values=void 0,new ln({type:"record",keyType:o,valueType:t,...Y.normalizeParams(r)})}function O_(e,t,r){return new ln({type:"record",keyType:e,valueType:t,mode:"loose",...Y.normalizeParams(r)})}var Ef=S("ZodMap",(e,t)=>{im.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qh(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(At(...r)),e.nonempty=r=>e.check(At(1,r)),e.max=(...r)=>e.check(vr(...r)),e.size=(...r)=>e.check(Qr(...r))});function N_(e,t,r){return new Ef({type:"map",keyType:e,valueType:t,...Y.normalizeParams(r)})}var kf=S("ZodSet",(e,t)=>{am.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Mh(e,r,o,n),e.min=(...r)=>e.check(At(...r)),e.nonempty=r=>e.check(At(1,r)),e.max=(...r)=>e.check(vr(...r)),e.size=(...r)=>e.check(Qr(...r))});function A_(e,t){return new kf({type:"set",valueType:e,...Y.normalizeParams(t)})}var un=S("ZodEnum",(e,t)=>{cm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Th(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new un({...t,checks:[],...Y.normalizeParams(n),entries:s})},e.exclude=(o,n)=>{let s={...t.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 un({...t,checks:[],...Y.normalizeParams(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new un({type:"enum",entries:r,...Y.normalizeParams(t)})}function q_(e,t){return new un({type:"enum",entries:e,...Y.normalizeParams(t)})}var $f=S("ZodLiteral",(e,t)=>{lm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Eh(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function b(e,t){return new $f({type:"literal",values:Array.isArray(e)?e:[e],...Y.normalizeParams(t)})}var Cf=S("ZodFile",(e,t)=>{um.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ch(e,r,o,n),e.min=(r,o)=>e.check(At(r,o)),e.max=(r,o)=>e.check(vr(r,o)),e.mime=(r,o)=>e.check(en(Array.isArray(r)?r:[r],o))});function M_(e){return ah(Cf,e)}var If=S("ZodTransform",(e,t)=>{dm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ah(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new fr(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(Y.issue(i))}};let n=t.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 su(e){return new If({type:"transform",transform:e})}var iu=S("ZodOptional",(e,t)=>{Yc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function L(e){return new iu({type:"optional",innerType:e})}var Of=S("ZodExactOptional",(e,t)=>{pm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Nf(e){return new Of({type:"optional",innerType:e})}var Af=S("ZodNullable",(e,t)=>{mm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ei(e){return new Af({type:"nullable",innerType:e})}function j_(e){return L(ei(e))}var qf=S("ZodDefault",(e,t)=>{hm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mf(e,t){return new qf({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Y.shallowClone(t)}})}var jf=S("ZodPrefault",(e,t)=>{fm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lf(e,t){return new jf({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Y.shallowClone(t)}})}var au=S("ZodNonOptional",(e,t)=>{gm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Uf(e,t){return new au({type:"nonoptional",innerType:e,...Y.normalizeParams(t)})}var Zf=S("ZodSuccess",(e,t)=>{Sm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ih(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function L_(e){return new Zf({type:"success",innerType:e})}var Df=S("ZodCatch",(e,t)=>{_m.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ff(e,t){return new Df({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Hf=S("ZodNaN",(e,t)=>{bm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kh(e,r,o,n)});function U_(e){return sh(Hf,e)}var ii=S("ZodPipe",(e,t)=>{Xc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wh(e,r,o,n),e.in=t.in,e.out=t.out});function Ml(e,t){return new ii({type:"pipe",in:e,out:t})}var ai=S("ZodCodec",(e,t)=>{ii.init(e,t),Bs.init(e,t)});function Z_(e,t,r){return new ai({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function D_(e){let t=e._zod.def;return new ai({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Vf=S("ZodPreprocess",(e,t)=>{ii.init(e,t),ym.init(e,t)}),Jf=S("ZodReadonly",(e,t)=>{vm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Bf(e){return new Jf({type:"readonly",innerType:e})}var Wf=S("ZodTemplateLiteral",(e,t)=>{zm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$h(e,r,o,n)});function F_(e,t){return new Wf({type:"template_literal",parts:e,...Y.normalizeParams(t)})}var Kf=S("ZodLazy",(e,t)=>{xm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yh(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Pr(e){return new Kf({type:"lazy",getter:e})}var Gf=S("ZodPromise",(e,t)=>{wm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gh(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function H_(e){return new Gf({type:"promise",innerType:e})}var Yf=S("ZodFunction",(e,t)=>{Rm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nh(e,r,o,n)});function V_(e){return new Yf({type:"function",input:Array.isArray(e?.input)?Tf(e?.input):e?.input??_(j()),output:e?.output??j()})}var ci=S("ZodCustom",(e,t)=>{Pm.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Oh(e,r,o,n)});function J_(e){let t=new ue({check:"custom"});return t._zod.check=e,t}function B_(e,t){return ch(ci,e??(()=>!0),t)}function Xf(e,t={}){return lh(ci,e,t)}function Qf(e,t){return uh(e,t)}var W_=dh,K_=ph;function G_(e,t={}){let r=new ci({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...Y.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var Y_=(...e)=>mh({Codec:ai,Boolean:fn,String:dn},...e);function X_(e){let t=Pr(()=>C([c(e),R(),k(),Mt(),_(t),T(c(),t)]));return t}function Yt(e,t){return new Vf({type:"pipe",in:su(e),out:t})}var tg={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function mR(e){Se({customError:e})}function hR(){return Se().customError}var eg;eg||(eg={});var $={...Ys,...Cl,iso:it},fR=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function gR(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function SR(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1];if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Q_(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return $.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return $.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let s=SR(n,t),i=Ce(s,t);return t.refs.set(n,i),t.processing.delete(n),i}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return $.null();if(n.length===0)return $.never();if(n.length===1)return $.literal(n[0]);if(n.every(i=>typeof i=="string"))return $.enum(n);let s=n.map(i=>$.literal(i));return s.length<2?s[0]:$.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return $.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(s=>{let i={...e,type:s};return Q_(i,t)});return n.length===0?$.never():n.length===1?n[0]:$.union(n)}if(!r)return $.any();let o;switch(r){case"string":{let n=$.string();if(e.format){let s=e.format;s==="email"?n=n.check($.email()):s==="uri"||s==="uri-reference"?n=n.check($.url()):s==="uuid"||s==="guid"?n=n.check($.uuid()):s==="date-time"?n=n.check($.iso.datetime()):s==="date"?n=n.check($.iso.date()):s==="time"?n=n.check($.iso.time()):s==="duration"?n=n.check($.iso.duration()):s==="ipv4"?n=n.check($.ipv4()):s==="ipv6"?n=n.check($.ipv6()):s==="mac"?n=n.check($.mac()):s==="cidr"?n=n.check($.cidrv4()):s==="cidr-v6"?n=n.check($.cidrv6()):s==="base64"?n=n.check($.base64()):s==="base64url"?n=n.check($.base64url()):s==="e164"?n=n.check($.e164()):s==="jwt"?n=n.check($.jwt()):s==="emoji"?n=n.check($.emoji()):s==="nanoid"?n=n.check($.nanoid()):s==="cuid"?n=n.check($.cuid()):s==="cuid2"?n=n.check($.cuid2()):s==="ulid"?n=n.check($.ulid()):s==="xid"?n=n.check($.xid()):s==="ksuid"&&(n=n.check($.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?$.number().int():$.number();typeof e.minimum=="number"&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=$.boolean();break}case"null":{o=$.null();break}case"object":{let n={},s=e.properties||{},i=new Set(e.required||[]);for(let[l,u]of Object.entries(s)){let d=Ce(u,t);n[l]=i.has(l)?d:d.optional()}if(e.propertyNames){let l=Ce(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties=="object"?Ce(e.additionalProperties,t):$.any();if(Object.keys(n).length===0){o=$.record(l,u);break}let d=$.object(n).passthrough(),m=$.looseRecord(l,u);o=$.intersection(d,m);break}if(e.patternProperties){let l=e.patternProperties,u=Object.keys(l),d=[];for(let h of u){let g=Ce(l[h],t),v=$.string().regex(new RegExp(h));d.push($.looseRecord(v,g))}let m=[];if(Object.keys(n).length>0&&m.push($.object(n).passthrough()),m.push(...d),m.length===0)o=$.object({}).passthrough();else if(m.length===1)o=m[0];else{let h=$.intersection(m[0],m[1]);for(let g=2;g<m.length;g++)h=$.intersection(h,m[g]);o=h}break}let a=$.object(n);e.additionalProperties===!1?o=a.strict():typeof e.additionalProperties=="object"?o=a.catchall(Ce(e.additionalProperties,t)):o=a.passthrough();break}case"array":{let n=e.prefixItems,s=e.items;if(n&&Array.isArray(n)){let i=n.map(l=>Ce(l,t)),a=s&&typeof s=="object"&&!Array.isArray(s)?Ce(s,t):void 0;a?o=$.tuple(i).rest(a):o=$.tuple(i),typeof e.minItems=="number"&&(o=o.check($.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check($.maxLength(e.maxItems)))}else if(Array.isArray(s)){let i=s.map(l=>Ce(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Ce(e.additionalItems,t):void 0;a?o=$.tuple(i).rest(a):o=$.tuple(i),typeof e.minItems=="number"&&(o=o.check($.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check($.maxLength(e.maxItems)))}else if(s!==void 0){let i=Ce(s,t),a=$.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),o=a}else o=$.array($.any());break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Ce(e,t){if(typeof e=="boolean")return e?$.any():$.never();let r=Q_(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Ce(u,t)),l=$.union(a);r=o?$.intersection(r,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Ce(u,t)),l=$.xor(a);r=o?$.intersection(r,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:$.any();else{let a=o?r:Ce(e.allOf[0],t),l=o?0:1;for(let u=l;u<e.allOf.length;u++)a=$.intersection(a,Ce(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=$.nullable(r)),e.readOnly===!0&&(r=$.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of s)a in e&&(n[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(n[a]=e[a]);for(let a of Object.keys(e))fR.has(a)||(n[a]=e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function eb(e,t){if(typeof e=="boolean")return e?$.any():$.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=gR(r,t?.defaultTarget),n=r.$defs||r.definitions||{},s={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??xe};return Ce(r,s)}var li={};Bt(li,{bigint:()=>vR,boolean:()=>yR,date:()=>zR,number:()=>bR,string:()=>_R});function _R(e){return $m(dn,e)}function bR(e){return jm(hn,e)}function yR(e){return Vm(fn,e)}function vR(e){return Bm(gn,e)}function zR(e){return nh(oi,e)}Se(Qc());var Sn="2025-11-25";var cu=[Sn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lu="io.modelcontextprotocol/related-task",Qt="io.modelcontextprotocol/protocolVersion",_n="io.modelcontextprotocol/clientInfo",er="io.modelcontextprotocol/serverInfo",no="io.modelcontextprotocol/clientCapabilities",ui="io.modelcontextprotocol/subscriptionId",bn="io.modelcontextprotocol/logLevel";var so="2.0";var Xt=Pr(()=>C([c(),R(),k(),Mt(),T(c(),Xt),_(Xt)])),me=T(c(),Xt),uu=_(Xt),yn=C([c(),R().int()]),vn=c(),di=f({ttl:R().optional()}),pi=f({taskId:c()}),zn=U({progressToken:yn.optional(),[lu]:pi.optional()}),Re=f({_meta:zn.optional()}),Er=Re.extend({task:di.optional()}),he=f({method:c(),params:Re.loose().optional()}),Ie=f({_meta:zn.optional()}),Pe=f({method:c(),params:Ie.loose().optional()}),Rn=U({get[er](){return Lt.optional().catch(void 0)}}),fe=U({_meta:Rn.optional()}),yt=C([c(),R().int()]),wn=f({jsonrpc:b(so),id:yt,...he.shape}).strict(),xn=f({jsonrpc:b(so),...Pe.shape}).strict(),io=f({jsonrpc:b(so),id:yt,result:fe}).strict(),ao=f({jsonrpc:b(so),id:yt.optional(),error:f({code:R().int(),message:c(),data:j().optional()})}).strict(),vt=C([wn,xn,io,ao]),du=C([io,ao]),kr=fe.strict(),mi=Ie.extend({requestId:yt.optional(),reason:c().optional()}),Pn=Pe.extend({method:b("notifications/cancelled"),params:mi}),hi=f({src:c(),mimeType:c().optional(),sizes:_(c()).optional(),theme:K(["light","dark"]).optional()}),tr=f({icons:_(hi).optional()}),jt=f({name:c(),title:c().optional()}),Lt=jt.extend({...jt.shape,...tr.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),wR=bt(f({applyDefaults:k().optional()}),me),xR=Yt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,bt(f({form:wR.optional(),url:me.optional()}),me.optional())),pu=U({list:me.optional(),cancel:me.optional(),requests:U({sampling:U({createMessage:me.optional()}).optional(),elicitation:U({create:me.optional()}).optional()}).optional()}),mu=U({list:me.optional(),cancel:me.optional(),requests:U({tools:U({call:me.optional()}).optional()}).optional()}),fi=f({experimental:T(c(),me).optional(),sampling:f({context:me.optional(),tools:me.optional()}).optional(),elicitation:xR.optional(),roots:f({listChanged:k().optional()}).optional(),tasks:pu.optional(),extensions:T(c(),me).optional()}),gi=Re.extend({protocolVersion:c(),capabilities:fi,clientInfo:Lt}),Tn=he.extend({method:b("initialize"),params:gi}),En=f({experimental:T(c(),me).optional(),logging:me.optional(),completions:me.optional(),prompts:f({listChanged:k().optional()}).optional(),resources:f({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:f({listChanged:k().optional()}).optional(),tasks:mu.optional(),extensions:T(c(),me).optional()}),Si=fe.extend({protocolVersion:c(),capabilities:En,serverInfo:Lt,instructions:c().optional()}),kn=Pe.extend({method:b("notifications/initialized"),params:Ie.optional()}),_i=he.extend({method:b("server/discover"),params:Re.optional()}),$r=fe.extend({supportedVersions:_(c()),capabilities:En,instructions:c().optional()}),$n=he.extend({method:b("ping"),params:Re.optional()}),bi=f({progress:R(),total:L(R()),message:L(c())}),yi=f({...Ie.shape,...bi.shape,progressToken:yn}),Cn=Pe.extend({method:b("notifications/progress"),params:yi}),vi=Re.extend({cursor:vn.optional()}),rr=he.extend({params:vi.optional()}),or=fe.extend({nextCursor:vn.optional()}),In=f({uri:c(),mimeType:L(c()),_meta:T(c(),j()).optional()}),On=In.extend({text:c()}),og=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Nn=In.extend({blob:og}),nr=K(["user","assistant"]),Ut=f({audience:_(nr).optional(),priority:R().min(0).max(1).optional(),lastModified:it.datetime({offset:!0}).optional()}),An=f({...jt.shape,...tr.shape,uri:c(),description:L(c()),mimeType:L(c()),size:L(R()),annotations:Ut.optional(),_meta:L(U({}))}),zi=f({...jt.shape,...tr.shape,uriTemplate:c(),description:L(c()),mimeType:L(c()),annotations:Ut.optional(),_meta:L(U({}))}),Ri=rr.extend({method:b("resources/list")}),wi=or.extend({resources:_(An)}),xi=rr.extend({method:b("resources/templates/list")}),Pi=or.extend({resourceTemplates:_(zi)}),co=Re.extend({uri:c()}),Ti=co,Ei=he.extend({method:b("resources/read"),params:Ti}),ki=fe.extend({contents:_(C([On,Nn]))}),$i=Pe.extend({method:b("notifications/resources/list_changed"),params:Ie.optional()}),Ci=co,Ii=he.extend({method:b("resources/subscribe"),params:Ci}),Oi=co,Ni=he.extend({method:b("resources/unsubscribe"),params:Oi}),qn=f({toolsListChanged:k().optional(),promptsListChanged:k().optional(),resourcesListChanged:k().optional(),resourceSubscriptions:_(c()).optional()}),Ai=Re.extend({notifications:qn}),qi=he.extend({method:b("subscriptions/listen"),params:Ai}),Mi=Ie.extend({notifications:qn}),ji=Pe.extend({method:b("notifications/subscriptions/acknowledged"),params:Mi}),Li=Rn.extend({[ui]:yt}),Ui=fe.extend({_meta:Li}),Zi=Ie.extend({uri:c()}),Di=Pe.extend({method:b("notifications/resources/updated"),params:Zi}),Fi=f({name:c(),description:L(c()),required:L(k())}),Hi=f({...jt.shape,...tr.shape,description:L(c()),arguments:L(_(Fi)),_meta:L(U({}))}),Vi=rr.extend({method:b("prompts/list")}),Ji=or.extend({prompts:_(Hi)}),Bi=Re.extend({name:c(),arguments:T(c(),c()).optional()}),Wi=he.extend({method:b("prompts/get"),params:Bi}),lo=f({type:b("text"),text:c(),annotations:Ut.optional(),_meta:T(c(),j()).optional()}),uo=f({type:b("image"),data:og,mimeType:c(),annotations:Ut.optional(),_meta:T(c(),j()).optional()}),po=f({type:b("audio"),data:og,mimeType:c(),annotations:Ut.optional(),_meta:T(c(),j()).optional()}),Ki=f({type:b("tool_use"),name:c(),id:c(),input:T(c(),j()),_meta:T(c(),j()).optional()}),mo=f({type:b("resource"),resource:C([On,Nn]),annotations:Ut.optional(),_meta:T(c(),j()).optional()}),ho=An.extend({type:b("resource_link")}),Zt=C([lo,uo,po,ho,mo]),Gi=f({role:nr,content:Zt}),Yi=fe.extend({description:c().optional(),messages:_(Gi)}),Xi=Pe.extend({method:b("notifications/prompts/list_changed"),params:Ie.optional()}),Qi=f({title:c().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),ea=f({taskSupport:K(["required","optional","forbidden"]).optional()}),Cr=f({...jt.shape,...tr.shape,description:c().optional(),inputSchema:f({type:b("object"),properties:T(c(),Xt).optional(),required:_(c()).optional()}).catchall(j()),outputSchema:U({$schema:c().optional()}).optional(),annotations:Qi.optional(),execution:ea.optional(),_meta:T(c(),j()).optional()}),ta=rr.extend({method:b("tools/list")}),ra=or.extend({tools:_(Cr)}),Ir=fe.extend({content:_(Zt).default([]),structuredContent:j().optional(),isError:k().optional()}),hu=Ir.or(fe.extend({toolResult:j()})),oa=Er.extend({name:c(),arguments:T(c(),j()).optional()}),na=he.extend({method:b("tools/call"),params:oa}),sa=Pe.extend({method:b("notifications/tools/list_changed"),params:Ie.optional()}),ia=f({autoRefresh:k().default(!0),debounceMs:R().int().nonnegative().default(300)}),Mn=K(["debug","info","notice","warning","error","critical","alert","emergency"]),aa=Re.extend({level:Mn}),ca=he.extend({method:b("logging/setLevel"),params:aa}),la=Ie.extend({level:Mn,logger:c().optional(),data:j()}),fo=Pe.extend({method:b("notifications/message"),params:la}),ua=f({name:c().optional()}),da=f({hints:_(ua).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),pa=f({mode:K(["auto","required","none"]).optional()}),ma=f({type:b("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:_(Zt),structuredContent:j().optional(),isError:k().optional(),_meta:T(c(),j()).optional()}),ha=xr("type",[lo,uo,po]),Tr=xr("type",[lo,uo,po,Ki,ma]),fa=f({role:nr,content:C([Tr,_(Tr)]),_meta:T(c(),j()).optional()}),ga=Er.extend({messages:_(fa),modelPreferences:da.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(c()).optional(),metadata:me.optional(),tools:_(Cr).optional(),toolChoice:pa.optional()}),Sa=he.extend({method:b("sampling/createMessage"),params:ga}),_a=fe.extend({model:c(),stopReason:L(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:nr,content:ha}),ba=fe.extend({model:c(),stopReason:L(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:nr,content:C([Tr,_(Tr)])}),jn=f({type:b("boolean"),title:c().optional(),description:c().optional(),default:k().optional()}),go=f({type:b("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),So=f({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),Ln=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),default:c().optional()}),Un=f({type:b("string"),title:c().optional(),description:c().optional(),oneOf:_(f({const:c(),title:c()})),default:c().optional()}),Zn=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),enumNames:_(c()).optional(),default:c().optional()}),ya=C([Ln,Un]),Dn=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(c())}),default:_(c()).optional()}),Fn=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:c(),title:c()}))}),default:_(c()).optional()}),va=C([Dn,Fn]),za=C([Zn,ya,va]),Hn=C([za,jn,go,So]),_o=Er.extend({mode:b("form").optional(),message:c(),requestedSchema:f({type:b("object"),properties:T(c(),Hn),required:_(c()).optional()}).catchall(j())}),Ra=Er.extend({mode:b("url"),message:c(),elicitationId:c(),url:c().url()}),wa=C([_o,Ra]),xa=he.extend({method:b("elicitation/create"),params:wa}),Pa=Ie.extend({elicitationId:c()}),Ta=Pe.extend({method:b("notifications/elicitation/complete"),params:Pa}),Ea=fe.extend({action:K(["accept","decline","cancel"]),content:Yt(e=>e===null?void 0:e,T(c(),C([c(),R(),k(),_(c())])).optional())}),ka=f({type:b("ref/resource"),uri:c()}),$a=f({type:b("ref/prompt"),name:c()}),Ca=Re.extend({ref:C([$a,ka]),argument:f({name:c(),value:c()}),context:f({arguments:T(c(),c()).optional()}).optional()}),Ia=he.extend({method:b("completion/complete"),params:Ca}),Oa=fe.extend({completion:U({values:_(c()).max(100),total:L(R().int()),hasMore:L(k())})}),Na=f({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),j()).optional()}),Aa=he.extend({method:b("roots/list"),params:Re.optional()}),qa=fe.extend({roots:_(Na)}),Ma=Pe.extend({method:b("notifications/roots/list_changed"),params:Ie.optional()}),fu=U({ttl:R().optional(),pollInterval:R().optional()}),ja=K(["working","input_required","completed","failed","cancelled"]),sr=f({taskId:c(),status:ja,ttl:C([R(),Mt()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:L(R()),statusMessage:L(c())}),gu=fe.extend({task:sr}),La=Ie.merge(sr),Su=Pe.extend({method:b("notifications/tasks/status"),params:La}),_u=he.extend({method:b("tasks/get"),params:Re.extend({taskId:c()})}),bu=fe.merge(sr),yu=he.extend({method:b("tasks/result"),params:Re.extend({taskId:c()})}),vu=fe.loose(),zu=rr.extend({method:b("tasks/list")}),Ru=or.extend({tasks:_(sr)}),wu=he.extend({method:b("tasks/cancel"),params:Re.extend({taskId:c()})}),xu=fe.merge(sr),Pu=C([$n,Tn,_i,Ia,ca,Wi,Vi,Ri,xi,Ei,Ii,Ni,qi,na,ta]),Tu=C([Pn,Cn,kn,Ma]),Eu=C([kr,_a,ba,Ea,qa]),ku=C([$n,Sa,xa,Aa]),$u=C([Pn,Cn,fo,Di,$i,sa,Xi,ji,Ta]),Cu=C([kr,Si,$r,Oa,Yi,Ji,wi,Pi,ki,Ir,ra,Ui]),ze=pn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:tg.custom,message:"URL must be parseable",fatal:!0}),Is}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Vn=U({resource:c().url(),authorization_servers:_(ze).optional(),jwks_uri:c().url().optional(),scopes_supported:_(c()).optional(),bearer_methods_supported:_(c()).optional(),resource_signing_alg_values_supported:_(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:k().optional(),authorization_details_types_supported:_(c()).optional(),dpop_signing_alg_values_supported:_(c()).optional(),dpop_bound_access_tokens_required:k().optional()}),bo=U({issuer:c(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),service_documentation:ze.optional(),revocation_endpoint:ze.optional(),revocation_endpoint_auth_methods_supported:_(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:_(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(c()).optional(),code_challenge_methods_supported:_(c()).optional(),client_id_metadata_document_supported:k().optional(),authorization_response_iss_parameter_supported:k().optional().catch(void 0),dpop_signing_alg_values_supported:_(c()).optional()}),Ua=U({issuer:c(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),acr_values_supported:_(c()).optional(),subject_types_supported:_(c()),id_token_signing_alg_values_supported:_(c()),id_token_encryption_alg_values_supported:_(c()).optional(),id_token_encryption_enc_values_supported:_(c()).optional(),userinfo_signing_alg_values_supported:_(c()).optional(),userinfo_encryption_alg_values_supported:_(c()).optional(),userinfo_encryption_enc_values_supported:_(c()).optional(),request_object_signing_alg_values_supported:_(c()).optional(),request_object_encryption_alg_values_supported:_(c()).optional(),request_object_encryption_enc_values_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),display_values_supported:_(c()).optional(),claim_types_supported:_(c()).optional(),claims_supported:_(c()).optional(),service_documentation:c().optional(),claims_locales_supported:_(c()).optional(),ui_locales_supported:_(c()).optional(),claims_parameter_supported:k().optional(),request_parameter_supported:k().optional(),request_uri_parameter_supported:k().optional(),require_request_uri_registration:k().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:k().optional(),authorization_response_iss_parameter_supported:k().optional().catch(void 0)}),Jn=f({...Ua.shape,...bo.pick({code_challenge_methods_supported:!0}).shape}),Bn=f({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:li.number().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),Za=f({issued_token_type:b("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:R().optional(),scope:c().optional()}).strip(),Wn=f({error:c(),error_description:c().optional(),error_uri:c().optional()}),rg=ze.optional().or(b("").transform(()=>{})),Da=f({redirect_uris:_(ze),token_endpoint_auth_method:c().optional(),grant_types:_(c()).optional(),response_types:_(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:ze.optional(),logo_uri:rg,scope:c().optional(),contacts:_(c()).optional(),tos_uri:rg,policy_uri:c().optional(),jwks_uri:ze.optional(),jwks:ou().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Fa=f({client_id:c(),client_secret:c().optional(),client_id_issued_at:R().optional(),client_secret_expires_at:R().optional(),issuer:c().optional().catch(void 0)}).strip(),Kn=Da.merge(Fa),Iu=f({error:c(),error_description:c().optional()}).strip(),Ou=f({token:c(),token_type_hint:c().optional()}).strip();var cg=Symbol.for("mcp.sdk.errorBrands");function yo(e,t){let r=new Set,o=t;for(;typeof o=="function";){let n=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n=="string"&&r.add(n),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,cg,{value:r,enumerable:!1,configurable:!0})}function at(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,cg)){let r=t[cg];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var ar=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),vo=class Rb extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return at(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",yo(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Rb(t.error,t.error_description??t.error,t.error_uri)}},A=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),q=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return at(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",yo(this,new.target)}},Dt=class extends q{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function wb(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function mg(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function xb({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.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 Pb="2026-07-28",hg=[Pb];function cr(e){return e>=Pb}function fg(e){return e.filter(t=>!cr(t))}function Ka(e){return e.filter(t=>cr(t))}function Tb(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Eb=["task","inputRequests","requestState"];function PR(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Eb.some(t=>t in e)?e:{...e,content:[]}}function TR(){let e=Pr(()=>C([c(),R(),k(),Mt(),T(c(),e),_(e)])),t=T(c(),e),r=C([c(),R().int()]),o=c(),n=f({ttl:R().optional()}),s=f({taskId:c()}),i=U({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=f({_meta:i.optional()}),l=a.extend({task:n.optional()}),u=f({method:c(),params:a.loose().optional()}),d=f({_meta:i.optional()}),m=f({method:c(),params:d.loose().optional()}),h=U({_meta:i.optional()}),g=C([c(),R().int()]),v=h.strict(),w=d.extend({requestId:g.optional(),reason:c().optional()}),y=m.extend({method:b("notifications/cancelled"),params:w}),D=f({src:c(),mimeType:c().optional(),sizes:_(c()).optional(),theme:K(["light","dark"]).optional()}),W=f({icons:_(D).optional()}),N=f({name:c(),title:c().optional()}),F=N.extend({...N.shape,...W.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=bt(f({applyDefaults:k().optional()}),t),z=Yt($e=>$e&&typeof $e=="object"&&!Array.isArray($e)&&Object.keys($e).length===0?{form:{}}:$e,bt(f({form:x.optional(),url:t.optional()}),t.optional())),Z=U({list:t.optional(),cancel:t.optional(),requests:U({sampling:U({createMessage:t.optional()}).optional(),elicitation:U({create:t.optional()}).optional()}).optional()}),oe=U({list:t.optional(),cancel:t.optional(),requests:U({tools:U({call:t.optional()}).optional()}).optional()}),te=f({experimental:T(c(),t).optional(),sampling:f({context:t.optional(),tools:t.optional()}).optional(),elicitation:z.optional(),roots:f({listChanged:k().optional()}).optional(),tasks:Z.optional(),extensions:T(c(),t).optional()}),pe=a.extend({protocolVersion:c(),capabilities:te,clientInfo:F}),Ne=u.extend({method:b("initialize"),params:pe}),ae=f({experimental:T(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:f({listChanged:k().optional()}).optional(),resources:f({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:f({listChanged:k().optional()}).optional(),tasks:oe.optional(),extensions:T(c(),t).optional()}),de=h.extend({protocolVersion:c(),capabilities:ae,serverInfo:F,instructions:c().optional()}),we=m.extend({method:b("notifications/initialized"),params:d.optional()}),Ae=u.extend({method:b("ping"),params:a.optional()}),xt=f({progress:R(),total:L(R()),message:L(c())}),Je=f({...d.shape,...xt.shape,progressToken:r}),ct=m.extend({method:b("notifications/progress"),params:Je}),Pt=a.extend({cursor:o.optional()}),Qe=u.extend({params:Pt.optional()}),qe=h.extend({nextCursor:o.optional()}),Vt=f({uri:c(),mimeType:L(c()),_meta:T(c(),j()).optional()}),Jt=Vt.extend({text:c()}),Tt=c().refine($e=>{try{return atob($e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ee=Vt.extend({blob:Tt}),Me=K(["user","assistant"]),je=f({audience:_(Me).optional(),priority:R().min(0).max(1).optional(),lastModified:it.datetime({offset:!0}).optional()}),ft=f({...N.shape,...W.shape,uri:c(),description:L(c()),mimeType:L(c()),size:L(R()),annotations:je.optional(),_meta:L(U({}))}),jr=f({...N.shape,...W.shape,uriTemplate:c(),description:L(c()),mimeType:L(c()),annotations:je.optional(),_meta:L(U({}))}),et=Qe.extend({method:b("resources/list")}),tt=qe.extend({resources:_(ft)}),Be=Qe.extend({method:b("resources/templates/list")}),lt=qe.extend({resourceTemplates:_(jr)}),ut=a.extend({uri:c()}),Et=ut,kt=u.extend({method:b("resources/read"),params:Et}),dr=h.extend({contents:_(C([Jt,Ee]))}),$t=m.extend({method:b("notifications/resources/list_changed"),params:d.optional()}),Lr=ut,I=u.extend({method:b("resources/subscribe"),params:Lr}),Ct=ut,H=u.extend({method:b("resources/unsubscribe"),params:Ct}),M=d.extend({uri:c()}),Q=m.extend({method:b("notifications/resources/updated"),params:M}),O=f({name:c(),description:L(c()),required:L(k())}),E=f({...N.shape,...W.shape,description:L(c()),arguments:L(_(O)),_meta:L(U({}))}),J=Qe.extend({method:b("prompts/list")}),V=qe.extend({prompts:_(E)}),ve=a.extend({name:c(),arguments:T(c(),c()).optional()}),Ur=u.extend({method:b("prompts/get"),params:ve}),It=f({type:b("text"),text:c(),annotations:je.optional(),_meta:T(c(),j()).optional()}),Zr=f({type:b("image"),data:Tt,mimeType:c(),annotations:je.optional(),_meta:T(c(),j()).optional()}),Dr=f({type:b("audio"),data:Tt,mimeType:c(),annotations:je.optional(),_meta:T(c(),j()).optional()}),ns=f({type:b("tool_use"),name:c(),id:c(),input:T(c(),j()),_meta:T(c(),j()).optional()}),pr=f({type:b("resource"),resource:C([Jt,Ee]),annotations:je.optional(),_meta:T(c(),j()).optional()}),ss=ft.extend({type:b("resource_link")}),dt=C([It,Zr,Dr,ss,pr]),ko=f({role:Me,content:dt}),$o=h.extend({description:c().optional(),messages:_(ko)}),Fr=m.extend({method:b("notifications/prompts/list_changed"),params:d.optional()}),is=f({title:c().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),Co=f({taskSupport:K(["required","optional","forbidden"]).optional()}),Hr=f({...N.shape,...W.shape,description:c().optional(),inputSchema:f({type:b("object"),properties:T(c(),e).optional(),required:_(c()).optional()}).catchall(j()),outputSchema:f({type:b("object"),properties:T(c(),e).optional(),required:_(c()).optional()}).catchall(j()).optional(),annotations:is.optional(),execution:Co.optional(),_meta:T(c(),j()).optional()}),Io=Qe.extend({method:b("tools/list")}),Oo=qe.extend({tools:_(Hr)}),No=h.extend({content:_(dt),structuredContent:T(c(),j()).optional(),isError:k().optional()}),ke=l.extend({name:c(),arguments:T(c(),j()).optional()}),as=u.extend({method:b("tools/call"),params:ke}),lc=m.extend({method:b("notifications/tools/list_changed"),params:d.optional()}),Ao=K(["debug","info","notice","warning","error","critical","alert","emergency"]),cs=a.extend({level:Ao}),ls=u.extend({method:b("logging/setLevel"),params:cs}),us=d.extend({level:Ao,logger:c().optional(),data:j()}),ds=m.extend({method:b("notifications/message"),params:us}),ps=f({name:c().optional()}),ms=f({hints:_(ps).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),hs=f({mode:K(["auto","required","none"]).optional()}),uc=f({type:b("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:_(dt),structuredContent:f({}).loose().optional(),isError:k().optional(),_meta:T(c(),j()).optional()}),fs=xr("type",[It,Zr,Dr]),mr=xr("type",[It,Zr,Dr,ns,uc]),gs=f({role:Me,content:C([mr,_(mr)]),_meta:T(c(),j()).optional()}),Ss=l.extend({messages:_(gs),modelPreferences:ms.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(c()).optional(),metadata:t.optional(),tools:_(Hr).optional(),toolChoice:hs.optional()}),_s=u.extend({method:b("sampling/createMessage"),params:Ss}),bs=h.extend({model:c(),stopReason:L(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Me,content:fs}),ys=h.extend({model:c(),stopReason:L(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Me,content:C([mr,_(mr)])}),vs=f({type:b("boolean"),title:c().optional(),description:c().optional(),default:k().optional()}),zs=f({type:b("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rs=f({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),ws=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),default:c().optional()}),xs=f({type:b("string"),title:c().optional(),description:c().optional(),oneOf:_(f({const:c(),title:c()})),default:c().optional()}),Ps=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),enumNames:_(c()).optional(),default:c().optional()}),Ts=C([ws,xs]),Vr=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(c())}),default:_(c()).optional()}),Jr=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:c(),title:c()}))}),default:_(c()).optional()}),dc=C([Vr,Jr]),pc=C([Ps,Ts,dc]),rt=C([pc,vs,zs,Rs]),ot=l.extend({mode:b("form").optional(),message:c(),requestedSchema:f({type:b("object"),properties:T(c(),rt),required:_(c()).optional()}).catchall(j())}),Es=l.extend({mode:b("url"),message:c(),elicitationId:c(),url:c().url()}),gt=C([ot,Es]),mc=u.extend({method:b("elicitation/create"),params:gt}),hc=d.extend({elicitationId:c()}),fc=m.extend({method:b("notifications/elicitation/complete"),params:hc}),gc=h.extend({action:K(["accept","decline","cancel"]),content:Yt($e=>$e===null?void 0:$e,T(c(),C([c(),R(),k(),_(c())])).optional())}),Sc=f({type:b("ref/resource"),uri:c()}),_c=f({type:b("ref/prompt"),name:c()}),bc=a.extend({ref:C([_c,Sc]),argument:f({name:c(),value:c()}),context:f({arguments:T(c(),c()).optional()}).optional()}),ks=u.extend({method:b("completion/complete"),params:bc}),yc=h.extend({completion:U({values:_(c()).max(100),total:L(R().int()),hasMore:L(k())})}),vc=f({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),j()).optional()}),qo=u.extend({method:b("roots/list"),params:a.optional()}),$s=h.extend({roots:_(vc)}),zc=m.extend({method:b("notifications/roots/list_changed"),params:d.optional()}),Rc=U({ttl:R().optional(),pollInterval:R().optional()}),Cs=K(["working","input_required","completed","failed","cancelled"]),hr=f({taskId:c(),status:Cs,ttl:C([R(),Mt()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:L(R()),statusMessage:L(c())}),We=h.extend({task:hr}),wc=d.merge(hr),Br=m.extend({method:b("notifications/tasks/status"),params:wc}),Mo=u.extend({method:b("tasks/get"),params:a.extend({taskId:c()})}),jo=h.merge(hr),Lo=u.extend({method:b("tasks/result"),params:a.extend({taskId:c()})}),sd=h.loose(),Le=Qe.extend({method:b("tasks/list")}),ye=qe.extend({tasks:_(hr)}),Wr=u.extend({method:b("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:h,RequestIdSchema:g,EmptyResultSchema:v,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:y,IconSchema:D,IconsSchema:W,BaseMetadataSchema:N,ImplementationSchema:F,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:oe,ClientCapabilitiesSchema:te,InitializeRequestParamsSchema:pe,InitializeRequestSchema:Ne,ServerCapabilitiesSchema:ae,InitializeResultSchema:de,InitializedNotificationSchema:we,PingRequestSchema:Ae,ProgressSchema:xt,ProgressNotificationParamsSchema:Je,ProgressNotificationSchema:ct,PaginatedRequestParamsSchema:Pt,PaginatedRequestSchema:Qe,PaginatedResultSchema:qe,ResourceContentsSchema:Vt,TextResourceContentsSchema:Jt,BlobResourceContentsSchema:Ee,RoleSchema:Me,AnnotationsSchema:je,ResourceSchema:ft,ResourceTemplateSchema:jr,ListResourcesRequestSchema:et,ListResourcesResultSchema:tt,ListResourceTemplatesRequestSchema:Be,ListResourceTemplatesResultSchema:lt,ResourceRequestParamsSchema:ut,ReadResourceRequestParamsSchema:Et,ReadResourceRequestSchema:kt,ReadResourceResultSchema:dr,ResourceListChangedNotificationSchema:$t,SubscribeRequestParamsSchema:Lr,SubscribeRequestSchema:I,UnsubscribeRequestParamsSchema:Ct,UnsubscribeRequestSchema:H,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:Q,PromptArgumentSchema:O,PromptSchema:E,ListPromptsRequestSchema:J,ListPromptsResultSchema:V,GetPromptRequestParamsSchema:ve,GetPromptRequestSchema:Ur,TextContentSchema:It,ImageContentSchema:Zr,AudioContentSchema:Dr,ToolUseContentSchema:ns,EmbeddedResourceSchema:pr,ResourceLinkSchema:ss,ContentBlockSchema:dt,PromptMessageSchema:ko,GetPromptResultSchema:$o,PromptListChangedNotificationSchema:Fr,ToolAnnotationsSchema:is,ToolExecutionSchema:Co,ToolSchema:Hr,ListToolsRequestSchema:Io,ListToolsResultSchema:Oo,CallToolResultSchema:No,CallToolRequestParamsSchema:ke,CallToolRequestSchema:as,ToolListChangedNotificationSchema:lc,LoggingLevelSchema:Ao,SetLevelRequestParamsSchema:cs,SetLevelRequestSchema:ls,LoggingMessageNotificationParamsSchema:us,LoggingMessageNotificationSchema:ds,ModelHintSchema:ps,ModelPreferencesSchema:ms,ToolChoiceSchema:hs,ToolResultContentSchema:uc,SamplingContentSchema:fs,SamplingMessageContentBlockSchema:mr,SamplingMessageSchema:gs,CreateMessageRequestParamsSchema:Ss,CreateMessageRequestSchema:_s,CreateMessageResultSchema:bs,CreateMessageResultWithToolsSchema:ys,BooleanSchemaSchema:vs,StringSchemaSchema:zs,NumberSchemaSchema:Rs,UntitledSingleSelectEnumSchemaSchema:ws,TitledSingleSelectEnumSchemaSchema:xs,LegacyTitledEnumSchemaSchema:Ps,SingleSelectEnumSchemaSchema:Ts,UntitledMultiSelectEnumSchemaSchema:Vr,TitledMultiSelectEnumSchemaSchema:Jr,MultiSelectEnumSchemaSchema:dc,EnumSchemaSchema:pc,PrimitiveSchemaDefinitionSchema:rt,ElicitRequestFormParamsSchema:ot,ElicitRequestURLParamsSchema:Es,ElicitRequestParamsSchema:gt,ElicitRequestSchema:mc,ElicitationCompleteNotificationParamsSchema:hc,ElicitationCompleteNotificationSchema:fc,ElicitResultSchema:gc,ResourceTemplateReferenceSchema:Sc,PromptReferenceSchema:_c,CompleteRequestParamsSchema:bc,CompleteRequestSchema:ks,CompleteResultSchema:yc,RootSchema:vc,ListRootsRequestSchema:qo,ListRootsResultSchema:$s,RootsListChangedNotificationSchema:zc,TaskCreationParamsSchema:Rc,TaskStatusSchema:Cs,TaskSchema:hr,CreateTaskResultSchema:We,TaskStatusNotificationParamsSchema:wc,TaskStatusNotificationSchema:Br,GetTaskRequestSchema:Mo,GetTaskResultSchema:jo,GetTaskPayloadRequestSchema:Lo,GetTaskPayloadResultSchema:sd,ListTasksRequestSchema:Le,ListTasksResultSchema:ye,CancelTaskRequestSchema:Wr,CancelTaskResultSchema:h.merge(hr),ClientRequestSchema:C([Ae,Ne,ks,ls,Ur,J,et,Be,kt,I,H,as,Io,Mo,Lo,Le,Wr]),ClientNotificationSchema:C([y,ct,we,zc,Br]),ClientResultSchema:C([v,bs,ys,gc,$s,jo,ye,We]),ServerRequestSchema:C([Ae,_s,mc,qo,Mo,Lo,Le,Wr]),ServerNotificationSchema:C([y,ct,ds,Q,$t,lc,Fr,Br,fc]),ServerResultSchema:C([v,de,yc,$o,V,tt,lt,dr,No,Oo,jo,ye,We]),CallToolResultWireSchema:j().superRefine(($e,bv)=>{if(!(typeof $e!="object"||$e===null||Array.isArray($e)||$e.content!==void 0)){for(let oS of Eb)if(oS in $e){bv.addIssue({code:"custom",message:`content is required when the body carries '${oS}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(PR).pipe(No)}}var ER;function kb(){return ER??=TR()}function $b(e){return e.type!=="object"}var kR=new Set(["const","enum","default","examples"]),$R=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ub(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function CR(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(ub(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=cS(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map(l=>o(l,!1));if(n===null||typeof n!="object"||!s&&ub(n.$id))return n;let i={},a=!1;for(let[l,u]of Object.entries(n))s?i[l]=o(u,!1):(l==="$ref"||l==="$dynamicRef")&&typeof u=="string"?i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:l==="$recursiveRef"&&u==="#"&&r?a=!0:kR.has(l)?i[l]=u:$R.has(l)?i[l]=o(u,!0):i[l]=o(u,!1);return a&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Cb={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ib={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},IR={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Nu;function gg(){if(Nu)return Nu;let e=kb();return Nu={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Nu}function Ob(e){return Object.prototype.hasOwnProperty.call(Cb,e)}function Nb(e){return Object.prototype.hasOwnProperty.call(Ib,e)}function OR(e){return Object.prototype.hasOwnProperty.call(IR,e)}function NR(e){return OR(e)?gg().resultSchemas[e]:void 0}function AR(e){return Ob(e)?gg().requestSchemas[e]:void 0}function qR(e){return Nb(e)?gg().notificationSchemas[e]:void 0}var jE=Object.keys(Cb),LE=Object.keys(Ib);function lg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Au(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var db={ok:!1,reason:"not-in-era"};function pb(e){return lg(e)&&lg(e.outputSchema)&&$b(e.outputSchema)}var Sg={era:"2025-11-25",hasRequestMethod:Ob,hasNotificationMethod:Nb,validateRequest:(e,t)=>Au(AR(e),t),validateResult:(e,t)=>Au(NR(e),t),validateNotification:(e,t)=>Au(qR(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>db,validateInputResponse:()=>db,samplingResultVariant:((e,t)=>{let r=kb();return Au(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=Tb(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&$b(t);return!n&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(lg(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(o=>pb(o))?t:{...t,tools:r.map(o=>pb(o)?{...o,outputSchema:CR(o.outputSchema)}:o)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function MR(){let e=Pr(()=>C([c(),R(),k(),Mt(),T(c(),e),_(e)])),t=T(c(),e),r=C([c(),R().int()]),o=c(),n=C([c(),R().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine(ye=>{try{return atob(ye),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=f({ttl:R().optional()}),u=f({taskId:c()}),d=U({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=f({_meta:d.optional()}),h=m.extend({task:l.optional()}),g=f({_meta:d.optional()}),v=f({method:c(),params:g.loose().optional()}),w=f({src:c(),mimeType:c().optional(),sizes:_(c()).optional(),theme:K(["light","dark"]).optional()}),y=f({icons:_(w).optional()}),D=f({name:c(),title:c().optional()}),W=D.extend({...D.shape,...y.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),N=bt(f({applyDefaults:k().optional()}),t),F=Yt(ye=>ye&&typeof ye=="object"&&!Array.isArray(ye)&&Object.keys(ye).length===0?{form:{}}:ye,bt(f({form:N.optional(),url:t.optional()}),t.optional())),x=U({list:t.optional(),cancel:t.optional(),requests:U({sampling:U({createMessage:t.optional()}).optional(),elicitation:U({create:t.optional()}).optional()}).optional()}),z=U({list:t.optional(),cancel:t.optional(),requests:U({tools:U({call:t.optional()}).optional()}).optional()}),Z=f({experimental:T(c(),t).optional(),sampling:f({context:t.optional(),tools:t.optional()}).optional(),elicitation:F.optional(),roots:f({listChanged:k().optional()}).optional(),tasks:x.optional(),extensions:T(c(),t).optional()}),oe=f({experimental:T(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:f({listChanged:k().optional()}).optional(),resources:f({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:f({listChanged:k().optional()}).optional(),tasks:z.optional(),extensions:T(c(),t).optional()}),te=f({progress:R(),total:L(R()),message:L(c())}),pe=f({...g.shape,...te.shape,progressToken:r}),Ne=v.extend({method:b("notifications/progress"),params:pe}),ae=g.extend({level:i,logger:c().optional(),data:j()}),de=v.extend({method:b("notifications/message"),params:ae}),we=f({uri:c(),mimeType:L(c()),_meta:T(c(),j()).optional()}),Ae=we.extend({text:c()}),xt=we.extend({blob:a}),Je=f({audience:_(s).optional(),priority:R().min(0).max(1).optional(),lastModified:it.datetime({offset:!0}).optional()}),ct=f({...D.shape,...y.shape,uri:c(),description:L(c()),mimeType:L(c()),size:L(R()),annotations:Je.optional(),_meta:L(U({}))}),Pt=f({...D.shape,...y.shape,uriTemplate:c(),description:L(c()),mimeType:L(c()),annotations:Je.optional(),_meta:L(U({}))}),Qe=v.extend({method:b("notifications/resources/list_changed"),params:g.optional()}),qe=g.extend({uri:c()}),Vt=v.extend({method:b("notifications/resources/updated"),params:qe}),Jt=f({name:c(),description:L(c()),required:L(k())}),Tt=f({...D.shape,...y.shape,description:L(c()),arguments:L(_(Jt)),_meta:L(U({}))}),Ee=v.extend({method:b("notifications/prompts/list_changed"),params:g.optional()}),Me=f({type:b("text"),text:c(),annotations:Je.optional(),_meta:T(c(),j()).optional()}),je=f({type:b("image"),data:a,mimeType:c(),annotations:Je.optional(),_meta:T(c(),j()).optional()}),ft=f({type:b("audio"),data:a,mimeType:c(),annotations:Je.optional(),_meta:T(c(),j()).optional()}),jr=f({type:b("tool_use"),name:c(),id:c(),input:T(c(),j()),_meta:T(c(),j()).optional()}),et=f({type:b("resource"),resource:C([Ae,xt]),annotations:Je.optional(),_meta:T(c(),j()).optional()}),tt=ct.extend({type:b("resource_link")}),Be=C([Me,je,ft,tt,et]),lt=f({role:s,content:Be}),ut=f({title:c().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),Et=v.extend({method:b("notifications/tools/list_changed"),params:g.optional()}),kt=f({name:c().optional()}),dr=f({hints:_(kt).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),$t=f({mode:K(["auto","required","none"]).optional()}),Lr=f({type:b("boolean"),title:c().optional(),description:c().optional(),default:k().optional()}),I=f({type:b("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Ct=f({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),H=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),default:c().optional()}),M=f({type:b("string"),title:c().optional(),description:c().optional(),oneOf:_(f({const:c(),title:c()})),default:c().optional()}),Q=f({type:b("string"),title:c().optional(),description:c().optional(),enum:_(c()),enumNames:_(c()).optional(),default:c().optional()}),O=C([H,M]),E=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(c())}),default:_(c()).optional()}),J=f({type:b("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:c(),title:c()}))}),default:_(c()).optional()}),V=C([E,J]),ve=C([Q,O,V]),Ur=C([ve,Lr,I,Ct]),It=h.extend({mode:b("form").optional(),message:c(),requestedSchema:f({type:b("object"),properties:T(c(),Ur),required:_(c()).optional()}).catchall(j())}),Zr=f({type:b("ref/resource"),uri:c()}),Dr=f({type:b("ref/prompt"),name:c()}),ns=f({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),j()).optional()}),pr=Z.shape,ss=f({experimental:pr.experimental,sampling:pr.sampling,elicitation:pr.elicitation,roots:pr.roots,extensions:pr.extensions}),dt=oe.shape,ko=f({experimental:dt.experimental,logging:dt.logging,completions:dt.completions,prompts:dt.prompts,resources:dt.resources,tools:dt.tools,extensions:dt.extensions}),$o=U({progressToken:r.optional(),[Qt]:c(),[_n]:W.optional(),[no]:ss,[bn]:i.optional()}),Fr=f({...D.shape,...y.shape,description:c().optional(),inputSchema:U({$schema:c().optional(),type:b("object")}),outputSchema:U({$schema:c().optional()}).optional(),annotations:ut.optional(),_meta:T(c(),j()).optional()}),is=f({type:b("tool_result"),toolUseId:c(),content:_(Be),structuredContent:j().optional(),isError:k().optional(),_meta:T(c(),j()).optional()}),Co=C([Me,je,ft,jr,is]),Hr=f({role:s,content:C([Co,_(Co)]),_meta:T(c(),j()).optional()}),Io=c(),Oo=U({[er]:W.optional().catch(void 0)}),No=Oo.optional();function ke(ye){return U({_meta:No,resultType:Io.default("complete"),...ye})}let as=ke({}),lc=ke({nextCursor:o.optional()}),Ao=ke({content:_(Be),structuredContent:j().optional(),isError:k().optional()}),cs=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),tools:_(Fr),nextCursor:o.optional()}),ls=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),prompts:_(Tt),nextCursor:o.optional()}),us=ke({description:c().optional(),messages:_(lt)}),ds=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resources:_(ct),nextCursor:o.optional()}),ps=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:_(Pt),nextCursor:o.optional()}),ms=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),contents:_(C([Ae,xt]))}),hs=ke({completion:f({values:_(c()).max(100),total:R().int().optional(),hasMore:k().optional()}).loose()}),uc=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"])}),fs=ke({ttlMs:R().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:_(c()),capabilities:ko,instructions:c().optional()}),mr=f({messages:_(Hr),modelPreferences:dr.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(c()).optional(),metadata:t.optional(),tools:_(Fr).optional(),toolChoice:$t.optional()}),gs=f({method:b("sampling/createMessage"),params:mr}),Ss=f({method:b("roots/list"),params:f({_meta:T(c(),j()).optional()}).optional()}),_s=f({...Hr.shape,model:c(),stopReason:c().optional()}),bs=f({roots:_(ns)}),ys=f({action:K(["accept","decline","cancel"]),content:T(c(),C([c(),R(),k(),_(c())])).optional()}),vs=f({mode:b("url"),message:c(),url:c().url()}),zs=C([It,vs]),Rs=f({method:b("elicitation/create"),params:zs}),ws=C([gs,Ss,Rs]),xs=C([_s,bs,ys]),Ps=T(c(),ws),Ts=T(c(),xs),Vr=ke({inputRequests:Ps.optional(),requestState:c().optional()}),Jr={inputResponses:Ts.optional(),requestState:c().optional()},dc=f({_meta:$o,...Jr}),pc=U({progressToken:r.optional()});function rt(ye,Wr){return f({method:b(ye),params:f({_meta:$o,...Wr})})}function ot(ye,Wr){return f({method:b(ye),params:f({_meta:pc.optional(),...Wr}).optional()})}let Es={name:c(),arguments:T(c(),j()).optional(),...Jr},gt={cursor:o.optional()},mc=rt("tools/call",Es),hc=rt("tools/list",gt),fc=rt("prompts/list",gt),gc=rt("prompts/get",{name:c(),arguments:T(c(),c()).optional(),...Jr}),Sc=rt("resources/list",gt),_c=rt("resources/templates/list",gt),bc=rt("resources/read",{uri:c(),...Jr}),ks={ref:C([Dr,Zr]),argument:f({name:c(),value:c()}),context:f({arguments:T(c(),c()).optional()}).optional()},yc=rt("completion/complete",ks),vc=rt("server/discover",{}),qo=f({toolsListChanged:k().optional(),promptsListChanged:k().optional(),resourcesListChanged:k().optional(),resourceSubscriptions:_(c()).optional()}),$s={notifications:qo},zc=rt("subscriptions/listen",$s),Rc=Oo.extend({"io.modelcontextprotocol/subscriptionId":n}),Cs=U({_meta:Rc,resultType:Io.default("complete")}),hr={"tools/call":ot("tools/call",Es),"tools/list":ot("tools/list",gt),"prompts/get":ot("prompts/get",{name:c(),arguments:T(c(),c()).optional()}),"prompts/list":ot("prompts/list",gt),"resources/list":ot("resources/list",gt),"resources/templates/list":ot("resources/templates/list",gt),"resources/read":ot("resources/read",{uri:c()}),"completion/complete":ot("completion/complete",ks),"server/discover":ot("server/discover",{}),"subscriptions/listen":ot("subscriptions/listen",$s)};function We(ye){return U({_meta:No,...ye})}let wc={"tools/call":We({content:_(Be),structuredContent:j().optional(),isError:k().optional()}),"tools/list":We({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),tools:_(Fr),nextCursor:o.optional()}),"prompts/get":We({description:c().optional(),messages:_(lt)}),"prompts/list":We({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),prompts:_(Tt),nextCursor:o.optional()}),"resources/list":We({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resources:_(ct),nextCursor:o.optional()}),"resources/templates/list":We({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:_(Pt),nextCursor:o.optional()}),"resources/read":We({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),contents:_(C([Ae,xt]))}),"completion/complete":We({completion:f({values:_(c()).max(100),total:R().int().optional(),hasMore:k().optional()}).loose()}),"server/discover":We({ttlMs:R().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:_(c()),capabilities:ko,instructions:c().optional()}),"subscriptions/listen":We({})},Br=U({"io.modelcontextprotocol/subscriptionId":n.optional()}),Mo=f({method:b("notifications/subscriptions/acknowledged"),params:f({_meta:Br.optional(),notifications:qo})}),jo=f({_meta:Br.optional(),requestId:n,reason:c().optional()}),Lo=f({method:b("notifications/cancelled"),params:jo}),sd={"notifications/cancelled":Lo,"notifications/progress":Ne,"notifications/message":de,"notifications/resources/updated":Vt,"notifications/resources/list_changed":Qe,"notifications/tools/list_changed":Et,"notifications/prompts/list_changed":Ee,"notifications/subscriptions/acknowledged":Mo},Le=ye=>f({jsonrpc:b("2.0"),id:C([c(),R().int()]),result:ye}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:h,NotificationsParamsSchema:g,NotificationSchema:v,IconSchema:w,IconsSchema:y,BaseMetadataSchema:D,ImplementationSchema:W,ClientTasksCapabilitySchema:x,ServerTasksCapabilitySchema:z,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:oe,ProgressSchema:te,ProgressNotificationParamsSchema:pe,ProgressNotificationSchema:Ne,LoggingMessageNotificationParamsSchema:ae,LoggingMessageNotificationSchema:de,ResourceContentsSchema:we,TextResourceContentsSchema:Ae,BlobResourceContentsSchema:xt,AnnotationsSchema:Je,ResourceSchema:ct,ResourceTemplateSchema:Pt,ResourceListChangedNotificationSchema:Qe,ResourceUpdatedNotificationParamsSchema:qe,ResourceUpdatedNotificationSchema:Vt,PromptArgumentSchema:Jt,PromptSchema:Tt,PromptListChangedNotificationSchema:Ee,TextContentSchema:Me,ImageContentSchema:je,AudioContentSchema:ft,ToolUseContentSchema:jr,EmbeddedResourceSchema:et,ResourceLinkSchema:tt,ContentBlockSchema:Be,PromptMessageSchema:lt,ToolAnnotationsSchema:ut,ToolListChangedNotificationSchema:Et,ModelHintSchema:kt,ModelPreferencesSchema:dr,ToolChoiceSchema:$t,BooleanSchemaSchema:Lr,StringSchemaSchema:I,NumberSchemaSchema:Ct,UntitledSingleSelectEnumSchemaSchema:H,TitledSingleSelectEnumSchemaSchema:M,LegacyTitledEnumSchemaSchema:Q,SingleSelectEnumSchemaSchema:O,UntitledMultiSelectEnumSchemaSchema:E,TitledMultiSelectEnumSchemaSchema:J,MultiSelectEnumSchemaSchema:V,EnumSchemaSchema:ve,PrimitiveSchemaDefinitionSchema:Ur,ElicitRequestFormParamsSchema:It,ResourceTemplateReferenceSchema:Zr,PromptReferenceSchema:Dr,RootSchema:ns,ClientCapabilities2026Schema:ss,ServerCapabilities2026Schema:ko,RequestMetaEnvelopeSchema:$o,ToolSchema:Fr,ToolResultContentSchema:is,SamplingMessageContentBlockSchema:Co,SamplingMessageSchema:Hr,ResultTypeSchema:Io,ResultMetaSchema:Oo,ResultSchema:as,PaginatedResultSchema:lc,CallToolResultSchema:Ao,ListToolsResultSchema:cs,ListPromptsResultSchema:ls,GetPromptResultSchema:us,ListResourcesResultSchema:ds,ListResourceTemplatesResultSchema:ps,ReadResourceResultSchema:ms,CompleteResultSchema:hs,CacheableResultSchema:uc,DiscoverResultSchema:fs,CreateMessageRequestParamsSchema:mr,CreateMessageRequestSchema:gs,ListRootsRequestSchema:Ss,CreateMessageResultSchema:_s,ListRootsResultSchema:bs,ElicitResultSchema:ys,ElicitRequestURLParamsSchema:vs,ElicitRequestParamsSchema:zs,ElicitRequestSchema:Rs,InputRequestSchema:ws,InputResponseSchema:xs,InputRequestsSchema:Ps,InputResponsesSchema:Ts,InputRequiredResultSchema:Vr,InputResponseRequestParamsSchema:dc,CallToolRequestSchema:mc,ListToolsRequestSchema:hc,ListPromptsRequestSchema:fc,GetPromptRequestSchema:gc,ListResourcesRequestSchema:Sc,ListResourceTemplatesRequestSchema:_c,ReadResourceRequestSchema:bc,CompleteRequestSchema:yc,DiscoverRequestSchema:vc,SubscriptionFilterSchema:qo,SubscriptionsListenRequestSchema:zc,SubscriptionsListenResultMetaSchema:Rc,SubscriptionsListenResultSchema:Cs,dispatchRequestSchemas:hr,dispatchResultSchemas:wc,NotificationMetaSchema:Br,SubscriptionsAcknowledgedNotificationSchema:Mo,CancelledNotificationParamsSchema:jo,CancelledNotificationSchema:Lo,notificationSchemas2026:sd,JSONRPCResultResponseSchema:Le(as),CallToolResultResponseSchema:Le(C([Ao,Vr])),ListToolsResultResponseSchema:Le(cs),ListPromptsResultResponseSchema:Le(ls),GetPromptResultResponseSchema:Le(C([us,Vr])),ListResourcesResultResponseSchema:Le(ds),ListResourceTemplatesResultResponseSchema:Le(ps),ReadResourceResultResponseSchema:Le(C([ms,Vr])),CompleteResultResponseSchema:Le(hs),DiscoverResultResponseSchema:Le(fs),SubscriptionsListenResultResponseSchema:Le(Cs)}}var jR;function Or(){return jR??=MR()}var LR=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function UR(e){return LR.includes(e)}var _g=Symbol("modelcontextprotocol.resultCacheHintFallback");function ZR(e){return e[_g]}function Ab(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function qb(e){return e==="public"||e==="private"}var B=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),ie=class Mb extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return at(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",yo(this,new.target)}static fromError(t,r,o){if(t===B.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Lb(n.elicitations,r)}if(t===B.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested=="string")return new Uu({supported:n.supported,requested:n.requested},r)}if(t===B.InvalidParams||t===B.ResourceNotFound){let n=o;if(typeof n?.uri=="string"&&(t===B.ResourceNotFound||Object.keys(n).length===1))return new jb(n.uri,r)}if(t===B.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities=="object"&&!Array.isArray(n.requiredCapabilities))return new Ub({requiredCapabilities:n.requiredCapabilities},r)}return new Mb(t,r,o)}},jb=class extends ie{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(B.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Lb=class extends ie{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Uu=class extends ie{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(B.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Ub=class extends ie{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(B.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},DR=0,FR="private",HR=["tools/call","prompts/get","resources/read"];function VR(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||HR.includes(e))return t;throw new ie(B.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function JR(e,t){let r=ZR(t);if(t.resultType!=="complete"||!UR(e))return r===void 0?t:YR(t);let o=t,n=Ab(o.ttlMs)?o.ttlMs:KR(r),s=qb(o.cacheScope)?o.cacheScope:GR(r),i={...o,ttlMs:n,cacheScope:s};return delete i[_g],i}function BR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function WR(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[er]:t}}:!BR(r)||r[er]!==void 0?e:{...e,_meta:{...r,[er]:t}}}function KR(e){return e!==void 0&&Ab(e.ttlMs)?e.ttlMs:DR}function GR(e){return e!==void 0&&qb(e.cacheScope)?e.cacheScope:FR}function YR(e){let t={...e};return delete t[_g],t}var XR=["elicitation/create","sampling/createMessage","roots/list"],qu;function Zb(){if(qu)return qu;let e=Or();return qu={request:{"elicitation/create":f({method:b("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":f({method:b("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":f({method:b("roots/list"),params:U({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},qu}function Db(e){return XR.includes(e)}function ng(e){return Db(e)?Zb().request[e]:void 0}function QR(e){return Db(e)?Zb().response[e]:void 0}var bg={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Fb={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Hb(e){return Object.prototype.hasOwnProperty.call(bg,e)}function Vb(e){return Object.prototype.hasOwnProperty.call(Fb,e)}function ew(e){return Object.prototype.hasOwnProperty.call(bg,e)}function tw(e){return Hb(e)?Or().dispatchRequestSchemas[e]:void 0}function rw(e){return ew(e)?Or().dispatchResultSchemas[e]:void 0}function ow(e){return Vb(e)?Or().notificationSchemas2026[e]:void 0}var UE=Object.keys(bg),ZE=Object.keys(Fb);function Ja(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ha(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var nw={ok:!1,reason:"not-in-era"},sw=[Qt,no];function iw(e,t){let r=t,o=!1,n=()=>(o||(r={...r},o=!0),r),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Ja(a)&&"execution"in a)&&(n().tools=s.map(a=>{if(!Ja(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l}));let i=t.capabilities;if(Ja(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var yg={era:"2026-07-28",hasRequestMethod:Hb,hasNotificationMethod:Vb,hasInputRequestMethod:e=>ng(e)!==void 0,validateRequest:(e,t)=>Ha(tw(e),t),validateResult:(e,t)=>Ha(rw(e),t),validateNotification:(e,t)=>Ha(ow(e),t),validateInputRequest:(e,t)=>Ha(ng(e),t),validateInputResponse:(e,t)=>Ha(QR(e),t),samplingResultVariant:()=>nw,outboundEnvelope(e){return{[Qt]:e.protocolVersion,[_n]:e.clientInfo,[no]:e.clientCapabilities,...e.logLevel!==void 0&&{[bn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of sw)o in e||t.push({key:o,problem:"missing"});let r=Or().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";n.length===1&&t.some(i=>i.key===s&&i.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:e=>Tb(e),inputRequestSchema:ng,decodeResult(e,t){if(!Ja(t))return{kind:"invalid",error:new q(A.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new q(A.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new q(A.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=Ja(i)?i:{},l=t.requestState,u=t._meta===void 0?void 0:Or().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;return Object.keys(a).length===0&&typeof l!="string"?{kind:"invalid",error:new q(A.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:a,...typeof l=="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new q(A.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=aw(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new q(A.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return WR(JR(e,VR(e,iw(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Or().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Mu;function aw(){if(Mu)return Mu;let e=Or();return Mu={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Mu}var Zu="2026-07-28";function ir(e){return e!==void 0&&cr(e)?yg:Sg}function mb(e){return e.revision!==void 0?ir(e.revision).era:e.era==="modern"?yg.era:Sg.era}function sg(e){return Jb.some(t=>t.hasRequestMethod(e))}function ig(e){return Jb.some(t=>t.hasNotificationMethod(e))}function hb(e){return e==="tasks/get"||e==="tasks/cancel"}var Jb=[Sg,yg],cw=sS({AnnotationsSchema:()=>Ut,AudioContentSchema:()=>po,BaseMetadataSchema:()=>jt,BaseRequestParamsSchema:()=>Re,BlobResourceContentsSchema:()=>Nn,BooleanSchemaSchema:()=>jn,CallToolRequestParamsSchema:()=>oa,CallToolRequestSchema:()=>na,CallToolResultSchema:()=>Ir,CancelTaskRequestSchema:()=>wu,CancelTaskResultSchema:()=>xu,CancelledNotificationParamsSchema:()=>mi,CancelledNotificationSchema:()=>Pn,ClientCapabilitiesSchema:()=>fi,ClientNotificationSchema:()=>Tu,ClientRequestSchema:()=>Pu,ClientResultSchema:()=>Eu,ClientTasksCapabilitySchema:()=>pu,CompatibilityCallToolResultSchema:()=>hu,CompleteRequestParamsSchema:()=>Ca,CompleteRequestSchema:()=>Ia,CompleteResultSchema:()=>Oa,ContentBlockSchema:()=>Zt,CreateMessageRequestParamsSchema:()=>ga,CreateMessageRequestSchema:()=>Sa,CreateMessageResultSchema:()=>_a,CreateMessageResultWithToolsSchema:()=>ba,CreateTaskResultSchema:()=>gu,CursorSchema:()=>vn,DiscoverRequestSchema:()=>_i,DiscoverResultSchema:()=>$r,ElicitRequestFormParamsSchema:()=>_o,ElicitRequestParamsSchema:()=>wa,ElicitRequestSchema:()=>xa,ElicitRequestURLParamsSchema:()=>Ra,ElicitResultSchema:()=>Ea,ElicitationCompleteNotificationParamsSchema:()=>Pa,ElicitationCompleteNotificationSchema:()=>Ta,EmbeddedResourceSchema:()=>mo,EmptyResultSchema:()=>kr,EnumSchemaSchema:()=>za,GetPromptRequestParamsSchema:()=>Bi,GetPromptRequestSchema:()=>Wi,GetPromptResultSchema:()=>Yi,GetTaskPayloadRequestSchema:()=>yu,GetTaskPayloadResultSchema:()=>vu,GetTaskRequestSchema:()=>_u,GetTaskResultSchema:()=>bu,IconSchema:()=>hi,IconsSchema:()=>tr,ImageContentSchema:()=>uo,ImplementationSchema:()=>Lt,InitializeRequestParamsSchema:()=>gi,InitializeRequestSchema:()=>Tn,InitializeResultSchema:()=>Si,InitializedNotificationSchema:()=>kn,JSONArraySchema:()=>uu,JSONObjectSchema:()=>me,JSONRPCErrorResponseSchema:()=>ao,JSONRPCMessageSchema:()=>vt,JSONRPCNotificationSchema:()=>xn,JSONRPCRequestSchema:()=>wn,JSONRPCResponseSchema:()=>du,JSONRPCResultResponseSchema:()=>io,JSONValueSchema:()=>Xt,LegacyTitledEnumSchemaSchema:()=>Zn,ListChangedOptionsBaseSchema:()=>ia,ListPromptsRequestSchema:()=>Vi,ListPromptsResultSchema:()=>Ji,ListResourceTemplatesRequestSchema:()=>xi,ListResourceTemplatesResultSchema:()=>Pi,ListResourcesRequestSchema:()=>Ri,ListResourcesResultSchema:()=>wi,ListRootsRequestSchema:()=>Aa,ListRootsResultSchema:()=>qa,ListTasksRequestSchema:()=>zu,ListTasksResultSchema:()=>Ru,ListToolsRequestSchema:()=>ta,ListToolsResultSchema:()=>ra,LoggingLevelSchema:()=>Mn,LoggingMessageNotificationParamsSchema:()=>la,LoggingMessageNotificationSchema:()=>fo,ModelHintSchema:()=>ua,ModelPreferencesSchema:()=>da,MultiSelectEnumSchemaSchema:()=>va,NotificationSchema:()=>Pe,NotificationsParamsSchema:()=>Ie,NumberSchemaSchema:()=>So,PaginatedRequestParamsSchema:()=>vi,PaginatedRequestSchema:()=>rr,PaginatedResultSchema:()=>or,PingRequestSchema:()=>$n,PrimitiveSchemaDefinitionSchema:()=>Hn,ProgressNotificationParamsSchema:()=>yi,ProgressNotificationSchema:()=>Cn,ProgressSchema:()=>bi,ProgressTokenSchema:()=>yn,PromptArgumentSchema:()=>Fi,PromptListChangedNotificationSchema:()=>Xi,PromptMessageSchema:()=>Gi,PromptReferenceSchema:()=>$a,PromptSchema:()=>Hi,ReadResourceRequestParamsSchema:()=>Ti,ReadResourceRequestSchema:()=>Ei,ReadResourceResultSchema:()=>ki,RelatedTaskMetadataSchema:()=>pi,RequestIdSchema:()=>yt,RequestMetaSchema:()=>zn,RequestSchema:()=>he,ResourceContentsSchema:()=>In,ResourceLinkSchema:()=>ho,ResourceListChangedNotificationSchema:()=>$i,ResourceRequestParamsSchema:()=>co,ResourceSchema:()=>An,ResourceTemplateReferenceSchema:()=>ka,ResourceTemplateSchema:()=>zi,ResourceUpdatedNotificationParamsSchema:()=>Zi,ResourceUpdatedNotificationSchema:()=>Di,ResultMetaObjectSchema:()=>Rn,ResultSchema:()=>fe,RoleSchema:()=>nr,RootSchema:()=>Na,RootsListChangedNotificationSchema:()=>Ma,SamplingContentSchema:()=>ha,SamplingMessageContentBlockSchema:()=>Tr,SamplingMessageSchema:()=>fa,ServerCapabilitiesSchema:()=>En,ServerNotificationSchema:()=>$u,ServerRequestSchema:()=>ku,ServerResultSchema:()=>Cu,ServerTasksCapabilitySchema:()=>mu,SetLevelRequestParamsSchema:()=>aa,SetLevelRequestSchema:()=>ca,SingleSelectEnumSchemaSchema:()=>ya,StringSchemaSchema:()=>go,SubscribeRequestParamsSchema:()=>Ci,SubscribeRequestSchema:()=>Ii,SubscriptionFilterSchema:()=>qn,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Mi,SubscriptionsAcknowledgedNotificationSchema:()=>ji,SubscriptionsListenRequestParamsSchema:()=>Ai,SubscriptionsListenRequestSchema:()=>qi,SubscriptionsListenResultMetaSchema:()=>Li,SubscriptionsListenResultSchema:()=>Ui,TaskAugmentedRequestParamsSchema:()=>Er,TaskCreationParamsSchema:()=>fu,TaskMetadataSchema:()=>di,TaskSchema:()=>sr,TaskStatusNotificationParamsSchema:()=>La,TaskStatusNotificationSchema:()=>Su,TaskStatusSchema:()=>ja,TextContentSchema:()=>lo,TextResourceContentsSchema:()=>On,TitledMultiSelectEnumSchemaSchema:()=>Fn,TitledSingleSelectEnumSchemaSchema:()=>Un,ToolAnnotationsSchema:()=>Qi,ToolChoiceSchema:()=>pa,ToolExecutionSchema:()=>ea,ToolListChangedNotificationSchema:()=>sa,ToolResultContentSchema:()=>ma,ToolSchema:()=>Cr,ToolUseContentSchema:()=>Ki,UnsubscribeRequestParamsSchema:()=>Oi,UnsubscribeRequestSchema:()=>Ni,UntitledMultiSelectEnumSchemaSchema:()=>Dn,UntitledSingleSelectEnumSchemaSchema:()=>Ln});var zo=e=>wn.safeParse(e).success,Bb=e=>xn.safeParse(e).success,Yn=e=>io.safeParse(e).success,Xn=e=>ao.safeParse(e).success;var Wb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var vg=e=>Tn.safeParse(e).success,Kb=e=>kn.safeParse(e).success;var lw="Mcp-Param-",fb="x-mcp-header",uw=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,dw=new Set(["string","integer","boolean","number"]);function zg(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!="object")return;let l=s;if(fb in l){if(!a||i.length===0)return`${ju(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[fb];if(typeof d!="string"||d.length===0)return`${ju(i)}: x-mcp-header MUST be a non-empty string`;if(!uw.test(d))return`${ju(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type=="string"?l.type:void 0;if(m===void 0||!dw.has(m))return`${ju(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let h=d.toLowerCase(),g=r.get(h);if(g!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${g}')`;r.set(h,d),t.push({path:i,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u=="object")for(let[d,m]of Object.entries(u)){let h=o(m,[...i,d],a);if(h!==void 0)return h}for(let d of pw){let m=l[d];if(m===void 0)continue;let h=Array.isArray(m)?m:m!==null&&typeof m=="object"&&mw.has(d)?Object.values(m):[m];for(let g of h){let v=o(g,[...i,`<${d}>`],!1);if(v!==void 0)return v}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var pw=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],mw=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function ju(e){return e.length===0?"<root>":e.join(".")}var Gb="=?base64?",Yb="?=";function hw(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function fw(e){if(e.length===0||e.startsWith(Gb)&&e.endsWith(Yb)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(!(r===9||r>=32&&r<=126))return!0}return!1}function gw(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function Rg(e){return fw(e)?`${Gb}${gw(e)}${Yb}`:e}function Sw(e,t){let r=e;for(let o of t){if(r===null||typeof r!="object")return;r=r[o]}return r}function Xb(e,t){let r={};for(let o of e){let n=Sw(t,o.path);if(n==null)continue;let s=hw(n);s!==void 0&&(r[`${lw}${o.headerName}`]=Rg(s))}return r}var Gn=-32020,DE=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[B.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Gn,B.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[B.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[B.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[B.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Gn],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[B.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Gn],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],FE={[B.ParseError]:400,[B.InvalidRequest]:400,[B.MethodNotFound]:404,[B.UnsupportedProtocolVersion]:400,[B.MissingRequiredClientCapability]:400,[Gn]:400},gb={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Qb(e,t){let r=Object.hasOwn(gb,e)?gb[e]:void 0;if(r===void 0)return;let o=_w(t)?t[r]:void 0;return{field:r,value:typeof o=="string"?o:void 0}}function _w(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Du(e,t){return Xs(e,t)}function Va(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function ug(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var Sb=!1,dg="draft-2020-12";function bw(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:dg});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Sb||(Sb=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=ro(e,{target:dg,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:ey(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function ey(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||ey(o)))}return!1}function yw(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function ag(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>yw(o)).join(", ")}:{success:!0,data:r.value}}function vw(e){let t=ro(e,{target:dg,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var zw=/\\\.\\d\{(\d+)\}/;function Rw(e){let t=zw.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(n=>r.map(s=>it.datetime({local:o,offset:n,precision:s}))))}function ww(e,t){let r;switch(e){case"email":r=[Ul()];break;case"uri":r=[pn()];break;case"date":r=[it.date()];break;case"date-time":r=Rw(t);break}return new Set(r.map(o=>vw(o)).filter(o=>o!==void 0))}function xw(e,t,r){return r!=="zod"?!0:ww(e,t).has(t)}function Wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pw(e){try{return bw(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ie(B.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Tw=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function wg(e){return Tw.has(e)||e.startsWith("x-")}var Ew=new Set(["$schema",...Object.keys(_o.shape.requestedSchema.shape)]),_b={string:Va([go,Ln,Un,Zn]),number:Va([So]),integer:Va([So]),boolean:Va([jn]),array:Va([Dn,Fn])},kw=new Set(go.shape.format.unwrap().options);function $w(e,t,r,o){if(!Wa(e))return e;let n=typeof e.type=="string"&&Object.hasOwn(_b,e.type)?_b[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))n.has(i)||wg(i)?s[i]=a:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?kw.has(e.format)?(typeof a!="string"||!xw(e.format,a,r))&&o.push(`${t}.${i}`):s[i]=a:o.push(`${t}.${i}`);return s}function Cw(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))n==="properties"&&Wa(s)?r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,$w(a,`properties.${i}`,t,o)])):Ew.has(n)?r[n]=s:wg(n)||o.push(n);if(o.length>0)throw new ie(B.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function Iw(e,t){if(!Wa(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Du(Hn,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function pg(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,n)=>pg(o,t[n],`${r}[${n}]`)):!Wa(e)||!Wa(t)?[]:Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?pg(n,t[o],s):wg(o)?[]:[s]})}function Ow(e){if(!ug(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Cw(Pw(e.requestedSchema),t),o=Du(_o.shape.requestedSchema,r);if(!o.success)throw new ie(B.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Iw(r,o.error.message)}`);let n=pg(r,o.data);if(n.length>0)throw new ie(B.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter(i=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new ie(B.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Nw(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var HE=Object.assign(Nw,{elicit(e){try{return{method:"elicitation/create",params:Ow(e)}}catch(t){throw t instanceof ie?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var Aw=!0,qw=10,Mw=250;function ty(e){return{autoFulfill:e?.autoFulfill??Aw,maxRounds:e?.maxRounds??qw}}function jw(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;return!o&&r===void 0?e:{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function Lw(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Uw(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof q?t.reason:new q(A.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof q?t.reason:new q(A.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function Zw(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:o=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Dw(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;for(;;){if(u+=1,u>t.maxRounds)throw new q(A.InputRequiredRoundsExceeded,Lw(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let v=Zw(i);try{let w=await Promise.all(d.map(async([y,D])=>{try{return[y,await s.dispatchInputRequest(y,D,v.signal)]}catch(W){throw v.abort(W),W}}));m=Object.fromEntries(w)}finally{v.dispose()}}else await Uw(Mw,i);let h={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let v=Date.now()-a,w=n.maxTotalTimeout-v;if(w<=0)throw new q(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:v});h.maxTotalTimeout=w}let g=await s.retry(jw(o,m,l.requestState),h);if(Wb(g)){l={inputRequests:g.inputRequests??{},...g.requestState!==void 0&&{requestState:g.requestState}};continue}return g}}var Fw=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],Hw={IdJagTokenExchangeResponseSchema:Za,OAuthClientInformationFullSchema:Kn,OAuthClientInformationSchema:Fa,OAuthClientMetadataSchema:Da,OAuthClientRegistrationErrorSchema:Iu,OAuthErrorResponseSchema:Wn,OAuthMetadataSchema:bo,OAuthProtectedResourceMetadataSchema:Vn,OAuthTokenRevocationRequestSchema:Ou,OAuthTokensSchema:Bn,OpenIdProviderDiscoveryMetadataSchema:Jn,OpenIdProviderMetadataSchema:Ua},ry={},oy={};function ny(e,t){let r=e.slice(0,-6);ry[r]=t,oy[r]=o=>t.safeParse(o).success}for(let e of Fw)ny(e,cw[e]);for(let[e,t]of Object.entries(Hw))ny(e,t);var Vw=Object.freeze(ry),sy=Object.freeze(oy);function Jw(e){switch(e){case"initialize":case"notifications/initialized":return ir(void 0);case"server/discover":return ir(Zu);default:return}}var Fu=6e4,Bw=[Qt,_n,no,bn],Ww=["inputResponses","requestState"];function bb(e,t){let r=e.params;if(!Ba(r))return{message:e,lifted:{}};let o=r._meta,n=Ba(o)?Bw.filter(l=>l in o):[],s=t==="request"?Ww.filter(l=>l in r):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ba(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];i.envelope=l,Object.keys(u).length>0?a._meta=u:delete a._meta}for(let l of s)l==="inputResponses"&&(i.inputResponses=a[l]),l==="requestState"&&(i.requestState=a[l]),delete a[l];return{message:{...e,params:a},lifted:i}}function yb(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);return n.ok?{value:n.value}:{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function xg(e){return()=>e}var Kw=xg(void 0),Gw,Hu=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Gw=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??cu,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new q(A.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new q(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=n=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{o?.(n,s),Yn(n)||Xn(n)?this._onresponse(n):zo(n)?this._onrequest(n,s):Bb(n)?this._onnotification(n,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new q(A.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=bb(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=mb(t.classification);if(i!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(ig(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;n===void 0&&s===void 0||Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=bb(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(w,y,D)=>{let W={jsonrpc:"2.0",id:r.id,error:{code:w,message:y,...D!==void 0&&{data:D}}};s?.send(W).catch(N=>this._onerror(new Error(`Failed to send an error response: ${N}`)))};if(t?.classification!==void 0){let w=mb(t.classification);if(w!==n.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${n.era}`));let y=t.classification.revision??w;i(B.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(sg(r.method)&&!n.hasRequestMethod(r.method)&&!(hb(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(B.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(B.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){i(B.InvalidParams,l);return}let u=(w,y)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...y,relatedRequestId:r.id}),d=(w,y,D)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,y,{...D,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let h=o.inputResponses===void 0?void 0:Yw(o.inputResponses),g={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...h!==void 0&&{inputResponses:h.accepted},...h!==void 0&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:o.requestState===void 0?Kw:xg(o.requestState),signal:m.signal,send:((w,y,D)=>{let W=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(W,w.method),ug(y))return d(w,y,D);let N=yb(W,w.method);if(N===void 0)throw new TypeError(`'${w.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(w,N,y)}),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},v=this.buildContext(g,t);Promise.resolve().then(()=>a(r,v)).then(async w=>{if(m.signal.aborted)return;let y;try{y=n.encodeResult(r.method,w,this._outboundServerInfo())}catch(W){this._onerror(new Error(`Failed to encode result for ${r.method}: ${W}`)),i(B.InternalError,"Internal error");return}let D={result:y,jsonrpc:"2.0",id:r.id};await s?.send(D)},async w=>{if(m.signal.aborted)return;let y=Number.isSafeInteger(w.code)?w.code:B.InternalError,D={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(y),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await s?.send(D)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===m&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Yn(e)?r(e):r(ie.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(ug(t))return hb(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let n=yb(o,e.method);if(n===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return ir(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Jw(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(sg(t)&&!e.hasRequestMethod(t))throw new q(A.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,h)=>{let g=z=>{h(z)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(z){g(z);return}if(o?.signal?.aborted){let z=o.signal.reason;throw z instanceof q?z:new q(A.RequestTimeout,String(z))}let v=e.era===Zu&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;d=w;let y={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let D=this._envelopeOutbound(y),W=!1,N=z=>{W||(this._progressHandlers.delete(w),v===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(z)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`))):v.abort(),h(z instanceof q?z:new q(A.RequestTimeout,String(z))))};this._responseHandlers.set(w,z=>{if(o?.signal?.aborted)return;if(W=!0,z instanceof Error)return h(z);let Z;try{Z=e.decodeResult(t.method,z.result)}catch(te){return h(te instanceof Error?te:new Error(String(te)))}if(Z.kind==="invalid")return h(Z.error);if(Z.kind==="input_required"){if(o?.allowInputRequired===!0)return m(tx(Z));let te={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(pe,Ne)=>this._requestWithSchemaViaCodec(e,pe===void 0?{method:t.method}:{method:t.method,params:pe},r,Ne)};return m(this._resolveNonCompleteResult(Z,te))}let oe=Z.result;ag(r,oe).then(te=>{te.success?m(te.data):h(new q(A.InvalidResult,`Invalid result for ${t.method}: ${te.error}`))},h)}),u=()=>N(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let F=o?.timeout??Fu,x=()=>N(new q(A.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(w,F,o?.maxTotalTimeout,x,o?.resetTimeoutOnProgress??!1),this._transport.send(D,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:v?.signal}).catch(z=>{this._progressHandlers.delete(w),h(z)})}).finally(()=>{u&&o?.signal?.removeEventListener("abort",u),d!==void 0&&(this._responseHandlers.delete(d),this._cleanupTimeout(d))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new q(A.NotConnected,"Not connected");if(ig(t.method)&&!e.hasNotificationMethod(t.method))throw new q(A.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,r).catch(n=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!sg(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era"&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason==="not-in-era"?new ie(B.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await ag(t.params,{...n.params});if(!i.success)throw new ie(B.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!ig(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new ie(B.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let n=await ag(t.params,{...o.params});if(!n.success)throw new ie(B.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ba(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function iy(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ba(i)&&Ba(s)?{...i,...s}:s}return r}function Lu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yw(e){let t={},r=[];if(!Lu(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!Lu(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function vb(e){throw new q(A.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Xw(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:xg(void 0),signal:o,send:(()=>vb("send")),notify:()=>vb("notify")}}}async function Qw(e,t,r,o,n){if(!Lu(o)||typeof o.method!="string")throw new q(A.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new q(A.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new q(A.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=Lu(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(Xw(r,s,a,n,e.sessionId)))}function ex(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function ay(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,h)=>Qw(e,n,d,m,h),retry:(d,m)=>o.retry(d,ex(i,m))};return Dw({config:t,method:s.method,originalParams:s.params,firstPayload:l,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function tx(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var rx=nS((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw new TypeError("argument string is required");var l=typeof a=="object"?s(a):a;if(typeof l!="string")throw new TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw new TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var h,g,v;for(t.lastIndex=u;g=t.exec(l);){if(g.index!==u)throw new TypeError("invalid parameter format");u+=g[0].length,h=g[1].toLowerCase(),v=g[2],v.charCodeAt(0)===34&&(v=v.slice(1,-1),v.indexOf("\\")!==-1&&(v=v.replace(r,"$1"))),m.parameters[h]=v}if(u!==l.length)throw new TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader=="function"?l=a.getHeader("content-type"):typeof a.headers=="object"&&(l=a.headers&&a.headers["content-type"]),typeof l!="string")throw new TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}})),ox=iS(rx(),1);function cy(e){if(e)try{return ox.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var nx=10*1024*1024;function zb(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ly(e=fetch,t){return t?async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...zb(t.headers),...zb(o.headers)}:t.headers}):e}var sx=new Set([301,302,303,307,308]),ix=5;function ax(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function uy(e,t){let r=sx.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}var dy=new WeakSet;function py(e){let t=(r,o)=>e(r,o);return dy.add(t),t}function Ga(e){return dy.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=uy(n,i);if(!a||s===ix)return i;let l=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!ax(l,a))return i;await i.text?.().catch(()=>{}),n=a}}}function my(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=uy(t.url||e,t);if(r)return r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:"?(r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`):`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function Ya(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!Ya(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!Ya(e[s],t[s]))return!1;return!0}return e===t}function zt(e){return encodeURI(cx(e))}function cx(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var lx={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},ux={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},dx={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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},px=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Ro(e,t=Object.create(null),r=px,o=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",o===""?r=i:Ro(e,t,r))}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw new Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(dx[s])continue;let i=`${o}/${zt(s)}`,a=e[s];if(Array.isArray(a)){if(lx[s]){let l=a.length;for(let u=0;u<l;u++)Ro(a[u],t,r,`${i}/${u}`)}}else if(ux[s])for(let l in a)Ro(a[l],t,r,`${i}/${zt(l)}`);else Ro(a,t,r,i)}return t}var mx=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,hx=[0,31,28,31,30,31,30,31,31,30,31,30,31],fx=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,gx=/^(?=.{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,Sx=/^(?:[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,_x=/^(?:(?:[^\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,bx=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,yx=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,vx=/^(?:\/(?:[^~/]|~0|~1)*)*$/,zx=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Rx=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,wx=e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(n=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},xx=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Px=/^((([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,Tx=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Ft(e){return e.test.bind(e)}var hy={date:fy,time:gy.bind(void 0,!1),"date-time":$x,duration:Tx,uri:Ox,"uri-reference":Ft(Sx),"uri-template":Ft(_x),url:Ft(bx),email:wx,hostname:Ft(gx),ipv4:Ft(xx),ipv6:Ft(Px),regex:Ax,uuid:Ft(yx),"json-pointer":Ft(vx),"json-pointer-uri-fragment":Ft(zx),"relative-json-pointer":Ft(Rx)};function Ex(e){return e%4===0&&(e%100!==0||e%400===0)}function fy(e){let t=e.match(mx);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Ex(r)?29:hx[o])}function gy(e,t){let r=t.match(fx);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var kx=/t|\s/i;function $x(e){let t=e.split(kx);return t.length==2&&fy(t[0])&&gy(!0,t[1])}var Cx=/\/|:/,Ix=/^(?:[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 Ox(e){return Cx.test(e)&&Ix.test(e)}var Nx=/[^\\]\\Z/;function Ax(e){if(Nx.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function qx(e){let t=0,r=e.length,o=0,n;for(;o<r;)t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r&&(n=e.charCodeAt(o),(n&64512)==56320&&o++);return t}function ge(e,t,r="2019-09",o=Ro(t),n=!0,s=null,i="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":e===null?d="null":Array.isArray(e)?d="array":d="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:g,type:v,const:w,enum:y,required:D,not:W,anyOf:N,allOf:F,oneOf:x,if:z,then:Z,else:oe,format:te,properties:pe,patternProperties:Ne,additionalProperties:ae,unevaluatedProperties:de,minProperties:we,maxProperties:Ae,propertyNames:xt,dependentRequired:Je,dependentSchemas:ct,dependencies:Pt,prefixItems:Qe,items:qe,additionalItems:Vt,unevaluatedItems:Jt,contains:Tt,minContains:Ee,maxContains:Me,minItems:je,maxItems:ft,uniqueItems:jr,minimum:et,maximum:tt,exclusiveMinimum:Be,exclusiveMaximum:lt,multipleOf:ut,minLength:Et,maxLength:kt,pattern:dr,__absolute_ref__:$t,__absolute_recursive_ref__:Lr}=t,I=[];if(g===!0&&s===null&&(s=t),h==="#"){let H=s===null?o[Lr]:s,M=`${a}/$recursiveRef`,Q=ge(e,s===null?t:s,r,o,n,H,i,M,l);Q.valid||I.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...Q.errors)}if(m!==void 0){let H=o[$t||m];if(H===void 0){let O=`Unresolved $ref "${m}".`;throw $t&&$t!==m&&(O+=` Absolute URI "${$t}".`),O+=`
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function wr(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},h=c.ref;if(c.ref=null,h){o(h);let g=e.seen.get(h),y=g.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,d),a._zod.parent===h)for(let z in u)z==="$ref"||z==="allOf"||z in d||delete u[z];if(y.$ref&&g.def)for(let z in u)z==="$ref"||z==="allOf"||z in g.def&&JSON.stringify(u[z])===JSON.stringify(g.def[z])&&delete u[z]}let m=a._zod.parent;if(m&&m!==h){o(m);let g=e.seen.get(m);if(g?.schema.$ref&&(u.$ref=g.schema.$ref,g.def))for(let y in u)y==="$ref"||y==="allOf"||y in g.def&&JSON.stringify(u[y])===JSON.stringify(g.def[y])&&delete u[y]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&n.id===s&&delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:sn(t,"input",e.processors),output:sn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function De(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return De(o.element,r);if(o.type==="set")return De(o.valueType,r);if(o.type==="lazy")return De(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 De(o.innerType,r);if(o.type==="intersection")return De(o.left,r)||De(o.right,r);if(o.type==="record"||o.type==="map")return De(o.keyType,r)||De(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:De(o.in,r)||De(o.out,r);if(o.type==="object"){for(let n in o.shape)if(De(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(De(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(De(n,r))return!0;return!!(o.rest&&De(o.rest,r))}return!1}var bm=(e,t={})=>r=>{let o=vr({...r,processors:t});return ne(e,o),zr(o,e),wr(o,e)},sn=(e,t,r={})=>o=>{let{libraryOptions:n,target:s}=o??{},i=vr({...n??{},target:s,io:t,processors:r});return ne(e,i),zr(i,e),wr(i,e)};var Pw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ym=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(n.minLength=s),typeof i=="number"&&(n.maxLength=i),a&&(n.format=Pw[a]??a,n.format===""&&delete n.format,a==="time"&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},vm=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof a=="string"&&a.includes("int")?n.type="integer":n.type="number";let h=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";h?g?(n.minimum=d,n.exclusiveMinimum=!0):n.exclusiveMinimum=d:typeof s=="number"&&(n.minimum=s),m?g?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof i=="number"&&(n.maximum=i),typeof c=="number"&&(n.multipleOf=c)},zm=(e,t,r,o)=>{r.type="boolean"},wm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Rm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},xm=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Tm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Em=(e,t,r,o)=>{r.not={}},km=(e,t,r,o)=>{},$m=(e,t,r,o)=>{},Cm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Im=(e,t,r,o)=>{let n=e._zod.def,s=As(n.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Om=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.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,t.target==="draft-04"||t.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},Nm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},qm=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},Am=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:c}=e._zod.bag;i!==void 0&&(s.minLength=i),a!==void 0&&(s.maxLength=a),c?c.length===1?(s.contentMediaType=c[0],Object.assign(n,s)):(Object.assign(n,s),n.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(n,s)},Mm=(e,t,r,o)=>{r.type="boolean"},jm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Lm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Um=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Zm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Dm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Fm=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(n.minItems=i),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=ne(s.element,t,{...o,path:[...o.path,"items"]})},Hm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=ne(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return t.io==="input"?d.optin===void 0:d.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=ne(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Il=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,c)=>ne(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Vm=(e,t,r,o)=>{let n=e._zod.def,s=ne(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=ne(n.right,t,{...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},Jm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((m,g)=>ne(m,t,{...o,path:[...o.path,i,g]})),u=s.rest?ne(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(n.prefixItems=c,u&&(n.items=u)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),n.minItems=c.length,u||(n.maxItems=c.length)):(n.items=c,u&&(n.additionalItems=u));let{minimum:d,maximum:h}=e._zod.bag;typeof d=="number"&&(n.minItems=d),typeof h=="number"&&(n.maxItems=h)},Bm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=ne(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let h of c)n.patternProperties[h.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(n.propertyNames=ne(s.keyType,t,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=ne(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(h=>typeof h=="string"||typeof h=="number");d.length>0&&(n.required=d)}},Wm=(e,t,r,o)=>{let n=e._zod.def,s=ne(n.innerType,t,o),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Km=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Gm=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Ym=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},Xm=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);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},Qm=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;ne(i,t,o);let a=t.seen.get(e);a.ref=i},ef=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},tf=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Ol=(e,t,r,o)=>{let n=e._zod.def;ne(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},rf=(e,t,r,o)=>{let n=e._zod.innerType;ne(n,t,o);let s=t.seen.get(e);s.ref=n},Cl={string:ym,number:vm,boolean:zm,bigint:wm,symbol:Rm,null:xm,undefined:Pm,void:Tm,never:Em,any:km,unknown:$m,date:Cm,enum:Im,literal:Om,nan:Nm,template_literal:qm,file:Am,success:Mm,custom:jm,function:Lm,transform:Um,map:Zm,set:Dm,array:Fm,object:Hm,union:Il,intersection:Vm,tuple:Jm,record:Bm,nullable:Wm,nonoptional:Km,default:Gm,prefault:Ym,catch:Xm,pipe:Qm,readonly:ef,promise:tf,optional:Ol,lazy:rf};function to(e,t){if("_idmap"in e){let o=e,n=vr({...t,processors:Cl}),s={};for(let c of o._idmap.entries()){let[u,d]=c;ne(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let c of o._idmap.entries()){let[u,d]=c;zr(n,d),i[u]=wr(n,d)}if(Object.keys(s).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:s}}return{schemas:i}}let r=vr({...t,processors:Cl});return ne(e,r),zr(r,e),wr(r,e)}var Nl=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=vr({processors:Cl,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return ne(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),zr(this.ctx,t);let o=wr(this.ctx,t),{"~standard":n,...s}=o;return s}};var e_={};var Qs={};Jt(Qs,{ZodAny:()=>wf,ZodArray:()=>Tf,ZodBase64:()=>ru,ZodBase64URL:()=>ou,ZodBigInt:()=>mn,ZodBigIntFormat:()=>iu,ZodBoolean:()=>hn,ZodCIDRv4:()=>eu,ZodCIDRv6:()=>tu,ZodCUID:()=>Bl,ZodCUID2:()=>Wl,ZodCatch:()=>Bf,ZodCodec:()=>li,ZodCustom:()=>ui,ZodCustomStringFormat:()=>dn,ZodDate:()=>si,ZodDefault:()=>Zf,ZodDiscriminatedUnion:()=>kf,ZodE164:()=>nu,ZodEmail:()=>Fl,ZodEmoji:()=>Vl,ZodEnum:()=>cn,ZodExactOptional:()=>jf,ZodFile:()=>Af,ZodFunction:()=>rg,ZodGUID:()=>ti,ZodIPv4:()=>Xl,ZodIPv6:()=>Ql,ZodIntersection:()=>$f,ZodJWT:()=>su,ZodKSUID:()=>Yl,ZodLazy:()=>eg,ZodLiteral:()=>qf,ZodMAC:()=>bf,ZodMap:()=>Of,ZodNaN:()=>Kf,ZodNanoID:()=>Jl,ZodNever:()=>xf,ZodNonOptional:()=>du,ZodNull:()=>zf,ZodNullable:()=>Uf,ZodNumber:()=>pn,ZodNumberFormat:()=>ro,ZodObject:()=>ii,ZodOptional:()=>uu,ZodPipe:()=>ci,ZodPrefault:()=>Ff,ZodPreprocess:()=>Gf,ZodPromise:()=>tg,ZodReadonly:()=>Yf,ZodRecord:()=>an,ZodSet:()=>Nf,ZodString:()=>ln,ZodStringFormat:()=>ce,ZodSuccess:()=>Jf,ZodSymbol:()=>yf,ZodTemplateLiteral:()=>Qf,ZodTransform:()=>Mf,ZodTuple:()=>Cf,ZodType:()=>ee,ZodULID:()=>Kl,ZodURL:()=>ni,ZodUUID:()=>Nt,ZodUndefined:()=>vf,ZodUnion:()=>ai,ZodUnknown:()=>Rf,ZodVoid:()=>Pf,ZodXID:()=>Gl,ZodXor:()=>Ef,_ZodString:()=>Dl,_default:()=>Df,_function:()=>rb,any:()=>au,array:()=>_,base64:()=>v_,base64url:()=>z_,bigint:()=>O_,boolean:()=>$,catch:()=>Wf,check:()=>ob,cidrv4:()=>b_,cidrv6:()=>y_,codec:()=>X_,cuid:()=>d_,cuid2:()=>p_,custom:()=>nb,date:()=>L_,describe:()=>sb,discriminatedUnion:()=>Rr,e164:()=>w_,email:()=>Hl,emoji:()=>l_,enum:()=>K,exactOptional:()=>Lf,file:()=>W_,float32:()=>k_,float64:()=>$_,function:()=>rb,guid:()=>o_,hash:()=>E_,hex:()=>T_,hostname:()=>P_,httpUrl:()=>c_,instanceof:()=>ab,int:()=>Ul,int32:()=>C_,int64:()=>N_,intersection:()=>St,invertCodec:()=>Q_,ipv4:()=>g_,ipv6:()=>__,json:()=>lb,jwt:()=>R_,keyof:()=>U_,ksuid:()=>f_,lazy:()=>xr,literal:()=>b,looseObject:()=>Z,looseRecord:()=>H_,mac:()=>S_,map:()=>V_,meta:()=>ib,nan:()=>Y_,nanoid:()=>u_,nativeEnum:()=>B_,never:()=>cu,nonoptional:()=>Vf,null:()=>qt,nullable:()=>ri,nullish:()=>K_,number:()=>R,object:()=>f,optional:()=>L,partialRecord:()=>F_,pipe:()=>Zl,prefault:()=>Hf,preprocess:()=>Gt,promise:()=>tb,readonly:()=>Xf,record:()=>E,refine:()=>og,set:()=>J_,strictObject:()=>Z_,string:()=>l,stringFormat:()=>x_,stringbool:()=>cb,success:()=>G_,superRefine:()=>ng,symbol:()=>A_,templateLiteral:()=>eb,transform:()=>lu,tuple:()=>If,uint32:()=>I_,uint64:()=>q_,ulid:()=>h_,undefined:()=>M_,union:()=>I,unknown:()=>j,url:()=>un,uuid:()=>n_,uuidv4:()=>s_,uuidv6:()=>i_,uuidv7:()=>a_,void:()=>j_,xid:()=>m_,xor:()=>D_});var ql={};Jt(ql,{endsWith:()=>Yo,gt:()=>It,gte:()=>Ze,includes:()=>Ko,length:()=>eo,lowercase:()=>Bo,lt:()=>Ct,lte:()=>rt,maxLength:()=>Qr,maxSize:()=>yr,mime:()=>Xo,minLength:()=>Wt,minSize:()=>Ot,multipleOf:()=>br,negative:()=>Tl,nonnegative:()=>kl,nonpositive:()=>El,normalize:()=>Qo,overwrite:()=>gt,positive:()=>Pl,property:()=>$l,regex:()=>Jo,size:()=>Xr,slugify:()=>on,startsWith:()=>Go,toLowerCase:()=>tn,toUpperCase:()=>rn,trim:()=>en,uppercase:()=>Wo});var ot={};Jt(ot,{ZodISODate:()=>Ml,ZodISODateTime:()=>Al,ZodISODuration:()=>Ll,ZodISOTime:()=>jl,date:()=>nf,datetime:()=>of,duration:()=>af,time:()=>sf});var Al=S("ZodISODateTime",(e,t)=>{Np.init(e,t),ce.init(e,t)});function of(e){return jh(Al,e)}var Ml=S("ZodISODate",(e,t)=>{qp.init(e,t),ce.init(e,t)});function nf(e){return Lh(Ml,e)}var jl=S("ZodISOTime",(e,t)=>{Ap.init(e,t),ce.init(e,t)});function sf(e){return Uh(jl,e)}var Ll=S("ZodISODuration",(e,t)=>{Mp.init(e,t),ce.init(e,t)});function af(e){return Zh(Ll,e)}var t_=(e,t)=>{Zs.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Fs(e,r)},flatten:{value:r=>Ds(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,jo,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,jo,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ew=S("ZodError",t_),We=S("ZodError",t_,{Parent:Error});var cf=Zo(We),lf=Do(We),ei=Fo(We),uf=Ho(We),df=Ac(We),pf=Mc(We),hf=jc(We),mf=Lc(We),ff=Uc(We),gf=Zc(We),Sf=Dc(We),_f=Fc(We);var r_=new WeakMap;function oi(e,t,r){let o=Object.getPrototypeOf(e),n=r_.get(o);if(n||(n=new Set,r_.set(o,n)),!n.has(t)){n.add(t);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 ee=S("ZodType",(e,t)=>(Y.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:sn(e,"input"),output:sn(e,"output")}}),e.toJSONSchema=bm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>cf(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>ei(e,r,o),e.parseAsync=async(r,o)=>lf(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>uf(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>df(e,r,o),e.decode=(r,o)=>pf(e,r,o),e.encodeAsync=async(r,o)=>hf(e,r,o),e.decodeAsync=async(r,o)=>mf(e,r,o),e.safeEncode=(r,o)=>ff(e,r,o),e.safeDecode=(r,o)=>gf(e,r,o),e.safeEncodeAsync=async(r,o)=>Sf(e,r,o),e.safeDecodeAsync=async(r,o)=>_f(e,r,o),oi(e,"ZodType",{check(...r){let o=this.def;return this.clone(G.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 Le(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(og(r,o))},superRefine(r,o){return this.check(ng(r,o))},overwrite(r){return this.check(gt(r))},optional(){return L(this)},exactOptional(){return Lf(this)},nullable(){return ri(this)},nullish(){return L(ri(this))},nonoptional(r){return Vf(this,r)},array(){return _(this)},or(r){return I([this,r])},and(r){return St(this,r)},transform(r){return Zl(this,lu(r))},default(r){return Df(this,r)},prefault(r){return Hf(this,r)},catch(r){return Wf(this,r)},pipe(r){return Zl(this,r)},readonly(){return Xf(this)},describe(r){let o=this.clone();return Pe.add(o,{description:r}),o},meta(...r){if(r.length===0)return Pe.get(this);let o=this.clone();return Pe.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(e,"description",{get(){return Pe.get(e)?.description},configurable:!0}),e)),Dl=S("_ZodString",(e,t)=>{Yr.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>ym(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,oi(e,"_ZodString",{regex(...o){return this.check(Jo(...o))},includes(...o){return this.check(Ko(...o))},startsWith(...o){return this.check(Go(...o))},endsWith(...o){return this.check(Yo(...o))},min(...o){return this.check(Wt(...o))},max(...o){return this.check(Qr(...o))},length(...o){return this.check(eo(...o))},nonempty(...o){return this.check(Wt(1,...o))},lowercase(o){return this.check(Bo(o))},uppercase(o){return this.check(Wo(o))},trim(){return this.check(en())},normalize(...o){return this.check(Qo(...o))},toLowerCase(){return this.check(tn())},toUpperCase(){return this.check(rn())},slugify(){return this.check(on())}})}),ln=S("ZodString",(e,t)=>{Yr.init(e,t),Dl.init(e,t),e.email=r=>e.check(il(Fl,r)),e.url=r=>e.check(Xs(ni,r)),e.jwt=r=>e.check(xl(su,r)),e.emoji=r=>e.check(dl(Vl,r)),e.guid=r=>e.check(Ys(ti,r)),e.uuid=r=>e.check(al(Nt,r)),e.uuidv4=r=>e.check(cl(Nt,r)),e.uuidv6=r=>e.check(ll(Nt,r)),e.uuidv7=r=>e.check(ul(Nt,r)),e.nanoid=r=>e.check(pl(Jl,r)),e.guid=r=>e.check(Ys(ti,r)),e.cuid=r=>e.check(hl(Bl,r)),e.cuid2=r=>e.check(ml(Wl,r)),e.ulid=r=>e.check(fl(Kl,r)),e.base64=r=>e.check(zl(ru,r)),e.base64url=r=>e.check(wl(ou,r)),e.xid=r=>e.check(gl(Gl,r)),e.ksuid=r=>e.check(Sl(Yl,r)),e.ipv4=r=>e.check(_l(Xl,r)),e.ipv6=r=>e.check(bl(Ql,r)),e.cidrv4=r=>e.check(yl(eu,r)),e.cidrv6=r=>e.check(vl(tu,r)),e.e164=r=>e.check(Rl(nu,r)),e.datetime=r=>e.check(of(r)),e.date=r=>e.check(nf(r)),e.time=r=>e.check(sf(r)),e.duration=r=>e.check(af(r))});function l(e){return Nh(ln,e)}var ce=S("ZodStringFormat",(e,t)=>{ae.init(e,t),Dl.init(e,t)}),Fl=S("ZodEmail",(e,t)=>{xp.init(e,t),ce.init(e,t)});function Hl(e){return il(Fl,e)}var ti=S("ZodGUID",(e,t)=>{wp.init(e,t),ce.init(e,t)});function o_(e){return Ys(ti,e)}var Nt=S("ZodUUID",(e,t)=>{Rp.init(e,t),ce.init(e,t)});function n_(e){return al(Nt,e)}function s_(e){return cl(Nt,e)}function i_(e){return ll(Nt,e)}function a_(e){return ul(Nt,e)}var ni=S("ZodURL",(e,t)=>{Pp.init(e,t),ce.init(e,t)});function un(e){return Xs(ni,e)}function c_(e){return Xs(ni,{protocol:tt.httpProtocol,hostname:tt.domain,...G.normalizeParams(e)})}var Vl=S("ZodEmoji",(e,t)=>{Tp.init(e,t),ce.init(e,t)});function l_(e){return dl(Vl,e)}var Jl=S("ZodNanoID",(e,t)=>{Ep.init(e,t),ce.init(e,t)});function u_(e){return pl(Jl,e)}var Bl=S("ZodCUID",(e,t)=>{kp.init(e,t),ce.init(e,t)});function d_(e){return hl(Bl,e)}var Wl=S("ZodCUID2",(e,t)=>{$p.init(e,t),ce.init(e,t)});function p_(e){return ml(Wl,e)}var Kl=S("ZodULID",(e,t)=>{Cp.init(e,t),ce.init(e,t)});function h_(e){return fl(Kl,e)}var Gl=S("ZodXID",(e,t)=>{Ip.init(e,t),ce.init(e,t)});function m_(e){return gl(Gl,e)}var Yl=S("ZodKSUID",(e,t)=>{Op.init(e,t),ce.init(e,t)});function f_(e){return Sl(Yl,e)}var Xl=S("ZodIPv4",(e,t)=>{jp.init(e,t),ce.init(e,t)});function g_(e){return _l(Xl,e)}var bf=S("ZodMAC",(e,t)=>{Up.init(e,t),ce.init(e,t)});function S_(e){return Ah(bf,e)}var Ql=S("ZodIPv6",(e,t)=>{Lp.init(e,t),ce.init(e,t)});function __(e){return bl(Ql,e)}var eu=S("ZodCIDRv4",(e,t)=>{Zp.init(e,t),ce.init(e,t)});function b_(e){return yl(eu,e)}var tu=S("ZodCIDRv6",(e,t)=>{Dp.init(e,t),ce.init(e,t)});function y_(e){return vl(tu,e)}var ru=S("ZodBase64",(e,t)=>{Hp.init(e,t),ce.init(e,t)});function v_(e){return zl(ru,e)}var ou=S("ZodBase64URL",(e,t)=>{Vp.init(e,t),ce.init(e,t)});function z_(e){return wl(ou,e)}var nu=S("ZodE164",(e,t)=>{Jp.init(e,t),ce.init(e,t)});function w_(e){return Rl(nu,e)}var su=S("ZodJWT",(e,t)=>{Bp.init(e,t),ce.init(e,t)});function R_(e){return xl(su,e)}var dn=S("ZodCustomStringFormat",(e,t)=>{Wp.init(e,t),ce.init(e,t)});function x_(e,t,r={}){return nn(dn,e,t,r)}function P_(e){return nn(dn,"hostname",tt.hostname,e)}function T_(e){return nn(dn,"hex",tt.hex,e)}function E_(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=tt[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return nn(dn,o,n,t)}var pn=S("ZodNumber",(e,t)=>{Xc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>vm(e,o,n,s),oi(e,"ZodNumber",{gt(o,n){return this.check(It(o,n))},gte(o,n){return this.check(Ze(o,n))},min(o,n){return this.check(Ze(o,n))},lt(o,n){return this.check(Ct(o,n))},lte(o,n){return this.check(rt(o,n))},max(o,n){return this.check(rt(o,n))},int(o){return this.check(Ul(o))},safe(o){return this.check(Ul(o))},positive(o){return this.check(It(0,o))},nonnegative(o){return this.check(Ze(0,o))},negative(o){return this.check(Ct(0,o))},nonpositive(o){return this.check(rt(0,o))},multipleOf(o,n){return this.check(br(o,n))},step(o,n){return this.check(br(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function R(e){return Dh(pn,e)}var ro=S("ZodNumberFormat",(e,t)=>{Kp.init(e,t),pn.init(e,t)});function Ul(e){return Hh(ro,e)}function k_(e){return Vh(ro,e)}function $_(e){return Jh(ro,e)}function C_(e){return Bh(ro,e)}function I_(e){return Wh(ro,e)}var hn=S("ZodBoolean",(e,t)=>{Bs.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zm(e,r,o,n)});function $(e){return Kh(hn,e)}var mn=S("ZodBigInt",(e,t)=>{Qc.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>wm(e,o,n,s),e.gte=(o,n)=>e.check(Ze(o,n)),e.min=(o,n)=>e.check(Ze(o,n)),e.gt=(o,n)=>e.check(It(o,n)),e.gte=(o,n)=>e.check(Ze(o,n)),e.min=(o,n)=>e.check(Ze(o,n)),e.lt=(o,n)=>e.check(Ct(o,n)),e.lte=(o,n)=>e.check(rt(o,n)),e.max=(o,n)=>e.check(rt(o,n)),e.positive=o=>e.check(It(BigInt(0),o)),e.negative=o=>e.check(Ct(BigInt(0),o)),e.nonpositive=o=>e.check(rt(BigInt(0),o)),e.nonnegative=o=>e.check(Ze(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(br(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function O_(e){return Yh(mn,e)}var iu=S("ZodBigIntFormat",(e,t)=>{Gp.init(e,t),mn.init(e,t)});function N_(e){return Qh(iu,e)}function q_(e){return em(iu,e)}var yf=S("ZodSymbol",(e,t)=>{Yp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rm(e,r,o,n)});function A_(e){return tm(yf,e)}var vf=S("ZodUndefined",(e,t)=>{Xp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pm(e,r,o,n)});function M_(e){return rm(vf,e)}var zf=S("ZodNull",(e,t)=>{Qp.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xm(e,r,o,n)});function qt(e){return om(zf,e)}var wf=S("ZodAny",(e,t)=>{eh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>km(e,r,o,n)});function au(){return nm(wf)}var Rf=S("ZodUnknown",(e,t)=>{th.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$m(e,r,o,n)});function j(){return sm(Rf)}var xf=S("ZodNever",(e,t)=>{rh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Em(e,r,o,n)});function cu(e){return im(xf,e)}var Pf=S("ZodVoid",(e,t)=>{oh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tm(e,r,o,n)});function j_(e){return am(Pf,e)}var si=S("ZodDate",(e,t)=>{nh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Cm(e,o,n,s),e.min=(o,n)=>e.check(Ze(o,n)),e.max=(o,n)=>e.check(rt(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function L_(e){return cm(si,e)}var Tf=S("ZodArray",(e,t)=>{sh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fm(e,r,o,n),e.element=t.element,oi(e,"ZodArray",{min(r,o){return this.check(Wt(r,o))},nonempty(r){return this.check(Wt(1,r))},max(r,o){return this.check(Qr(r,o))},length(r,o){return this.check(eo(r,o))},unwrap(){return this.element}})});function _(e,t){return dm(Tf,e,t)}function U_(e){let t=e._zod.def.shape;return K(Object.keys(t))}var ii=S("ZodObject",(e,t)=>{ih.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hm(e,r,o,n),G.defineLazy(e,"shape",()=>t.shape),oi(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:j()})},loose(){return this.clone({...this._zod.def,catchall:j()})},strict(){return this.clone({...this._zod.def,catchall:cu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return G.extend(this,r)},safeExtend(r){return G.safeExtend(this,r)},merge(r){return G.merge(this,r)},pick(r){return G.pick(this,r)},omit(r){return G.omit(this,r)},partial(...r){return G.partial(uu,this,r[0])},required(...r){return G.required(du,this,r[0])}})});function f(e,t){let r={type:"object",shape:e??{},...G.normalizeParams(t)};return new ii(r)}function Z_(e,t){return new ii({type:"object",shape:e,catchall:cu(),...G.normalizeParams(t)})}function Z(e,t){return new ii({type:"object",shape:e,catchall:j(),...G.normalizeParams(t)})}var ai=S("ZodUnion",(e,t)=>{Ws.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.options=t.options});function I(e,t){return new ai({type:"union",options:e,...G.normalizeParams(t)})}var Ef=S("ZodXor",(e,t)=>{ai.init(e,t),ah.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.options=t.options});function D_(e,t){return new Ef({type:"union",options:e,inclusive:!1,...G.normalizeParams(t)})}var kf=S("ZodDiscriminatedUnion",(e,t)=>{ai.init(e,t),ch.init(e,t)});function Rr(e,t,r){return new kf({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}var $f=S("ZodIntersection",(e,t)=>{lh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vm(e,r,o,n)});function St(e,t){return new $f({type:"intersection",left:e,right:t})}var Cf=S("ZodTuple",(e,t)=>{el.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jm(e,r,o,n),e.rest=r=>e.clone({...e._zod.def,rest:r})});function If(e,t,r){let o=t instanceof Y,n=o?r:t,s=o?t:null;return new Cf({type:"tuple",items:e,rest:s,...G.normalizeParams(n)})}var an=S("ZodRecord",(e,t)=>{uh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bm(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function E(e,t,r){return!t||!t._zod?new an({type:"record",keyType:l(),valueType:e,...G.normalizeParams(t)}):new an({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}function F_(e,t,r){let o=Le(e);return o._zod.values=void 0,new an({type:"record",keyType:o,valueType:t,...G.normalizeParams(r)})}function H_(e,t,r){return new an({type:"record",keyType:e,valueType:t,mode:"loose",...G.normalizeParams(r)})}var Of=S("ZodMap",(e,t)=>{dh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zm(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ot(...r)),e.nonempty=r=>e.check(Ot(1,r)),e.max=(...r)=>e.check(yr(...r)),e.size=(...r)=>e.check(Xr(...r))});function V_(e,t,r){return new Of({type:"map",keyType:e,valueType:t,...G.normalizeParams(r)})}var Nf=S("ZodSet",(e,t)=>{ph.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dm(e,r,o,n),e.min=(...r)=>e.check(Ot(...r)),e.nonempty=r=>e.check(Ot(1,r)),e.max=(...r)=>e.check(yr(...r)),e.size=(...r)=>e.check(Xr(...r))});function J_(e,t){return new Nf({type:"set",valueType:e,...G.normalizeParams(t)})}var cn=S("ZodEnum",(e,t)=>{hh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Im(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new cn({...t,checks:[],...G.normalizeParams(n),entries:s})},e.exclude=(o,n)=>{let s={...t.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 cn({...t,checks:[],...G.normalizeParams(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new cn({type:"enum",entries:r,...G.normalizeParams(t)})}function B_(e,t){return new cn({type:"enum",entries:e,...G.normalizeParams(t)})}var qf=S("ZodLiteral",(e,t)=>{mh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Om(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function b(e,t){return new qf({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}var Af=S("ZodFile",(e,t)=>{fh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Am(e,r,o,n),e.min=(r,o)=>e.check(Ot(r,o)),e.max=(r,o)=>e.check(yr(r,o)),e.mime=(r,o)=>e.check(Xo(Array.isArray(r)?r:[r],o))});function W_(e){return pm(Af,e)}var Mf=S("ZodTransform",(e,t)=>{gh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Um(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new mr(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(G.issue(i))}};let n=t.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 lu(e){return new Mf({type:"transform",transform:e})}var uu=S("ZodOptional",(e,t)=>{tl.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function L(e){return new uu({type:"optional",innerType:e})}var jf=S("ZodExactOptional",(e,t)=>{Sh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Lf(e){return new jf({type:"optional",innerType:e})}var Uf=S("ZodNullable",(e,t)=>{_h.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wm(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ri(e){return new Uf({type:"nullable",innerType:e})}function K_(e){return L(ri(e))}var Zf=S("ZodDefault",(e,t)=>{bh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gm(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Df(e,t){return new Zf({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}var Ff=S("ZodPrefault",(e,t)=>{yh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ym(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Hf(e,t){return new Ff({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}var du=S("ZodNonOptional",(e,t)=>{vh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Km(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Vf(e,t){return new du({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}var Jf=S("ZodSuccess",(e,t)=>{zh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Mm(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function G_(e){return new Jf({type:"success",innerType:e})}var Bf=S("ZodCatch",(e,t)=>{wh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xm(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wf(e,t){return new Bf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Kf=S("ZodNaN",(e,t)=>{Rh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nm(e,r,o,n)});function Y_(e){return um(Kf,e)}var ci=S("ZodPipe",(e,t)=>{rl.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Qm(e,r,o,n),e.in=t.in,e.out=t.out});function Zl(e,t){return new ci({type:"pipe",in:e,out:t})}var li=S("ZodCodec",(e,t)=>{ci.init(e,t),Ks.init(e,t)});function X_(e,t,r){return new li({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function Q_(e){let t=e._zod.def;return new li({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var Gf=S("ZodPreprocess",(e,t)=>{ci.init(e,t),xh.init(e,t)}),Yf=S("ZodReadonly",(e,t)=>{Ph.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ef(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Xf(e){return new Yf({type:"readonly",innerType:e})}var Qf=S("ZodTemplateLiteral",(e,t)=>{Th.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qm(e,r,o,n)});function eb(e,t){return new Qf({type:"template_literal",parts:e,...G.normalizeParams(t)})}var eg=S("ZodLazy",(e,t)=>{$h.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rf(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function xr(e){return new eg({type:"lazy",getter:e})}var tg=S("ZodPromise",(e,t)=>{kh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>tf(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tb(e){return new tg({type:"promise",innerType:e})}var rg=S("ZodFunction",(e,t)=>{Eh.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Lm(e,r,o,n)});function rb(e){return new rg({type:"function",input:Array.isArray(e?.input)?If(e?.input):e?.input??_(j()),output:e?.output??j()})}var ui=S("ZodCustom",(e,t)=>{Ch.init(e,t),ee.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jm(e,r,o,n)});function ob(e){let t=new le({check:"custom"});return t._zod.check=e,t}function nb(e,t){return hm(ui,e??(()=>!0),t)}function og(e,t={}){return mm(ui,e,t)}function ng(e,t){return fm(e,t)}var sb=gm,ib=Sm;function ab(e,t={}){let r=new ui({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...G.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var cb=(...e)=>_m({Codec:li,Boolean:hn,String:ln},...e);function lb(e){let t=xr(()=>I([l(e),R(),$(),qt(),_(t),E(l(),t)]));return t}function Gt(e,t){return new Gf({type:"pipe",in:lu(e),out:t})}var ig={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function $w(e){ge({customError:e})}function Cw(){return ge().customError}var sg;sg||(sg={});var C={...Qs,...ql,iso:ot},Iw=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Ow(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function Nw(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1];if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function ub(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return C.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return C.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let s=Nw(n,t),i=Ce(s,t);return t.refs.set(n,i),t.processing.delete(n),i}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return C.null();if(n.length===0)return C.never();if(n.length===1)return C.literal(n[0]);if(n.every(i=>typeof i=="string"))return C.enum(n);let s=n.map(i=>C.literal(i));return s.length<2?s[0]:C.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return C.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(s=>{let i={...e,type:s};return ub(i,t)});return n.length===0?C.never():n.length===1?n[0]:C.union(n)}if(!r)return C.any();let o;switch(r){case"string":{let n=C.string();if(e.format){let s=e.format;s==="email"?n=n.check(C.email()):s==="uri"||s==="uri-reference"?n=n.check(C.url()):s==="uuid"||s==="guid"?n=n.check(C.uuid()):s==="date-time"?n=n.check(C.iso.datetime()):s==="date"?n=n.check(C.iso.date()):s==="time"?n=n.check(C.iso.time()):s==="duration"?n=n.check(C.iso.duration()):s==="ipv4"?n=n.check(C.ipv4()):s==="ipv6"?n=n.check(C.ipv6()):s==="mac"?n=n.check(C.mac()):s==="cidr"?n=n.check(C.cidrv4()):s==="cidr-v6"?n=n.check(C.cidrv6()):s==="base64"?n=n.check(C.base64()):s==="base64url"?n=n.check(C.base64url()):s==="e164"?n=n.check(C.e164()):s==="jwt"?n=n.check(C.jwt()):s==="emoji"?n=n.check(C.emoji()):s==="nanoid"?n=n.check(C.nanoid()):s==="cuid"?n=n.check(C.cuid()):s==="cuid2"?n=n.check(C.cuid2()):s==="ulid"?n=n.check(C.ulid()):s==="xid"?n=n.check(C.xid()):s==="ksuid"&&(n=n.check(C.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?C.number().int():C.number();typeof e.minimum=="number"&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=C.boolean();break}case"null":{o=C.null();break}case"object":{let n={},s=e.properties||{},i=new Set(e.required||[]);for(let[c,u]of Object.entries(s)){let d=Ce(u,t);n[c]=i.has(c)?d:d.optional()}if(e.propertyNames){let c=Ce(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties=="object"?Ce(e.additionalProperties,t):C.any();if(Object.keys(n).length===0){o=C.record(c,u);break}let d=C.object(n).passthrough(),h=C.looseRecord(c,u);o=C.intersection(d,h);break}if(e.patternProperties){let c=e.patternProperties,u=Object.keys(c),d=[];for(let m of u){let g=Ce(c[m],t),y=C.string().regex(new RegExp(m));d.push(C.looseRecord(y,g))}let h=[];if(Object.keys(n).length>0&&h.push(C.object(n).passthrough()),h.push(...d),h.length===0)o=C.object({}).passthrough();else if(h.length===1)o=h[0];else{let m=C.intersection(h[0],h[1]);for(let g=2;g<h.length;g++)m=C.intersection(m,h[g]);o=m}break}let a=C.object(n);e.additionalProperties===!1?o=a.strict():typeof e.additionalProperties=="object"?o=a.catchall(Ce(e.additionalProperties,t)):o=a.passthrough();break}case"array":{let n=e.prefixItems,s=e.items;if(n&&Array.isArray(n)){let i=n.map(c=>Ce(c,t)),a=s&&typeof s=="object"&&!Array.isArray(s)?Ce(s,t):void 0;a?o=C.tuple(i).rest(a):o=C.tuple(i),typeof e.minItems=="number"&&(o=o.check(C.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(C.maxLength(e.maxItems)))}else if(Array.isArray(s)){let i=s.map(c=>Ce(c,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Ce(e.additionalItems,t):void 0;a?o=C.tuple(i).rest(a):o=C.tuple(i),typeof e.minItems=="number"&&(o=o.check(C.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(C.maxLength(e.maxItems)))}else if(s!==void 0){let i=Ce(s,t),a=C.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),o=a}else o=C.array(C.any());break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Ce(e,t){if(typeof e=="boolean")return e?C.any():C.never();let r=ub(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Ce(u,t)),c=C.union(a);r=o?C.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Ce(u,t)),c=C.xor(a);r=o?C.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:C.any();else{let a=o?r:Ce(e.allOf[0],t),c=o?0:1;for(let u=c;u<e.allOf.length;u++)a=C.intersection(a,Ce(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=C.nullable(r)),e.readOnly===!0&&(r=C.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of s)a in e&&(n[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(n[a]=e[a]);for(let a of Object.keys(e))Iw.has(a)||(n[a]=e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function db(e,t){if(typeof e=="boolean")return e?C.any():C.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=Ow(r,t?.defaultTarget),n=r.$defs||r.definitions||{},s={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??Pe};return Ce(r,s)}var di={};Jt(di,{bigint:()=>jw,boolean:()=>Mw,date:()=>Lw,number:()=>Aw,string:()=>qw});function qw(e){return qh(ln,e)}function Aw(e){return Fh(pn,e)}function Mw(e){return Gh(hn,e)}function jw(e){return Xh(mn,e)}function Lw(e){return lm(si,e)}ge(ol());var fn="2025-11-25";var pu=[fn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],hu="io.modelcontextprotocol/related-task",Xt="io.modelcontextprotocol/protocolVersion",gn="io.modelcontextprotocol/clientInfo",Qt="io.modelcontextprotocol/serverInfo",oo="io.modelcontextprotocol/clientCapabilities",pi="io.modelcontextprotocol/subscriptionId",Sn="io.modelcontextprotocol/logLevel";var no="2.0";var Yt=xr(()=>I([l(),R(),$(),qt(),E(l(),Yt),_(Yt)])),pe=E(l(),Yt),mu=_(Yt),_n=I([l(),R().int()]),bn=l(),hi=f({ttl:R().optional()}),mi=f({taskId:l()}),yn=Z({progressToken:_n.optional(),[hu]:mi.optional()}),Re=f({_meta:yn.optional()}),Tr=Re.extend({task:hi.optional()}),he=f({method:l(),params:Re.loose().optional()}),Ie=f({_meta:yn.optional()}),Te=f({method:l(),params:Ie.loose().optional()}),vn=Z({get[Qt](){return Mt.optional().catch(void 0)}}),me=Z({_meta:vn.optional()}),_t=I([l(),R().int()]),zn=f({jsonrpc:b(no),id:_t,...he.shape}).strict(),wn=f({jsonrpc:b(no),...Te.shape}).strict(),so=f({jsonrpc:b(no),id:_t,result:me}).strict(),io=f({jsonrpc:b(no),id:_t.optional(),error:f({code:R().int(),message:l(),data:j().optional()})}).strict(),bt=I([zn,wn,so,io]),fu=I([so,io]),Er=me.strict(),fi=Ie.extend({requestId:_t.optional(),reason:l().optional()}),Rn=Te.extend({method:b("notifications/cancelled"),params:fi}),gi=f({src:l(),mimeType:l().optional(),sizes:_(l()).optional(),theme:K(["light","dark"]).optional()}),er=f({icons:_(gi).optional()}),At=f({name:l(),title:l().optional()}),Mt=At.extend({...At.shape,...er.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),Zw=St(f({applyDefaults:$().optional()}),pe),Dw=Gt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,St(f({form:Zw.optional(),url:pe.optional()}),pe.optional())),gu=Z({list:pe.optional(),cancel:pe.optional(),requests:Z({sampling:Z({createMessage:pe.optional()}).optional(),elicitation:Z({create:pe.optional()}).optional()}).optional()}),Su=Z({list:pe.optional(),cancel:pe.optional(),requests:Z({tools:Z({call:pe.optional()}).optional()}).optional()}),Si=f({experimental:E(l(),pe).optional(),sampling:f({context:pe.optional(),tools:pe.optional()}).optional(),elicitation:Dw.optional(),roots:f({listChanged:$().optional()}).optional(),tasks:gu.optional(),extensions:E(l(),pe).optional()}),_i=Re.extend({protocolVersion:l(),capabilities:Si,clientInfo:Mt}),xn=he.extend({method:b("initialize"),params:_i}),Pn=f({experimental:E(l(),pe).optional(),logging:pe.optional(),completions:pe.optional(),prompts:f({listChanged:$().optional()}).optional(),resources:f({subscribe:$().optional(),listChanged:$().optional()}).optional(),tools:f({listChanged:$().optional()}).optional(),tasks:Su.optional(),extensions:E(l(),pe).optional()}),bi=me.extend({protocolVersion:l(),capabilities:Pn,serverInfo:Mt,instructions:l().optional()}),Tn=Te.extend({method:b("notifications/initialized"),params:Ie.optional()}),yi=he.extend({method:b("server/discover"),params:Re.optional()}),kr=me.extend({supportedVersions:_(l()),capabilities:Pn,instructions:l().optional()}),En=he.extend({method:b("ping"),params:Re.optional()}),vi=f({progress:R(),total:L(R()),message:L(l())}),zi=f({...Ie.shape,...vi.shape,progressToken:_n}),kn=Te.extend({method:b("notifications/progress"),params:zi}),wi=Re.extend({cursor:bn.optional()}),tr=he.extend({params:wi.optional()}),rr=me.extend({nextCursor:bn.optional()}),$n=f({uri:l(),mimeType:L(l()),_meta:E(l(),j()).optional()}),Cn=$n.extend({text:l()}),cg=l().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),In=$n.extend({blob:cg}),or=K(["user","assistant"]),jt=f({audience:_(or).optional(),priority:R().min(0).max(1).optional(),lastModified:ot.datetime({offset:!0}).optional()}),On=f({...At.shape,...er.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(R()),annotations:jt.optional(),_meta:L(Z({}))}),Ri=f({...At.shape,...er.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:jt.optional(),_meta:L(Z({}))}),xi=tr.extend({method:b("resources/list")}),Pi=rr.extend({resources:_(On)}),Ti=tr.extend({method:b("resources/templates/list")}),Ei=rr.extend({resourceTemplates:_(Ri)}),ao=Re.extend({uri:l()}),ki=ao,$i=he.extend({method:b("resources/read"),params:ki}),Ci=me.extend({contents:_(I([Cn,In]))}),Ii=Te.extend({method:b("notifications/resources/list_changed"),params:Ie.optional()}),Oi=ao,Ni=he.extend({method:b("resources/subscribe"),params:Oi}),qi=ao,Ai=he.extend({method:b("resources/unsubscribe"),params:qi}),Nn=f({toolsListChanged:$().optional(),promptsListChanged:$().optional(),resourcesListChanged:$().optional(),resourceSubscriptions:_(l()).optional()}),Mi=Re.extend({notifications:Nn}),ji=he.extend({method:b("subscriptions/listen"),params:Mi}),Li=Ie.extend({notifications:Nn}),Ui=Te.extend({method:b("notifications/subscriptions/acknowledged"),params:Li}),Zi=vn.extend({[pi]:_t}),Di=me.extend({_meta:Zi}),Fi=Ie.extend({uri:l()}),Hi=Te.extend({method:b("notifications/resources/updated"),params:Fi}),Vi=f({name:l(),description:L(l()),required:L($())}),Ji=f({...At.shape,...er.shape,description:L(l()),arguments:L(_(Vi)),_meta:L(Z({}))}),Bi=tr.extend({method:b("prompts/list")}),Wi=rr.extend({prompts:_(Ji)}),Ki=Re.extend({name:l(),arguments:E(l(),l()).optional()}),Gi=he.extend({method:b("prompts/get"),params:Ki}),co=f({type:b("text"),text:l(),annotations:jt.optional(),_meta:E(l(),j()).optional()}),lo=f({type:b("image"),data:cg,mimeType:l(),annotations:jt.optional(),_meta:E(l(),j()).optional()}),uo=f({type:b("audio"),data:cg,mimeType:l(),annotations:jt.optional(),_meta:E(l(),j()).optional()}),Yi=f({type:b("tool_use"),name:l(),id:l(),input:E(l(),j()),_meta:E(l(),j()).optional()}),po=f({type:b("resource"),resource:I([Cn,In]),annotations:jt.optional(),_meta:E(l(),j()).optional()}),ho=On.extend({type:b("resource_link")}),Lt=I([co,lo,uo,ho,po]),Xi=f({role:or,content:Lt}),Qi=me.extend({description:l().optional(),messages:_(Xi)}),ea=Te.extend({method:b("notifications/prompts/list_changed"),params:Ie.optional()}),ta=f({title:l().optional(),readOnlyHint:$().optional(),destructiveHint:$().optional(),idempotentHint:$().optional(),openWorldHint:$().optional()}),ra=f({taskSupport:K(["required","optional","forbidden"]).optional()}),$r=f({...At.shape,...er.shape,description:l().optional(),inputSchema:f({type:b("object"),properties:E(l(),Yt).optional(),required:_(l()).optional()}).catchall(j()),outputSchema:Z({$schema:l().optional()}).optional(),annotations:ta.optional(),execution:ra.optional(),_meta:E(l(),j()).optional()}),oa=tr.extend({method:b("tools/list")}),na=rr.extend({tools:_($r)}),Cr=me.extend({content:_(Lt).default([]),structuredContent:j().optional(),isError:$().optional()}),_u=Cr.or(me.extend({toolResult:j()})),sa=Tr.extend({name:l(),arguments:E(l(),j()).optional()}),ia=he.extend({method:b("tools/call"),params:sa}),aa=Te.extend({method:b("notifications/tools/list_changed"),params:Ie.optional()}),ca=f({autoRefresh:$().default(!0),debounceMs:R().int().nonnegative().default(300)}),qn=K(["debug","info","notice","warning","error","critical","alert","emergency"]),la=Re.extend({level:qn}),ua=he.extend({method:b("logging/setLevel"),params:la}),da=Ie.extend({level:qn,logger:l().optional(),data:j()}),mo=Te.extend({method:b("notifications/message"),params:da}),pa=f({name:l().optional()}),ha=f({hints:_(pa).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),ma=f({mode:K(["auto","required","none"]).optional()}),fa=f({type:b("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:_(Lt),structuredContent:j().optional(),isError:$().optional(),_meta:E(l(),j()).optional()}),ga=Rr("type",[co,lo,uo]),Pr=Rr("type",[co,lo,uo,Yi,fa]),Sa=f({role:or,content:I([Pr,_(Pr)]),_meta:E(l(),j()).optional()}),_a=Tr.extend({messages:_(Sa),modelPreferences:ha.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(l()).optional(),metadata:pe.optional(),tools:_($r).optional(),toolChoice:ma.optional()}),ba=he.extend({method:b("sampling/createMessage"),params:_a}),ya=me.extend({model:l(),stopReason:L(K(["endTurn","stopSequence","maxTokens"]).or(l())),role:or,content:ga}),va=me.extend({model:l(),stopReason:L(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:or,content:I([Pr,_(Pr)])}),An=f({type:b("boolean"),title:l().optional(),description:l().optional(),default:$().optional()}),fo=f({type:b("string"),title:l().optional(),description:l().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),go=f({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),Mn=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),default:l().optional()}),jn=f({type:b("string"),title:l().optional(),description:l().optional(),oneOf:_(f({const:l(),title:l()})),default:l().optional()}),Ln=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),enumNames:_(l()).optional(),default:l().optional()}),za=I([Mn,jn]),Un=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(l())}),default:_(l()).optional()}),Zn=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:l(),title:l()}))}),default:_(l()).optional()}),wa=I([Un,Zn]),Ra=I([Ln,za,wa]),Dn=I([Ra,An,fo,go]),So=Tr.extend({mode:b("form").optional(),message:l(),requestedSchema:f({type:b("object"),properties:E(l(),Dn),required:_(l()).optional()}).catchall(j())}),xa=Tr.extend({mode:b("url"),message:l(),elicitationId:l(),url:l().url()}),Pa=I([So,xa]),Ta=he.extend({method:b("elicitation/create"),params:Pa}),Ea=Ie.extend({elicitationId:l()}),ka=Te.extend({method:b("notifications/elicitation/complete"),params:Ea}),$a=me.extend({action:K(["accept","decline","cancel"]),content:Gt(e=>e===null?void 0:e,E(l(),I([l(),R(),$(),_(l())])).optional())}),Ca=f({type:b("ref/resource"),uri:l()}),Ia=f({type:b("ref/prompt"),name:l()}),Oa=Re.extend({ref:I([Ia,Ca]),argument:f({name:l(),value:l()}),context:f({arguments:E(l(),l()).optional()}).optional()}),Na=he.extend({method:b("completion/complete"),params:Oa}),qa=me.extend({completion:Z({values:_(l()).max(100),total:L(R().int()),hasMore:L($())})}),Aa=f({uri:l().startsWith("file://"),name:l().optional(),_meta:E(l(),j()).optional()}),Ma=he.extend({method:b("roots/list"),params:Re.optional()}),ja=me.extend({roots:_(Aa)}),La=Te.extend({method:b("notifications/roots/list_changed"),params:Ie.optional()}),bu=Z({ttl:R().optional(),pollInterval:R().optional()}),Ua=K(["working","input_required","completed","failed","cancelled"]),nr=f({taskId:l(),status:Ua,ttl:I([R(),qt()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:L(R()),statusMessage:L(l())}),yu=me.extend({task:nr}),Za=Ie.merge(nr),vu=Te.extend({method:b("notifications/tasks/status"),params:Za}),zu=he.extend({method:b("tasks/get"),params:Re.extend({taskId:l()})}),wu=me.merge(nr),Ru=he.extend({method:b("tasks/result"),params:Re.extend({taskId:l()})}),xu=me.loose(),Pu=tr.extend({method:b("tasks/list")}),Tu=rr.extend({tasks:_(nr)}),Eu=he.extend({method:b("tasks/cancel"),params:Re.extend({taskId:l()})}),ku=me.merge(nr),$u=I([En,xn,yi,Na,ua,Gi,Bi,xi,Ti,$i,Ni,Ai,ji,ia,oa]),Cu=I([Rn,kn,Tn,La]),Iu=I([Er,ya,va,$a,ja]),Ou=I([En,ba,Ta,Ma]),Nu=I([Rn,kn,mo,Hi,Ii,aa,ea,Ui,ka]),qu=I([Er,bi,kr,qa,Qi,Wi,Pi,Ei,Ci,Cr,na,Di]),we=un().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ig.custom,message:"URL must be parseable",fatal:!0}),Ns}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Fn=Z({resource:l().url(),authorization_servers:_(we).optional(),jwks_uri:l().url().optional(),scopes_supported:_(l()).optional(),bearer_methods_supported:_(l()).optional(),resource_signing_alg_values_supported:_(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:$().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:$().optional()}),_o=Z({issuer:l(),authorization_endpoint:we,token_endpoint:we,registration_endpoint:we.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),service_documentation:we.optional(),revocation_endpoint:we.optional(),revocation_endpoint_auth_methods_supported:_(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:_(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(l()).optional(),code_challenge_methods_supported:_(l()).optional(),client_id_metadata_document_supported:$().optional(),authorization_response_iss_parameter_supported:$().optional().catch(void 0),dpop_signing_alg_values_supported:_(l()).optional()}),Da=Z({issuer:l(),authorization_endpoint:we,token_endpoint:we,userinfo_endpoint:we.optional(),jwks_uri:we,registration_endpoint:we.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),acr_values_supported:_(l()).optional(),subject_types_supported:_(l()),id_token_signing_alg_values_supported:_(l()),id_token_encryption_alg_values_supported:_(l()).optional(),id_token_encryption_enc_values_supported:_(l()).optional(),userinfo_signing_alg_values_supported:_(l()).optional(),userinfo_encryption_alg_values_supported:_(l()).optional(),userinfo_encryption_enc_values_supported:_(l()).optional(),request_object_signing_alg_values_supported:_(l()).optional(),request_object_encryption_alg_values_supported:_(l()).optional(),request_object_encryption_enc_values_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),display_values_supported:_(l()).optional(),claim_types_supported:_(l()).optional(),claims_supported:_(l()).optional(),service_documentation:l().optional(),claims_locales_supported:_(l()).optional(),ui_locales_supported:_(l()).optional(),claims_parameter_supported:$().optional(),request_parameter_supported:$().optional(),request_uri_parameter_supported:$().optional(),require_request_uri_registration:$().optional(),op_policy_uri:we.optional(),op_tos_uri:we.optional(),client_id_metadata_document_supported:$().optional(),authorization_response_iss_parameter_supported:$().optional().catch(void 0)}),Hn=f({...Da.shape,..._o.pick({code_challenge_methods_supported:!0}).shape}),Vn=f({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:di.number().optional(),scope:l().optional(),refresh_token:l().optional(),issuer:l().optional().catch(void 0)}).strip(),Fa=f({issued_token_type:b("urn:ietf:params:oauth:token-type:id-jag"),access_token:l(),token_type:l().optional(),expires_in:R().optional(),scope:l().optional()}).strip(),Jn=f({error:l(),error_description:l().optional(),error_uri:l().optional()}),ag=we.optional().or(b("").transform(()=>{})),Ha=f({redirect_uris:_(we),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),application_type:l().optional(),client_name:l().optional(),client_uri:we.optional(),logo_uri:ag,scope:l().optional(),contacts:_(l()).optional(),tos_uri:ag,policy_uri:l().optional(),jwks_uri:we.optional(),jwks:au().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Va=f({client_id:l(),client_secret:l().optional(),client_id_issued_at:R().optional(),client_secret_expires_at:R().optional(),issuer:l().optional().catch(void 0)}).strip(),Bn=Ha.merge(Va),Au=f({error:l(),error_description:l().optional()}).strip(),Mu=f({token:l(),token_type_hint:l().optional()}).strip();var hg=Symbol.for("mcp.sdk.errorBrands");function bo(e,t){let r=new Set,o=t;for(;typeof o=="function";){let n=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n=="string"&&r.add(n),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,hg,{value:r,enumerable:!1,configurable:!0})}function nt(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,hg)){let r=t[hg];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var ir=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),yo=class Nb extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return nt(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",bo(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Nb(t.error,t.error_description??t.error,t.error_uri)}},q=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),A=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return nt(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,e)}constructor(e,t,r,o){super(t,o),this.code=e,this.data=r,this.name="SdkError",bo(this,new.target)}},Ut=class extends A{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function qb(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function _g(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Ab({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.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 Mb="2026-07-28",bg=[Mb];function ar(e){return e>=Mb}function yg(e){return e.filter(t=>!ar(t))}function Ya(e){return e.filter(t=>ar(t))}function jb(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Lb=["task","inputRequests","requestState"];function Fw(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Lb.some(t=>t in e)?e:{...e,content:[]}}function Hw(){let e=xr(()=>I([l(),R(),$(),qt(),E(l(),e),_(e)])),t=E(l(),e),r=I([l(),R().int()]),o=l(),n=f({ttl:R().optional()}),s=f({taskId:l()}),i=Z({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=f({_meta:i.optional()}),c=a.extend({task:n.optional()}),u=f({method:l(),params:a.loose().optional()}),d=f({_meta:i.optional()}),h=f({method:l(),params:d.loose().optional()}),m=Z({_meta:i.optional()}),g=I([l(),R().int()]),y=m.strict(),v=d.extend({requestId:g.optional(),reason:l().optional()}),z=h.extend({method:b("notifications/cancelled"),params:v}),U=f({src:l(),mimeType:l().optional(),sizes:_(l()).optional(),theme:K(["light","dark"]).optional()}),H=f({icons:_(U).optional()}),T=f({name:l(),title:l().optional()}),D=T.extend({...T.shape,...H.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),x=St(f({applyDefaults:$().optional()}),t),w=Gt($e=>$e&&typeof $e=="object"&&!Array.isArray($e)&&Object.keys($e).length===0?{form:{}}:$e,St(f({form:x.optional(),url:t.optional()}),t.optional())),F=Z({list:t.optional(),cancel:t.optional(),requests:Z({sampling:Z({createMessage:t.optional()}).optional(),elicitation:Z({create:t.optional()}).optional()}).optional()}),oe=Z({list:t.optional(),cancel:t.optional(),requests:Z({tools:Z({call:t.optional()}).optional()}).optional()}),te=f({experimental:E(l(),t).optional(),sampling:f({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:f({listChanged:$().optional()}).optional(),tasks:F.optional(),extensions:E(l(),t).optional()}),de=a.extend({protocolVersion:l(),capabilities:te,clientInfo:D}),Oe=u.extend({method:b("initialize"),params:de}),ie=f({experimental:E(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:f({listChanged:$().optional()}).optional(),resources:f({subscribe:$().optional(),listChanged:$().optional()}).optional(),tools:f({listChanged:$().optional()}).optional(),tasks:oe.optional(),extensions:E(l(),t).optional()}),ue=m.extend({protocolVersion:l(),capabilities:ie,serverInfo:D,instructions:l().optional()}),xe=h.extend({method:b("notifications/initialized"),params:d.optional()}),Ne=u.extend({method:b("ping"),params:a.optional()}),wt=f({progress:R(),total:L(R()),message:L(l())}),Fe=f({...d.shape,...wt.shape,progressToken:r}),st=h.extend({method:b("notifications/progress"),params:Fe}),Rt=a.extend({cursor:o.optional()}),Ge=u.extend({params:Rt.optional()}),qe=m.extend({nextCursor:o.optional()}),Ht=f({uri:l(),mimeType:L(l()),_meta:E(l(),j()).optional()}),Vt=Ht.extend({text:l()}),xt=l().refine($e=>{try{return atob($e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ee=Ht.extend({blob:xt}),Ae=K(["user","assistant"]),Me=f({audience:_(Ae).optional(),priority:R().min(0).max(1).optional(),lastModified:ot.datetime({offset:!0}).optional()}),ht=f({...T.shape,...H.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(R()),annotations:Me.optional(),_meta:L(Z({}))}),Mr=f({...T.shape,...H.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:Me.optional(),_meta:L(Z({}))}),Ye=Ge.extend({method:b("resources/list")}),Xe=qe.extend({resources:_(ht)}),He=Ge.extend({method:b("resources/templates/list")}),it=qe.extend({resourceTemplates:_(Mr)}),at=a.extend({uri:l()}),Pt=at,Tt=u.extend({method:b("resources/read"),params:Pt}),ur=m.extend({contents:_(I([Vt,Ee]))}),Et=h.extend({method:b("notifications/resources/list_changed"),params:d.optional()}),jr=at,O=u.extend({method:b("resources/subscribe"),params:jr}),kt=at,V=u.extend({method:b("resources/unsubscribe"),params:kt}),M=d.extend({uri:l()}),X=h.extend({method:b("notifications/resources/updated"),params:M}),N=f({name:l(),description:L(l()),required:L($())}),k=f({...T.shape,...H.shape,description:L(l()),arguments:L(_(N)),_meta:L(Z({}))}),B=Ge.extend({method:b("prompts/list")}),J=qe.extend({prompts:_(k)}),ye=a.extend({name:l(),arguments:E(l(),l()).optional()}),Lr=u.extend({method:b("prompts/get"),params:ye}),$t=f({type:b("text"),text:l(),annotations:Me.optional(),_meta:E(l(),j()).optional()}),Ur=f({type:b("image"),data:xt,mimeType:l(),annotations:Me.optional(),_meta:E(l(),j()).optional()}),Zr=f({type:b("audio"),data:xt,mimeType:l(),annotations:Me.optional(),_meta:E(l(),j()).optional()}),is=f({type:b("tool_use"),name:l(),id:l(),input:E(l(),j()),_meta:E(l(),j()).optional()}),dr=f({type:b("resource"),resource:I([Vt,Ee]),annotations:Me.optional(),_meta:E(l(),j()).optional()}),as=ht.extend({type:b("resource_link")}),ct=I([$t,Ur,Zr,as,dr]),To=f({role:Ae,content:ct}),Eo=m.extend({description:l().optional(),messages:_(To)}),Dr=h.extend({method:b("notifications/prompts/list_changed"),params:d.optional()}),cs=f({title:l().optional(),readOnlyHint:$().optional(),destructiveHint:$().optional(),idempotentHint:$().optional(),openWorldHint:$().optional()}),ko=f({taskSupport:K(["required","optional","forbidden"]).optional()}),Fr=f({...T.shape,...H.shape,description:l().optional(),inputSchema:f({type:b("object"),properties:E(l(),e).optional(),required:_(l()).optional()}).catchall(j()),outputSchema:f({type:b("object"),properties:E(l(),e).optional(),required:_(l()).optional()}).catchall(j()).optional(),annotations:cs.optional(),execution:ko.optional(),_meta:E(l(),j()).optional()}),$o=Ge.extend({method:b("tools/list")}),Co=qe.extend({tools:_(Fr)}),Io=m.extend({content:_(ct),structuredContent:E(l(),j()).optional(),isError:$().optional()}),ke=c.extend({name:l(),arguments:E(l(),j()).optional()}),ls=u.extend({method:b("tools/call"),params:ke}),hc=h.extend({method:b("notifications/tools/list_changed"),params:d.optional()}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),us=a.extend({level:Oo}),ds=u.extend({method:b("logging/setLevel"),params:us}),ps=d.extend({level:Oo,logger:l().optional(),data:j()}),hs=h.extend({method:b("notifications/message"),params:ps}),ms=f({name:l().optional()}),fs=f({hints:_(ms).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),gs=f({mode:K(["auto","required","none"]).optional()}),mc=f({type:b("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:_(ct),structuredContent:f({}).loose().optional(),isError:$().optional(),_meta:E(l(),j()).optional()}),Ss=Rr("type",[$t,Ur,Zr]),pr=Rr("type",[$t,Ur,Zr,is,mc]),_s=f({role:Ae,content:I([pr,_(pr)]),_meta:E(l(),j()).optional()}),bs=c.extend({messages:_(_s),modelPreferences:fs.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(l()).optional(),metadata:t.optional(),tools:_(Fr).optional(),toolChoice:gs.optional()}),ys=u.extend({method:b("sampling/createMessage"),params:bs}),vs=m.extend({model:l(),stopReason:L(K(["endTurn","stopSequence","maxTokens"]).or(l())),role:Ae,content:Ss}),zs=m.extend({model:l(),stopReason:L(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:Ae,content:I([pr,_(pr)])}),ws=f({type:b("boolean"),title:l().optional(),description:l().optional(),default:$().optional()}),Rs=f({type:b("string"),title:l().optional(),description:l().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),xs=f({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),Ps=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),default:l().optional()}),Ts=f({type:b("string"),title:l().optional(),description:l().optional(),oneOf:_(f({const:l(),title:l()})),default:l().optional()}),Es=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),enumNames:_(l()).optional(),default:l().optional()}),ks=I([Ps,Ts]),Hr=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(l())}),default:_(l()).optional()}),Vr=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:l(),title:l()}))}),default:_(l()).optional()}),fc=I([Hr,Vr]),gc=I([Es,ks,fc]),Qe=I([gc,ws,Rs,xs]),et=c.extend({mode:b("form").optional(),message:l(),requestedSchema:f({type:b("object"),properties:E(l(),Qe),required:_(l()).optional()}).catchall(j())}),$s=c.extend({mode:b("url"),message:l(),elicitationId:l(),url:l().url()}),mt=I([et,$s]),Sc=u.extend({method:b("elicitation/create"),params:mt}),_c=d.extend({elicitationId:l()}),bc=h.extend({method:b("notifications/elicitation/complete"),params:_c}),yc=m.extend({action:K(["accept","decline","cancel"]),content:Gt($e=>$e===null?void 0:$e,E(l(),I([l(),R(),$(),_(l())])).optional())}),vc=f({type:b("ref/resource"),uri:l()}),zc=f({type:b("ref/prompt"),name:l()}),wc=a.extend({ref:I([zc,vc]),argument:f({name:l(),value:l()}),context:f({arguments:E(l(),l()).optional()}).optional()}),Cs=u.extend({method:b("completion/complete"),params:wc}),Rc=m.extend({completion:Z({values:_(l()).max(100),total:L(R().int()),hasMore:L($())})}),xc=f({uri:l().startsWith("file://"),name:l().optional(),_meta:E(l(),j()).optional()}),No=u.extend({method:b("roots/list"),params:a.optional()}),Is=m.extend({roots:_(xc)}),Pc=h.extend({method:b("notifications/roots/list_changed"),params:d.optional()}),Tc=Z({ttl:R().optional(),pollInterval:R().optional()}),Os=K(["working","input_required","completed","failed","cancelled"]),hr=f({taskId:l(),status:Os,ttl:I([R(),qt()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:L(R()),statusMessage:L(l())}),Ve=m.extend({task:hr}),Ec=d.merge(hr),Jr=h.extend({method:b("notifications/tasks/status"),params:Ec}),qo=u.extend({method:b("tasks/get"),params:a.extend({taskId:l()})}),Ao=m.merge(hr),Mo=u.extend({method:b("tasks/result"),params:a.extend({taskId:l()})}),ud=m.loose(),je=Ge.extend({method:b("tasks/list")}),_e=qe.extend({tasks:_(hr)}),Br=u.extend({method:b("tasks/cancel"),params:a.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:c,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:h,ResultSchema:m,RequestIdSchema:g,EmptyResultSchema:y,CancelledNotificationParamsSchema:v,CancelledNotificationSchema:z,IconSchema:U,IconsSchema:H,BaseMetadataSchema:T,ImplementationSchema:D,ClientTasksCapabilitySchema:F,ServerTasksCapabilitySchema:oe,ClientCapabilitiesSchema:te,InitializeRequestParamsSchema:de,InitializeRequestSchema:Oe,ServerCapabilitiesSchema:ie,InitializeResultSchema:ue,InitializedNotificationSchema:xe,PingRequestSchema:Ne,ProgressSchema:wt,ProgressNotificationParamsSchema:Fe,ProgressNotificationSchema:st,PaginatedRequestParamsSchema:Rt,PaginatedRequestSchema:Ge,PaginatedResultSchema:qe,ResourceContentsSchema:Ht,TextResourceContentsSchema:Vt,BlobResourceContentsSchema:Ee,RoleSchema:Ae,AnnotationsSchema:Me,ResourceSchema:ht,ResourceTemplateSchema:Mr,ListResourcesRequestSchema:Ye,ListResourcesResultSchema:Xe,ListResourceTemplatesRequestSchema:He,ListResourceTemplatesResultSchema:it,ResourceRequestParamsSchema:at,ReadResourceRequestParamsSchema:Pt,ReadResourceRequestSchema:Tt,ReadResourceResultSchema:ur,ResourceListChangedNotificationSchema:Et,SubscribeRequestParamsSchema:jr,SubscribeRequestSchema:O,UnsubscribeRequestParamsSchema:kt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:X,PromptArgumentSchema:N,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ye,GetPromptRequestSchema:Lr,TextContentSchema:$t,ImageContentSchema:Ur,AudioContentSchema:Zr,ToolUseContentSchema:is,EmbeddedResourceSchema:dr,ResourceLinkSchema:as,ContentBlockSchema:ct,PromptMessageSchema:To,GetPromptResultSchema:Eo,PromptListChangedNotificationSchema:Dr,ToolAnnotationsSchema:cs,ToolExecutionSchema:ko,ToolSchema:Fr,ListToolsRequestSchema:$o,ListToolsResultSchema:Co,CallToolResultSchema:Io,CallToolRequestParamsSchema:ke,CallToolRequestSchema:ls,ToolListChangedNotificationSchema:hc,LoggingLevelSchema:Oo,SetLevelRequestParamsSchema:us,SetLevelRequestSchema:ds,LoggingMessageNotificationParamsSchema:ps,LoggingMessageNotificationSchema:hs,ModelHintSchema:ms,ModelPreferencesSchema:fs,ToolChoiceSchema:gs,ToolResultContentSchema:mc,SamplingContentSchema:Ss,SamplingMessageContentBlockSchema:pr,SamplingMessageSchema:_s,CreateMessageRequestParamsSchema:bs,CreateMessageRequestSchema:ys,CreateMessageResultSchema:vs,CreateMessageResultWithToolsSchema:zs,BooleanSchemaSchema:ws,StringSchemaSchema:Rs,NumberSchemaSchema:xs,UntitledSingleSelectEnumSchemaSchema:Ps,TitledSingleSelectEnumSchemaSchema:Ts,LegacyTitledEnumSchemaSchema:Es,SingleSelectEnumSchemaSchema:ks,UntitledMultiSelectEnumSchemaSchema:Hr,TitledMultiSelectEnumSchemaSchema:Vr,MultiSelectEnumSchemaSchema:fc,EnumSchemaSchema:gc,PrimitiveSchemaDefinitionSchema:Qe,ElicitRequestFormParamsSchema:et,ElicitRequestURLParamsSchema:$s,ElicitRequestParamsSchema:mt,ElicitRequestSchema:Sc,ElicitationCompleteNotificationParamsSchema:_c,ElicitationCompleteNotificationSchema:bc,ElicitResultSchema:yc,ResourceTemplateReferenceSchema:vc,PromptReferenceSchema:zc,CompleteRequestParamsSchema:wc,CompleteRequestSchema:Cs,CompleteResultSchema:Rc,RootSchema:xc,ListRootsRequestSchema:No,ListRootsResultSchema:Is,RootsListChangedNotificationSchema:Pc,TaskCreationParamsSchema:Tc,TaskStatusSchema:Os,TaskSchema:hr,CreateTaskResultSchema:Ve,TaskStatusNotificationParamsSchema:Ec,TaskStatusNotificationSchema:Jr,GetTaskRequestSchema:qo,GetTaskResultSchema:Ao,GetTaskPayloadRequestSchema:Mo,GetTaskPayloadResultSchema:ud,ListTasksRequestSchema:je,ListTasksResultSchema:_e,CancelTaskRequestSchema:Br,CancelTaskResultSchema:m.merge(hr),ClientRequestSchema:I([Ne,Oe,Cs,ds,Lr,B,Ye,He,Tt,O,V,ls,$o,qo,Mo,je,Br]),ClientNotificationSchema:I([z,st,xe,Pc,Jr]),ClientResultSchema:I([y,vs,zs,yc,Is,Ao,_e,Ve]),ServerRequestSchema:I([Ne,ys,Sc,No,qo,Mo,je,Br]),ServerNotificationSchema:I([z,st,hs,X,Et,hc,Dr,Jr,bc]),ServerResultSchema:I([y,ue,Rc,Eo,J,Xe,it,ur,Io,Co,Ao,_e,Ve]),CallToolResultWireSchema:j().superRefine(($e,Av)=>{if(!(typeof $e!="object"||$e===null||Array.isArray($e)||$e.content!==void 0)){for(let mS of Lb)if(mS in $e){Av.addIssue({code:"custom",message:`content is required when the body carries '${mS}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Fw).pipe(Io)}}var Vw;function Ub(){return Vw??=Hw()}function Zb(e){return e.type!=="object"}var Jw=new Set(["const","enum","default","examples"]),Bw=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function vb(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function Ww(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(vb(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=bS(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map(c=>o(c,!1));if(n===null||typeof n!="object"||!s&&vb(n.$id))return n;let i={},a=!1;for(let[c,u]of Object.entries(n))s?i[c]=o(u,!1):(c==="$ref"||c==="$dynamicRef")&&typeof u=="string"?i[c]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:c==="$recursiveRef"&&u==="#"&&r?a=!0:Jw.has(c)?i[c]=u:Bw.has(c)?i[c]=o(u,!0):i[c]=o(u,!1);return a&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Db={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Fb={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Kw={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},ju;function vg(){if(ju)return ju;let e=Ub();return ju={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},ju}function Hb(e){return Object.prototype.hasOwnProperty.call(Db,e)}function Vb(e){return Object.prototype.hasOwnProperty.call(Fb,e)}function Gw(e){return Object.prototype.hasOwnProperty.call(Kw,e)}function Yw(e){return Gw(e)?vg().resultSchemas[e]:void 0}function Xw(e){return Hb(e)?vg().requestSchemas[e]:void 0}function Qw(e){return Vb(e)?vg().notificationSchemas[e]:void 0}var rk=Object.keys(Db),ok=Object.keys(Fb);function mg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lu(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var zb={ok:!1,reason:"not-in-era"};function wb(e){return mg(e)&&mg(e.outputSchema)&&Zb(e.outputSchema)}var zg={era:"2025-11-25",hasRequestMethod:Hb,hasNotificationMethod:Vb,validateRequest:(e,t)=>Lu(Xw(e),t),validateResult:(e,t)=>Lu(Yw(e),t),validateNotification:(e,t)=>Lu(Qw(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>zb,validateInputResponse:()=>zb,samplingResultVariant:((e,t)=>{let r=Ub();return Lu(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=jb(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Zb(t);return!n&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(mg(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(o=>wb(o))?t:{...t,tools:r.map(o=>wb(o)?{...o,outputSchema:Ww(o.outputSchema)}:o)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function eR(){let e=xr(()=>I([l(),R(),$(),qt(),E(l(),e),_(e)])),t=E(l(),e),r=I([l(),R().int()]),o=l(),n=I([l(),R().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=l().refine(_e=>{try{return atob(_e),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=f({ttl:R().optional()}),u=f({taskId:l()}),d=Z({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),h=f({_meta:d.optional()}),m=h.extend({task:c.optional()}),g=f({_meta:d.optional()}),y=f({method:l(),params:g.loose().optional()}),v=f({src:l(),mimeType:l().optional(),sizes:_(l()).optional(),theme:K(["light","dark"]).optional()}),z=f({icons:_(v).optional()}),U=f({name:l(),title:l().optional()}),H=U.extend({...U.shape,...z.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),T=St(f({applyDefaults:$().optional()}),t),D=Gt(_e=>_e&&typeof _e=="object"&&!Array.isArray(_e)&&Object.keys(_e).length===0?{form:{}}:_e,St(f({form:T.optional(),url:t.optional()}),t.optional())),x=Z({list:t.optional(),cancel:t.optional(),requests:Z({sampling:Z({createMessage:t.optional()}).optional(),elicitation:Z({create:t.optional()}).optional()}).optional()}),w=Z({list:t.optional(),cancel:t.optional(),requests:Z({tools:Z({call:t.optional()}).optional()}).optional()}),F=f({experimental:E(l(),t).optional(),sampling:f({context:t.optional(),tools:t.optional()}).optional(),elicitation:D.optional(),roots:f({listChanged:$().optional()}).optional(),tasks:x.optional(),extensions:E(l(),t).optional()}),oe=f({experimental:E(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:f({listChanged:$().optional()}).optional(),resources:f({subscribe:$().optional(),listChanged:$().optional()}).optional(),tools:f({listChanged:$().optional()}).optional(),tasks:w.optional(),extensions:E(l(),t).optional()}),te=f({progress:R(),total:L(R()),message:L(l())}),de=f({...g.shape,...te.shape,progressToken:r}),Oe=y.extend({method:b("notifications/progress"),params:de}),ie=g.extend({level:i,logger:l().optional(),data:j()}),ue=y.extend({method:b("notifications/message"),params:ie}),xe=f({uri:l(),mimeType:L(l()),_meta:E(l(),j()).optional()}),Ne=xe.extend({text:l()}),wt=xe.extend({blob:a}),Fe=f({audience:_(s).optional(),priority:R().min(0).max(1).optional(),lastModified:ot.datetime({offset:!0}).optional()}),st=f({...U.shape,...z.shape,uri:l(),description:L(l()),mimeType:L(l()),size:L(R()),annotations:Fe.optional(),_meta:L(Z({}))}),Rt=f({...U.shape,...z.shape,uriTemplate:l(),description:L(l()),mimeType:L(l()),annotations:Fe.optional(),_meta:L(Z({}))}),Ge=y.extend({method:b("notifications/resources/list_changed"),params:g.optional()}),qe=g.extend({uri:l()}),Ht=y.extend({method:b("notifications/resources/updated"),params:qe}),Vt=f({name:l(),description:L(l()),required:L($())}),xt=f({...U.shape,...z.shape,description:L(l()),arguments:L(_(Vt)),_meta:L(Z({}))}),Ee=y.extend({method:b("notifications/prompts/list_changed"),params:g.optional()}),Ae=f({type:b("text"),text:l(),annotations:Fe.optional(),_meta:E(l(),j()).optional()}),Me=f({type:b("image"),data:a,mimeType:l(),annotations:Fe.optional(),_meta:E(l(),j()).optional()}),ht=f({type:b("audio"),data:a,mimeType:l(),annotations:Fe.optional(),_meta:E(l(),j()).optional()}),Mr=f({type:b("tool_use"),name:l(),id:l(),input:E(l(),j()),_meta:E(l(),j()).optional()}),Ye=f({type:b("resource"),resource:I([Ne,wt]),annotations:Fe.optional(),_meta:E(l(),j()).optional()}),Xe=st.extend({type:b("resource_link")}),He=I([Ae,Me,ht,Xe,Ye]),it=f({role:s,content:He}),at=f({title:l().optional(),readOnlyHint:$().optional(),destructiveHint:$().optional(),idempotentHint:$().optional(),openWorldHint:$().optional()}),Pt=y.extend({method:b("notifications/tools/list_changed"),params:g.optional()}),Tt=f({name:l().optional()}),ur=f({hints:_(Tt).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),Et=f({mode:K(["auto","required","none"]).optional()}),jr=f({type:b("boolean"),title:l().optional(),description:l().optional(),default:$().optional()}),O=f({type:b("string"),title:l().optional(),description:l().optional(),minLength:R().optional(),maxLength:R().optional(),format:K(["email","uri","date","date-time"]).optional(),default:l().optional()}),kt=f({type:K(["number","integer"]),title:l().optional(),description:l().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),V=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),default:l().optional()}),M=f({type:b("string"),title:l().optional(),description:l().optional(),oneOf:_(f({const:l(),title:l()})),default:l().optional()}),X=f({type:b("string"),title:l().optional(),description:l().optional(),enum:_(l()),enumNames:_(l()).optional(),default:l().optional()}),N=I([V,M]),k=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({type:b("string"),enum:_(l())}),default:_(l()).optional()}),B=f({type:b("array"),title:l().optional(),description:l().optional(),minItems:R().optional(),maxItems:R().optional(),items:f({anyOf:_(f({const:l(),title:l()}))}),default:_(l()).optional()}),J=I([k,B]),ye=I([X,N,J]),Lr=I([ye,jr,O,kt]),$t=m.extend({mode:b("form").optional(),message:l(),requestedSchema:f({type:b("object"),properties:E(l(),Lr),required:_(l()).optional()}).catchall(j())}),Ur=f({type:b("ref/resource"),uri:l()}),Zr=f({type:b("ref/prompt"),name:l()}),is=f({uri:l().startsWith("file://"),name:l().optional(),_meta:E(l(),j()).optional()}),dr=F.shape,as=f({experimental:dr.experimental,sampling:dr.sampling,elicitation:dr.elicitation,roots:dr.roots,extensions:dr.extensions}),ct=oe.shape,To=f({experimental:ct.experimental,logging:ct.logging,completions:ct.completions,prompts:ct.prompts,resources:ct.resources,tools:ct.tools,extensions:ct.extensions}),Eo=Z({progressToken:r.optional(),[Xt]:l(),[gn]:H.optional(),[oo]:as,[Sn]:i.optional()}),Dr=f({...U.shape,...z.shape,description:l().optional(),inputSchema:Z({$schema:l().optional(),type:b("object")}),outputSchema:Z({$schema:l().optional()}).optional(),annotations:at.optional(),_meta:E(l(),j()).optional()}),cs=f({type:b("tool_result"),toolUseId:l(),content:_(He),structuredContent:j().optional(),isError:$().optional(),_meta:E(l(),j()).optional()}),ko=I([Ae,Me,ht,Mr,cs]),Fr=f({role:s,content:I([ko,_(ko)]),_meta:E(l(),j()).optional()}),$o=l(),Co=Z({[Qt]:H.optional().catch(void 0)}),Io=Co.optional();function ke(_e){return Z({_meta:Io,resultType:$o.default("complete"),..._e})}let ls=ke({}),hc=ke({nextCursor:o.optional()}),Oo=ke({content:_(He),structuredContent:j().optional(),isError:$().optional()}),us=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),tools:_(Dr),nextCursor:o.optional()}),ds=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),prompts:_(xt),nextCursor:o.optional()}),ps=ke({description:l().optional(),messages:_(it)}),hs=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resources:_(st),nextCursor:o.optional()}),ms=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:_(Rt),nextCursor:o.optional()}),fs=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),contents:_(I([Ne,wt]))}),gs=ke({completion:f({values:_(l()).max(100),total:R().int().optional(),hasMore:$().optional()}).loose()}),mc=ke({ttlMs:R().int().min(0),cacheScope:K(["public","private"])}),Ss=ke({ttlMs:R().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:_(l()),capabilities:To,instructions:l().optional()}),pr=f({messages:_(Fr),modelPreferences:ur.optional(),systemPrompt:l().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:_(l()).optional(),metadata:t.optional(),tools:_(Dr).optional(),toolChoice:Et.optional()}),_s=f({method:b("sampling/createMessage"),params:pr}),bs=f({method:b("roots/list"),params:f({_meta:E(l(),j()).optional()}).optional()}),ys=f({...Fr.shape,model:l(),stopReason:l().optional()}),vs=f({roots:_(is)}),zs=f({action:K(["accept","decline","cancel"]),content:E(l(),I([l(),R(),$(),_(l())])).optional()}),ws=f({mode:b("url"),message:l(),url:l().url()}),Rs=I([$t,ws]),xs=f({method:b("elicitation/create"),params:Rs}),Ps=I([_s,bs,xs]),Ts=I([ys,vs,zs]),Es=E(l(),Ps),ks=E(l(),Ts),Hr=ke({inputRequests:Es.optional(),requestState:l().optional()}),Vr={inputResponses:ks.optional(),requestState:l().optional()},fc=f({_meta:Eo,...Vr}),gc=Z({progressToken:r.optional()});function Qe(_e,Br){return f({method:b(_e),params:f({_meta:Eo,...Br})})}function et(_e,Br){return f({method:b(_e),params:f({_meta:gc.optional(),...Br}).optional()})}let $s={name:l(),arguments:E(l(),j()).optional(),...Vr},mt={cursor:o.optional()},Sc=Qe("tools/call",$s),_c=Qe("tools/list",mt),bc=Qe("prompts/list",mt),yc=Qe("prompts/get",{name:l(),arguments:E(l(),l()).optional(),...Vr}),vc=Qe("resources/list",mt),zc=Qe("resources/templates/list",mt),wc=Qe("resources/read",{uri:l(),...Vr}),Cs={ref:I([Zr,Ur]),argument:f({name:l(),value:l()}),context:f({arguments:E(l(),l()).optional()}).optional()},Rc=Qe("completion/complete",Cs),xc=Qe("server/discover",{}),No=f({toolsListChanged:$().optional(),promptsListChanged:$().optional(),resourcesListChanged:$().optional(),resourceSubscriptions:_(l()).optional()}),Is={notifications:No},Pc=Qe("subscriptions/listen",Is),Tc=Co.extend({"io.modelcontextprotocol/subscriptionId":n}),Os=Z({_meta:Tc,resultType:$o.default("complete")}),hr={"tools/call":et("tools/call",$s),"tools/list":et("tools/list",mt),"prompts/get":et("prompts/get",{name:l(),arguments:E(l(),l()).optional()}),"prompts/list":et("prompts/list",mt),"resources/list":et("resources/list",mt),"resources/templates/list":et("resources/templates/list",mt),"resources/read":et("resources/read",{uri:l()}),"completion/complete":et("completion/complete",Cs),"server/discover":et("server/discover",{}),"subscriptions/listen":et("subscriptions/listen",Is)};function Ve(_e){return Z({_meta:Io,..._e})}let Ec={"tools/call":Ve({content:_(He),structuredContent:j().optional(),isError:$().optional()}),"tools/list":Ve({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),tools:_(Dr),nextCursor:o.optional()}),"prompts/get":Ve({description:l().optional(),messages:_(it)}),"prompts/list":Ve({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),prompts:_(xt),nextCursor:o.optional()}),"resources/list":Ve({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resources:_(st),nextCursor:o.optional()}),"resources/templates/list":Ve({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:_(Rt),nextCursor:o.optional()}),"resources/read":Ve({ttlMs:R().int().min(0),cacheScope:K(["public","private"]),contents:_(I([Ne,wt]))}),"completion/complete":Ve({completion:f({values:_(l()).max(100),total:R().int().optional(),hasMore:$().optional()}).loose()}),"server/discover":Ve({ttlMs:R().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:_(l()),capabilities:To,instructions:l().optional()}),"subscriptions/listen":Ve({})},Jr=Z({"io.modelcontextprotocol/subscriptionId":n.optional()}),qo=f({method:b("notifications/subscriptions/acknowledged"),params:f({_meta:Jr.optional(),notifications:No})}),Ao=f({_meta:Jr.optional(),requestId:n,reason:l().optional()}),Mo=f({method:b("notifications/cancelled"),params:Ao}),ud={"notifications/cancelled":Mo,"notifications/progress":Oe,"notifications/message":ue,"notifications/resources/updated":Ht,"notifications/resources/list_changed":Ge,"notifications/tools/list_changed":Pt,"notifications/prompts/list_changed":Ee,"notifications/subscriptions/acknowledged":qo},je=_e=>f({jsonrpc:b("2.0"),id:I([l(),R().int()]),result:_e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:g,NotificationSchema:y,IconSchema:v,IconsSchema:z,BaseMetadataSchema:U,ImplementationSchema:H,ClientTasksCapabilitySchema:x,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:F,ServerCapabilitiesSchema:oe,ProgressSchema:te,ProgressNotificationParamsSchema:de,ProgressNotificationSchema:Oe,LoggingMessageNotificationParamsSchema:ie,LoggingMessageNotificationSchema:ue,ResourceContentsSchema:xe,TextResourceContentsSchema:Ne,BlobResourceContentsSchema:wt,AnnotationsSchema:Fe,ResourceSchema:st,ResourceTemplateSchema:Rt,ResourceListChangedNotificationSchema:Ge,ResourceUpdatedNotificationParamsSchema:qe,ResourceUpdatedNotificationSchema:Ht,PromptArgumentSchema:Vt,PromptSchema:xt,PromptListChangedNotificationSchema:Ee,TextContentSchema:Ae,ImageContentSchema:Me,AudioContentSchema:ht,ToolUseContentSchema:Mr,EmbeddedResourceSchema:Ye,ResourceLinkSchema:Xe,ContentBlockSchema:He,PromptMessageSchema:it,ToolAnnotationsSchema:at,ToolListChangedNotificationSchema:Pt,ModelHintSchema:Tt,ModelPreferencesSchema:ur,ToolChoiceSchema:Et,BooleanSchemaSchema:jr,StringSchemaSchema:O,NumberSchemaSchema:kt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:M,LegacyTitledEnumSchemaSchema:X,SingleSelectEnumSchemaSchema:N,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ye,PrimitiveSchemaDefinitionSchema:Lr,ElicitRequestFormParamsSchema:$t,ResourceTemplateReferenceSchema:Ur,PromptReferenceSchema:Zr,RootSchema:is,ClientCapabilities2026Schema:as,ServerCapabilities2026Schema:To,RequestMetaEnvelopeSchema:Eo,ToolSchema:Dr,ToolResultContentSchema:cs,SamplingMessageContentBlockSchema:ko,SamplingMessageSchema:Fr,ResultTypeSchema:$o,ResultMetaSchema:Co,ResultSchema:ls,PaginatedResultSchema:hc,CallToolResultSchema:Oo,ListToolsResultSchema:us,ListPromptsResultSchema:ds,GetPromptResultSchema:ps,ListResourcesResultSchema:hs,ListResourceTemplatesResultSchema:ms,ReadResourceResultSchema:fs,CompleteResultSchema:gs,CacheableResultSchema:mc,DiscoverResultSchema:Ss,CreateMessageRequestParamsSchema:pr,CreateMessageRequestSchema:_s,ListRootsRequestSchema:bs,CreateMessageResultSchema:ys,ListRootsResultSchema:vs,ElicitResultSchema:zs,ElicitRequestURLParamsSchema:ws,ElicitRequestParamsSchema:Rs,ElicitRequestSchema:xs,InputRequestSchema:Ps,InputResponseSchema:Ts,InputRequestsSchema:Es,InputResponsesSchema:ks,InputRequiredResultSchema:Hr,InputResponseRequestParamsSchema:fc,CallToolRequestSchema:Sc,ListToolsRequestSchema:_c,ListPromptsRequestSchema:bc,GetPromptRequestSchema:yc,ListResourcesRequestSchema:vc,ListResourceTemplatesRequestSchema:zc,ReadResourceRequestSchema:wc,CompleteRequestSchema:Rc,DiscoverRequestSchema:xc,SubscriptionFilterSchema:No,SubscriptionsListenRequestSchema:Pc,SubscriptionsListenResultMetaSchema:Tc,SubscriptionsListenResultSchema:Os,dispatchRequestSchemas:hr,dispatchResultSchemas:Ec,NotificationMetaSchema:Jr,SubscriptionsAcknowledgedNotificationSchema:qo,CancelledNotificationParamsSchema:Ao,CancelledNotificationSchema:Mo,notificationSchemas2026:ud,JSONRPCResultResponseSchema:je(ls),CallToolResultResponseSchema:je(I([Oo,Hr])),ListToolsResultResponseSchema:je(us),ListPromptsResultResponseSchema:je(ds),GetPromptResultResponseSchema:je(I([ps,Hr])),ListResourcesResultResponseSchema:je(hs),ListResourceTemplatesResultResponseSchema:je(ms),ReadResourceResultResponseSchema:je(I([fs,Hr])),CompleteResultResponseSchema:je(gs),DiscoverResultResponseSchema:je(Ss),SubscriptionsListenResultResponseSchema:je(Os)}}var tR;function Ir(){return tR??=eR()}var rR=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function oR(e){return rR.includes(e)}var wg=Symbol("modelcontextprotocol.resultCacheHintFallback");function nR(e){return e[wg]}function Jb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Bb(e){return e==="public"||e==="private"}var W=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),se=class Wb extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return nt(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",bo(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Gb(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested=="string")return new Hu({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri=="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Kb(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities=="object"&&!Array.isArray(n.requiredCapabilities))return new Yb({requiredCapabilities:n.requiredCapabilities},r)}return new Wb(t,r,o)}},Kb=class extends se{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Gb=class extends se{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Hu=class extends se{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Yb=class extends se{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},sR=0,iR="private",aR=["tools/call","prompts/get","resources/read"];function cR(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||aR.includes(e))return t;throw new se(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function lR(e,t){let r=nR(t);if(t.resultType!=="complete"||!oR(e))return r===void 0?t:mR(t);let o=t,n=Jb(o.ttlMs)?o.ttlMs:pR(r),s=Bb(o.cacheScope)?o.cacheScope:hR(r),i={...o,ttlMs:n,cacheScope:s};return delete i[wg],i}function uR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dR(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[Qt]:t}}:!uR(r)||r[Qt]!==void 0?e:{...e,_meta:{...r,[Qt]:t}}}function pR(e){return e!==void 0&&Jb(e.ttlMs)?e.ttlMs:sR}function hR(e){return e!==void 0&&Bb(e.cacheScope)?e.cacheScope:iR}function mR(e){let t={...e};return delete t[wg],t}var fR=["elicitation/create","sampling/createMessage","roots/list"],Uu;function Xb(){if(Uu)return Uu;let e=Ir();return Uu={request:{"elicitation/create":f({method:b("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":f({method:b("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":f({method:b("roots/list"),params:Z({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Uu}function Qb(e){return fR.includes(e)}function lg(e){return Qb(e)?Xb().request[e]:void 0}function gR(e){return Qb(e)?Xb().response[e]:void 0}var Rg={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},ey={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function ty(e){return Object.prototype.hasOwnProperty.call(Rg,e)}function ry(e){return Object.prototype.hasOwnProperty.call(ey,e)}function SR(e){return Object.prototype.hasOwnProperty.call(Rg,e)}function _R(e){return ty(e)?Ir().dispatchRequestSchemas[e]:void 0}function bR(e){return SR(e)?Ir().dispatchResultSchemas[e]:void 0}function yR(e){return ry(e)?Ir().notificationSchemas2026[e]:void 0}var nk=Object.keys(Rg),sk=Object.keys(ey);function Wa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ja(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var vR={ok:!1,reason:"not-in-era"},zR=[Xt,oo];function wR(e,t){let r=t,o=!1,n=()=>(o||(r={...r},o=!0),r),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Wa(a)&&"execution"in a)&&(n().tools=s.map(a=>{if(!Wa(a)||!("execution"in a))return a;let c={...a};return delete c.execution,c}));let i=t.capabilities;if(Wa(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var xg={era:"2026-07-28",hasRequestMethod:ty,hasNotificationMethod:ry,hasInputRequestMethod:e=>lg(e)!==void 0,validateRequest:(e,t)=>Ja(_R(e),t),validateResult:(e,t)=>Ja(bR(e),t),validateNotification:(e,t)=>Ja(yR(e),t),validateInputRequest:(e,t)=>Ja(lg(e),t),validateInputResponse:(e,t)=>Ja(gR(e),t),samplingResultVariant:()=>vR,outboundEnvelope(e){return{[Xt]:e.protocolVersion,[gn]:e.clientInfo,[oo]:e.clientCapabilities,...e.logLevel!==void 0&&{[Sn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of zR)o in e||t.push({key:o,problem:"missing"});let r=Ir().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";n.length===1&&t.some(i=>i.key===s&&i.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:e=>jb(e),inputRequestSchema:lg,decodeResult(e,t){if(!Wa(t))return{kind:"invalid",error:new A(q.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new A(q.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new A(q.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=Wa(i)?i:{},c=t.requestState,u=t._meta===void 0?void 0:Ir().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;return Object.keys(a).length===0&&typeof c!="string"?{kind:"invalid",error:new A(q.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:a,...typeof c=="string"&&{requestState:c},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new A(q.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=RR(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new A(q.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return dR(lR(e,cR(e,wR(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Ir().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Zu;function RR(){if(Zu)return Zu;let e=Ir();return Zu={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Zu}var Vu="2026-07-28";function sr(e){return e!==void 0&&ar(e)?xg:zg}function Rb(e){return e.revision!==void 0?sr(e.revision).era:e.era==="modern"?xg.era:zg.era}function ug(e){return oy.some(t=>t.hasRequestMethod(e))}function dg(e){return oy.some(t=>t.hasNotificationMethod(e))}function xb(e){return e==="tasks/get"||e==="tasks/cancel"}var oy=[zg,xg],xR=gS({AnnotationsSchema:()=>jt,AudioContentSchema:()=>uo,BaseMetadataSchema:()=>At,BaseRequestParamsSchema:()=>Re,BlobResourceContentsSchema:()=>In,BooleanSchemaSchema:()=>An,CallToolRequestParamsSchema:()=>sa,CallToolRequestSchema:()=>ia,CallToolResultSchema:()=>Cr,CancelTaskRequestSchema:()=>Eu,CancelTaskResultSchema:()=>ku,CancelledNotificationParamsSchema:()=>fi,CancelledNotificationSchema:()=>Rn,ClientCapabilitiesSchema:()=>Si,ClientNotificationSchema:()=>Cu,ClientRequestSchema:()=>$u,ClientResultSchema:()=>Iu,ClientTasksCapabilitySchema:()=>gu,CompatibilityCallToolResultSchema:()=>_u,CompleteRequestParamsSchema:()=>Oa,CompleteRequestSchema:()=>Na,CompleteResultSchema:()=>qa,ContentBlockSchema:()=>Lt,CreateMessageRequestParamsSchema:()=>_a,CreateMessageRequestSchema:()=>ba,CreateMessageResultSchema:()=>ya,CreateMessageResultWithToolsSchema:()=>va,CreateTaskResultSchema:()=>yu,CursorSchema:()=>bn,DiscoverRequestSchema:()=>yi,DiscoverResultSchema:()=>kr,ElicitRequestFormParamsSchema:()=>So,ElicitRequestParamsSchema:()=>Pa,ElicitRequestSchema:()=>Ta,ElicitRequestURLParamsSchema:()=>xa,ElicitResultSchema:()=>$a,ElicitationCompleteNotificationParamsSchema:()=>Ea,ElicitationCompleteNotificationSchema:()=>ka,EmbeddedResourceSchema:()=>po,EmptyResultSchema:()=>Er,EnumSchemaSchema:()=>Ra,GetPromptRequestParamsSchema:()=>Ki,GetPromptRequestSchema:()=>Gi,GetPromptResultSchema:()=>Qi,GetTaskPayloadRequestSchema:()=>Ru,GetTaskPayloadResultSchema:()=>xu,GetTaskRequestSchema:()=>zu,GetTaskResultSchema:()=>wu,IconSchema:()=>gi,IconsSchema:()=>er,ImageContentSchema:()=>lo,ImplementationSchema:()=>Mt,InitializeRequestParamsSchema:()=>_i,InitializeRequestSchema:()=>xn,InitializeResultSchema:()=>bi,InitializedNotificationSchema:()=>Tn,JSONArraySchema:()=>mu,JSONObjectSchema:()=>pe,JSONRPCErrorResponseSchema:()=>io,JSONRPCMessageSchema:()=>bt,JSONRPCNotificationSchema:()=>wn,JSONRPCRequestSchema:()=>zn,JSONRPCResponseSchema:()=>fu,JSONRPCResultResponseSchema:()=>so,JSONValueSchema:()=>Yt,LegacyTitledEnumSchemaSchema:()=>Ln,ListChangedOptionsBaseSchema:()=>ca,ListPromptsRequestSchema:()=>Bi,ListPromptsResultSchema:()=>Wi,ListResourceTemplatesRequestSchema:()=>Ti,ListResourceTemplatesResultSchema:()=>Ei,ListResourcesRequestSchema:()=>xi,ListResourcesResultSchema:()=>Pi,ListRootsRequestSchema:()=>Ma,ListRootsResultSchema:()=>ja,ListTasksRequestSchema:()=>Pu,ListTasksResultSchema:()=>Tu,ListToolsRequestSchema:()=>oa,ListToolsResultSchema:()=>na,LoggingLevelSchema:()=>qn,LoggingMessageNotificationParamsSchema:()=>da,LoggingMessageNotificationSchema:()=>mo,ModelHintSchema:()=>pa,ModelPreferencesSchema:()=>ha,MultiSelectEnumSchemaSchema:()=>wa,NotificationSchema:()=>Te,NotificationsParamsSchema:()=>Ie,NumberSchemaSchema:()=>go,PaginatedRequestParamsSchema:()=>wi,PaginatedRequestSchema:()=>tr,PaginatedResultSchema:()=>rr,PingRequestSchema:()=>En,PrimitiveSchemaDefinitionSchema:()=>Dn,ProgressNotificationParamsSchema:()=>zi,ProgressNotificationSchema:()=>kn,ProgressSchema:()=>vi,ProgressTokenSchema:()=>_n,PromptArgumentSchema:()=>Vi,PromptListChangedNotificationSchema:()=>ea,PromptMessageSchema:()=>Xi,PromptReferenceSchema:()=>Ia,PromptSchema:()=>Ji,ReadResourceRequestParamsSchema:()=>ki,ReadResourceRequestSchema:()=>$i,ReadResourceResultSchema:()=>Ci,RelatedTaskMetadataSchema:()=>mi,RequestIdSchema:()=>_t,RequestMetaSchema:()=>yn,RequestSchema:()=>he,ResourceContentsSchema:()=>$n,ResourceLinkSchema:()=>ho,ResourceListChangedNotificationSchema:()=>Ii,ResourceRequestParamsSchema:()=>ao,ResourceSchema:()=>On,ResourceTemplateReferenceSchema:()=>Ca,ResourceTemplateSchema:()=>Ri,ResourceUpdatedNotificationParamsSchema:()=>Fi,ResourceUpdatedNotificationSchema:()=>Hi,ResultMetaObjectSchema:()=>vn,ResultSchema:()=>me,RoleSchema:()=>or,RootSchema:()=>Aa,RootsListChangedNotificationSchema:()=>La,SamplingContentSchema:()=>ga,SamplingMessageContentBlockSchema:()=>Pr,SamplingMessageSchema:()=>Sa,ServerCapabilitiesSchema:()=>Pn,ServerNotificationSchema:()=>Nu,ServerRequestSchema:()=>Ou,ServerResultSchema:()=>qu,ServerTasksCapabilitySchema:()=>Su,SetLevelRequestParamsSchema:()=>la,SetLevelRequestSchema:()=>ua,SingleSelectEnumSchemaSchema:()=>za,StringSchemaSchema:()=>fo,SubscribeRequestParamsSchema:()=>Oi,SubscribeRequestSchema:()=>Ni,SubscriptionFilterSchema:()=>Nn,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Li,SubscriptionsAcknowledgedNotificationSchema:()=>Ui,SubscriptionsListenRequestParamsSchema:()=>Mi,SubscriptionsListenRequestSchema:()=>ji,SubscriptionsListenResultMetaSchema:()=>Zi,SubscriptionsListenResultSchema:()=>Di,TaskAugmentedRequestParamsSchema:()=>Tr,TaskCreationParamsSchema:()=>bu,TaskMetadataSchema:()=>hi,TaskSchema:()=>nr,TaskStatusNotificationParamsSchema:()=>Za,TaskStatusNotificationSchema:()=>vu,TaskStatusSchema:()=>Ua,TextContentSchema:()=>co,TextResourceContentsSchema:()=>Cn,TitledMultiSelectEnumSchemaSchema:()=>Zn,TitledSingleSelectEnumSchemaSchema:()=>jn,ToolAnnotationsSchema:()=>ta,ToolChoiceSchema:()=>ma,ToolExecutionSchema:()=>ra,ToolListChangedNotificationSchema:()=>aa,ToolResultContentSchema:()=>fa,ToolSchema:()=>$r,ToolUseContentSchema:()=>Yi,UnsubscribeRequestParamsSchema:()=>qi,UnsubscribeRequestSchema:()=>Ai,UntitledMultiSelectEnumSchemaSchema:()=>Un,UntitledSingleSelectEnumSchemaSchema:()=>Mn});var vo=e=>zn.safeParse(e).success,ny=e=>wn.safeParse(e).success,Kn=e=>so.safeParse(e).success,Gn=e=>io.safeParse(e).success;var sy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Pg=e=>xn.safeParse(e).success,iy=e=>Tn.safeParse(e).success;var PR="Mcp-Param-",Pb="x-mcp-header",TR=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ER=new Set(["string","integer","boolean","number"]);function Tg(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!="object")return;let c=s;if(Pb in c){if(!a||i.length===0)return`${Du(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=c[Pb];if(typeof d!="string"||d.length===0)return`${Du(i)}: x-mcp-header MUST be a non-empty string`;if(!TR.test(d))return`${Du(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let h=typeof c.type=="string"?c.type:void 0;if(h===void 0||!ER.has(h))return`${Du(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${h??"<none>"}`;let m=d.toLowerCase(),g=r.get(m);if(g!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${g}')`;r.set(m,d),t.push({path:i,headerName:d,type:h})}let u=c.properties;if(u!==null&&typeof u=="object")for(let[d,h]of Object.entries(u)){let m=o(h,[...i,d],a);if(m!==void 0)return m}for(let d of kR){let h=c[d];if(h===void 0)continue;let m=Array.isArray(h)?h:h!==null&&typeof h=="object"&&$R.has(d)?Object.values(h):[h];for(let g of m){let y=o(g,[...i,`<${d}>`],!1);if(y!==void 0)return y}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var kR=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],$R=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function Du(e){return e.length===0?"<root>":e.join(".")}var ay="=?base64?",cy="?=";function CR(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function IR(e){if(e.length===0||e.startsWith(ay)&&e.endsWith(cy)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(!(r===9||r>=32&&r<=126))return!0}return!1}function OR(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function Eg(e){return IR(e)?`${ay}${OR(e)}${cy}`:e}function NR(e,t){let r=e;for(let o of t){if(r===null||typeof r!="object")return;r=r[o]}return r}function ly(e,t){let r={};for(let o of e){let n=NR(t,o.path);if(n==null)continue;let s=CR(n);s!==void 0&&(r[`${PR}${o.headerName}`]=Eg(s))}return r}var Wn=-32020,ik=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Wn,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Wn],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Wn],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],ak={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Wn]:400},Tb={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function uy(e,t){let r=Object.hasOwn(Tb,e)?Tb[e]:void 0;if(r===void 0)return;let o=qR(t)?t[r]:void 0;return{field:r,value:typeof o=="string"?o:void 0}}function qR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ju(e,t){return ei(e,t)}function Ba(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function fg(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var Eb=!1,gg="draft-2020-12";function AR(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:gg});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Eb||(Eb=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=to(e,{target:gg,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:dy(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function dy(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||dy(o)))}return!1}function MR(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function pg(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>MR(o)).join(", ")}:{success:!0,data:r.value}}function jR(e){let t=to(e,{target:gg,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var LR=/\\\.\\d\{(\d+)\}/;function UR(e){let t=LR.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(n=>r.map(s=>ot.datetime({local:o,offset:n,precision:s}))))}function ZR(e,t){let r;switch(e){case"email":r=[Hl()];break;case"uri":r=[un()];break;case"date":r=[ot.date()];break;case"date-time":r=UR(t);break}return new Set(r.map(o=>jR(o)).filter(o=>o!==void 0))}function DR(e,t,r){return r!=="zod"?!0:ZR(e,t).has(t)}function Ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FR(e){try{return AR(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new se(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var HR=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function kg(e){return HR.has(e)||e.startsWith("x-")}var VR=new Set(["$schema",...Object.keys(So.shape.requestedSchema.shape)]),kb={string:Ba([fo,Mn,jn,Ln]),number:Ba([go]),integer:Ba([go]),boolean:Ba([An]),array:Ba([Un,Zn])},JR=new Set(fo.shape.format.unwrap().options);function BR(e,t,r,o){if(!Ga(e))return e;let n=typeof e.type=="string"&&Object.hasOwn(kb,e.type)?kb[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))n.has(i)||kg(i)?s[i]=a:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?JR.has(e.format)?(typeof a!="string"||!DR(e.format,a,r))&&o.push(`${t}.${i}`):s[i]=a:o.push(`${t}.${i}`);return s}function WR(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))n==="properties"&&Ga(s)?r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,BR(a,`properties.${i}`,t,o)])):VR.has(n)?r[n]=s:kg(n)||o.push(n);if(o.length>0)throw new se(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function KR(e,t){if(!Ga(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Ju(Dn,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function Sg(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,n)=>Sg(o,t[n],`${r}[${n}]`)):!Ga(e)||!Ga(t)?[]:Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Sg(n,t[o],s):kg(o)?[]:[s]})}function GR(e){if(!fg(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=WR(FR(e.requestedSchema),t),o=Ju(So.shape.requestedSchema,r);if(!o.success)throw new se(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${KR(r,o.error.message)}`);let n=Sg(r,o.data);if(n.length>0)throw new se(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter(i=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new se(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function YR(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var ck=Object.assign(YR,{elicit(e){try{return{method:"elicitation/create",params:GR(e)}}catch(t){throw t instanceof se?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var XR=!0,QR=10,ex=250;function py(e){return{autoFulfill:e?.autoFulfill??XR,maxRounds:e?.maxRounds??QR}}function tx(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;return!o&&r===void 0?e:{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function rx(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function ox(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof A?t.reason:new A(q.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof A?t.reason:new A(q.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function nx(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:o=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function sx(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),c=e.firstPayload,u=0;for(;;){if(u+=1,u>t.maxRounds)throw new A(q.InputRequiredRoundsExceeded,rx(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:c.inputRequests,...c.requestState!==void 0&&{requestState:c.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(c.inputRequests??{}),h;if(d.length>0){let y=nx(i);try{let v=await Promise.all(d.map(async([z,U])=>{try{return[z,await s.dispatchInputRequest(z,U,y.signal)]}catch(H){throw y.abort(H),H}}));h=Object.fromEntries(v)}finally{y.dispose()}}else await ox(ex,i);let m={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let y=Date.now()-a,v=n.maxTotalTimeout-y;if(v<=0)throw new A(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:y});m.maxTotalTimeout=v}let g=await s.retry(tx(o,h,c.requestState),m);if(sy(g)){c={inputRequests:g.inputRequests??{},...g.requestState!==void 0&&{requestState:g.requestState}};continue}return g}}var ix=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],ax={IdJagTokenExchangeResponseSchema:Fa,OAuthClientInformationFullSchema:Bn,OAuthClientInformationSchema:Va,OAuthClientMetadataSchema:Ha,OAuthClientRegistrationErrorSchema:Au,OAuthErrorResponseSchema:Jn,OAuthMetadataSchema:_o,OAuthProtectedResourceMetadataSchema:Fn,OAuthTokenRevocationRequestSchema:Mu,OAuthTokensSchema:Vn,OpenIdProviderDiscoveryMetadataSchema:Hn,OpenIdProviderMetadataSchema:Da},hy={},my={};function fy(e,t){let r=e.slice(0,-6);hy[r]=t,my[r]=o=>t.safeParse(o).success}for(let e of ix)fy(e,xR[e]);for(let[e,t]of Object.entries(ax))fy(e,t);var cx=Object.freeze(hy),gy=Object.freeze(my);function lx(e){switch(e){case"initialize":case"notifications/initialized":return sr(void 0);case"server/discover":return sr(Vu);default:return}}var Bu=6e4,ux=[Xt,gn,oo,Sn],dx=["inputResponses","requestState"];function $b(e,t){let r=e.params;if(!Ka(r))return{message:e,lifted:{}};let o=r._meta,n=Ka(o)?ux.filter(c=>c in o):[],s=t==="request"?dx.filter(c=>c in r):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ka(o)){let c={},u={...o};for(let d of n)c[d]=o[d],delete u[d];i.envelope=c,Object.keys(u).length>0?a._meta=u:delete a._meta}for(let c of s)c==="inputResponses"&&(i.inputResponses=a[c]),c==="requestState"&&(i.requestState=a[c]),delete a[c];return{message:{...e,params:a},lifted:i}}function Cb(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);return n.ok?{value:n.value}:{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function $g(e){return()=>e}var px=$g(void 0),hx,Wu=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{hx=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??pu,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new A(q.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new A(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=n=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{o?.(n,s),Kn(n)||Gn(n)?this._onresponse(n):vo(n)?this._onrequest(n,s):ny(n)?this._onnotification(n,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new A(q.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=$b(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=Rb(t.classification);if(i!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(dg(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;n===void 0&&s===void 0||Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=$b(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(v,z,U)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:v,message:z,...U!==void 0&&{data:U}}};s?.send(H).catch(T=>this._onerror(new Error(`Failed to send an error response: ${T}`)))};if(t?.classification!==void 0){let v=Rb(t.classification);if(v!==n.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${v} but this instance serves ${n.era}`));let z=t.classification.revision??v;i(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${z}`,{supported:this._supportedProtocolVersions,requested:z});return}}if(ug(r.method)&&!n.hasRequestMethod(r.method)&&!(xb(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(W.MethodNotFound,"Method not found");return}let c=n.checkInboundEnvelope(o);if(c!==void 0){i(W.InvalidParams,c);return}let u=(v,z)=>this._notificationViaCodec(this._resolveOutboundCodec(v.method),v,{...z,relatedRequestId:r.id}),d=(v,z,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(v.method),v,z,{...U,relatedRequestId:r.id}),h=new AbortController;this._requestHandlerAbortControllers.set(r.id,h);let m=o.inputResponses===void 0?void 0:mx(o.inputResponses),g={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...m!==void 0&&{inputResponses:m.accepted},...m!==void 0&&m.droppedKeys.length>0&&{droppedInputResponseKeys:m.droppedKeys},requestState:o.requestState===void 0?px:$g(o.requestState),signal:h.signal,send:((v,z,U)=>{let H=this._resolveOutboundCodec(v.method);if(this._assertOutboundRequestInEra(H,v.method),fg(z))return d(v,z,U);let T=Cb(H,v.method);if(T===void 0)throw new TypeError(`'${v.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(v,T,z)}),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},y=this.buildContext(g,t);Promise.resolve().then(()=>a(r,y)).then(async v=>{if(h.signal.aborted)return;let z;try{z=n.encodeResult(r.method,v,this._outboundServerInfo())}catch(H){this._onerror(new Error(`Failed to encode result for ${r.method}: ${H}`)),i(W.InternalError,"Internal error");return}let U={result:z,jsonrpc:"2.0",id:r.id};await s?.send(U)},async v=>{if(h.signal.aborted)return;let z=Number.isSafeInteger(v.code)?v.code:W.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(z),message:v.message??"Internal error",...v.data!==void 0&&{data:v.data}}};await s?.send(U)}).catch(v=>this._onerror(new Error(`Failed to send response: ${v}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===h&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Kn(e)?r(e):r(se.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(fg(t))return xb(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r);this._assertOutboundRequestInEra(o,e.method);let n=Cb(o,e.method);if(n===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return sr(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=lx(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(ug(t)&&!e.hasRequestMethod(t))throw new A(q.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},c=Date.now(),u,d;return new Promise((h,m)=>{let g=w=>{m(w)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){g(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof A?w:new A(q.RequestTimeout,String(w))}let y=e.era===Vu&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,v=this._requestMessageId++;d=v;let z={...t,jsonrpc:"2.0",id:v};o?.onprogress&&(this._progressHandlers.set(v,o.onprogress),z.params={...t.params,_meta:{...t.params?._meta,progressToken:v}});let U=this._envelopeOutbound(z),H=!1,T=w=>{H||(this._progressHandlers.delete(v),y===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(w)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(F=>this._onerror(new Error(`Failed to send cancellation: ${F}`))):y.abort(),m(w instanceof A?w:new A(q.RequestTimeout,String(w))))};this._responseHandlers.set(v,w=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return m(w);let F;try{F=e.decodeResult(t.method,w.result)}catch(te){return m(te instanceof Error?te:new Error(String(te)))}if(F.kind==="invalid")return m(F.error);if(F.kind==="input_required"){if(o?.allowInputRequired===!0)return h(_x(F));let te={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:c,retry:(de,Oe)=>this._requestWithSchemaViaCodec(e,de===void 0?{method:t.method}:{method:t.method,params:de},r,Oe)};return h(this._resolveNonCompleteResult(F,te))}let oe=F.result;pg(r,oe).then(te=>{te.success?h(te.data):m(new A(q.InvalidResult,`Invalid result for ${t.method}: ${te.error}`))},m)}),u=()=>T(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let D=o?.timeout??Bu,x=()=>T(new A(q.RequestTimeout,"Request timed out",{timeout:D}));this._setupTimeout(v,D,o?.maxTotalTimeout,x,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:y?.signal}).catch(w=>{this._progressHandlers.delete(v),m(w)})}).finally(()=>{u&&o?.signal?.removeEventListener("abort",u),d!==void 0&&(this._responseHandlers.delete(d),this._cleanupTimeout(d))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new A(q.NotConnected,"Not connected");if(dg(t.method)&&!e.hasNotificationMethod(t.method))throw new A(q.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,r).catch(n=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!ug(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era"&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason==="not-in-era"?new se(W.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await pg(t.params,{...n.params});if(!i.success)throw new se(W.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!dg(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new se(W.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let n=await pg(t.params,{...o.params});if(!n.success)throw new se(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ka(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sy(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ka(i)&&Ka(s)?{...i,...s}:s}return r}function Fu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mx(e){let t={},r=[];if(!Fu(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!Fu(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Ib(e){throw new A(q.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function fx(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:$g(void 0),signal:o,send:(()=>Ib("send")),notify:()=>Ib("notify")}}}async function gx(e,t,r,o,n){if(!Fu(o)||typeof o.method!="string")throw new A(q.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new A(q.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new A(q.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=Fu(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(fx(r,s,a,n,e.sessionId)))}function Sx(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function _y(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,c={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,h,m)=>gx(e,n,d,h,m),retry:(d,h)=>o.retry(d,Sx(i,h))};return sx({config:t,method:s.method,originalParams:s.params,firstPayload:c,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function _x(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var bx=fS((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw new TypeError("argument string is required");var c=typeof a=="object"?s(a):a;if(typeof c!="string")throw new TypeError("argument string is required to be a string");var u=c.indexOf(";"),d=u!==-1?c.slice(0,u).trim():c.trim();if(!o.test(d))throw new TypeError("invalid media type");var h=new i(d.toLowerCase());if(u!==-1){var m,g,y;for(t.lastIndex=u;g=t.exec(c);){if(g.index!==u)throw new TypeError("invalid parameter format");u+=g[0].length,m=g[1].toLowerCase(),y=g[2],y.charCodeAt(0)===34&&(y=y.slice(1,-1),y.indexOf("\\")!==-1&&(y=y.replace(r,"$1"))),h.parameters[m]=y}if(u!==c.length)throw new TypeError("invalid parameter format")}return h}function s(a){var c;if(typeof a.getHeader=="function"?c=a.getHeader("content-type"):typeof a.headers=="object"&&(c=a.headers&&a.headers["content-type"]),typeof c!="string")throw new TypeError("content-type header is missing from object");return c}function i(a){this.parameters=Object.create(null),this.type=a}})),yx=SS(bx(),1);function by(e){if(e)try{return yx.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var vx=10*1024*1024;function Ob(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function yy(e=fetch,t){return t?async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Ob(t.headers),...Ob(o.headers)}:t.headers}):e}var zx=new Set([301,302,303,307,308]),wx=5;function Rx(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function vy(e,t){let r=zx.has(t.status)?t.headers?.get("location"):void 0;if(r)try{return new URL(r,e)}catch{return}}var zy=new WeakSet;function wy(e){let t=(r,o)=>e(r,o);return zy.add(t),t}function Xa(e){return zy.has(e)?e:async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=vy(n,i);if(!a||s===wx)return i;let c=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===c.username&&a.password===c.password;if(!u||!d||!Rx(c,a))return i;await i.text?.().catch(()=>{}),n=a}}}function Ry(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=vy(t.url||e,t);if(r)return r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:"?(r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`):`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function Qa(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!Qa(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!Qa(e[s],t[s]))return!1;return!0}return e===t}function yt(e){return encodeURI(xx(e))}function xx(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Px={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Tx={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ex={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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},kx=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function zo(e,t=Object.create(null),r=kx,o=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",o===""?r=i:zo(e,t,r))}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw new Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(Ex[s])continue;let i=`${o}/${yt(s)}`,a=e[s];if(Array.isArray(a)){if(Px[s]){let c=a.length;for(let u=0;u<c;u++)zo(a[u],t,r,`${i}/${u}`)}}else if(Tx[s])for(let c in a)zo(a[c],t,r,`${i}/${yt(c)}`);else zo(a,t,r,i)}return t}var $x=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cx=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ix=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Ox=/^(?=.{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,Nx=/^(?:[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,qx=/^(?:(?:[^\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,Ax=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Mx=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,jx=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Lx=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ux=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Zx=e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(n=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},Dx=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Fx=/^((([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,Hx=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Zt(e){return e.test.bind(e)}var xy={date:Py,time:Ty.bind(void 0,!1),"date-time":Bx,duration:Hx,uri:Gx,"uri-reference":Zt(Nx),"uri-template":Zt(qx),url:Zt(Ax),email:Zx,hostname:Zt(Ox),ipv4:Zt(Dx),ipv6:Zt(Fx),regex:Xx,uuid:Zt(Mx),"json-pointer":Zt(jx),"json-pointer-uri-fragment":Zt(Lx),"relative-json-pointer":Zt(Ux)};function Vx(e){return e%4===0&&(e%100!==0||e%400===0)}function Py(e){let t=e.match($x);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Vx(r)?29:Cx[o])}function Ty(e,t){let r=t.match(Ix);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var Jx=/t|\s/i;function Bx(e){let t=e.split(Jx);return t.length==2&&Py(t[0])&&Ty(!0,t[1])}var Wx=/\/|:/,Kx=/^(?:[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 Gx(e){return Wx.test(e)&&Kx.test(e)}var Yx=/[^\\]\\Z/;function Xx(e){if(Yx.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function Qx(e){let t=0,r=e.length,o=0,n;for(;o<r;)t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r&&(n=e.charCodeAt(o),(n&64512)==56320&&o++);return t}function fe(e,t,r="2019-09",o=zo(t),n=!0,s=null,i="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":e===null?d="null":Array.isArray(e)?d="array":d="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:h,$recursiveRef:m,$recursiveAnchor:g,type:y,const:v,enum:z,required:U,not:H,anyOf:T,allOf:D,oneOf:x,if:w,then:F,else:oe,format:te,properties:de,patternProperties:Oe,additionalProperties:ie,unevaluatedProperties:ue,minProperties:xe,maxProperties:Ne,propertyNames:wt,dependentRequired:Fe,dependentSchemas:st,dependencies:Rt,prefixItems:Ge,items:qe,additionalItems:Ht,unevaluatedItems:Vt,contains:xt,minContains:Ee,maxContains:Ae,minItems:Me,maxItems:ht,uniqueItems:Mr,minimum:Ye,maximum:Xe,exclusiveMinimum:He,exclusiveMaximum:it,multipleOf:at,minLength:Pt,maxLength:Tt,pattern:ur,__absolute_ref__:Et,__absolute_recursive_ref__:jr}=t,O=[];if(g===!0&&s===null&&(s=t),m==="#"){let V=s===null?o[jr]:s,M=`${a}/$recursiveRef`,X=fe(e,s===null?t:s,r,o,n,V,i,M,c);X.valid||O.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...X.errors)}if(h!==void 0){let V=o[Et||h];if(V===void 0){let N=`Unresolved $ref "${h}".`;throw Et&&Et!==h&&(N+=` Absolute URI "${Et}".`),N+=`
66
66
  Known schemas:
67
67
  - ${Object.keys(o).join(`
68
- - `)}`,new Error(O)}let M=`${a}/$ref`,Q=ge(e,H,r,o,n,s,i,M,l);if(Q.valid||I.push({instanceLocation:i,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...Q.errors),r==="4"||r==="7")return{valid:I.length===0,errors:I}}if(Array.isArray(v)){let H=v.length,M=!1;for(let Q=0;Q<H;Q++)if(d===v[Q]||v[Q]==="integer"&&d==="number"&&e%1===0&&e===e){M=!0;break}M||I.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v.join('", "')}".`})}else v==="integer"?(d!=="number"||e%1||e!==e)&&I.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`}):v!==void 0&&d!==v&&I.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`});if(w!==void 0&&(d==="object"||d==="array"?Ya(e,w)||I.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(w)}.`}):e!==w&&I.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(w)}.`})),y!==void 0&&(d==="object"||d==="array"?y.some(H=>Ya(e,H))||I.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(H=>e===H)||I.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),W!==void 0){let H=`${a}/not`;ge(e,W,r,o,n,s,i,H).valid&&I.push({instanceLocation:i,keyword:"not",keywordLocation:H,error:'Instance matched "not" schema.'})}let Ct=[];if(N!==void 0){let H=`${a}/anyOf`,M=I.length,Q=!1;for(let O=0;O<N.length;O++){let E=N[O],J=Object.create(l),V=ge(e,E,r,o,n,g===!0?s:null,i,`${H}/${O}`,J);I.push(...V.errors),Q=Q||V.valid,V.valid&&Ct.push(J)}Q?I.length=M:I.splice(M,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:H,error:"Instance does not match any subschemas."})}if(F!==void 0){let H=`${a}/allOf`,M=I.length,Q=!0;for(let O=0;O<F.length;O++){let E=F[O],J=Object.create(l),V=ge(e,E,r,o,n,g===!0?s:null,i,`${H}/${O}`,J);I.push(...V.errors),Q=Q&&V.valid,V.valid&&Ct.push(J)}Q?I.length=M:I.splice(M,0,{instanceLocation:i,keyword:"allOf",keywordLocation:H,error:"Instance does not match every subschema."})}if(x!==void 0){let H=`${a}/oneOf`,M=I.length,Q=x.filter((O,E)=>{let J=Object.create(l),V=ge(e,O,r,o,n,g===!0?s:null,i,`${H}/${E}`,J);return I.push(...V.errors),V.valid&&Ct.push(J),V.valid}).length;Q===1?I.length=M:I.splice(M,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:H,error:`Instance does not match exactly one subschema (${Q} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...Ct),z!==void 0){let H=`${a}/if`;if(ge(e,z,r,o,n,s,i,H,l).valid){if(Z!==void 0){let M=ge(e,Z,r,o,n,s,i,`${a}/then`,l);M.valid||I.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "then" schema.'},...M.errors)}}else if(oe!==void 0){let M=ge(e,oe,r,o,n,s,i,`${a}/else`,l);M.valid||I.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "else" schema.'},...M.errors)}}if(d==="object"){if(D!==void 0)for(let O of D)O in e||I.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${O}".`});let H=Object.keys(e);if(we!==void 0&&H.length<we&&I.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${we} properties.`}),Ae!==void 0&&H.length>Ae&&I.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Ae} properties.`}),xt!==void 0){let O=`${a}/propertyNames`;for(let E in e){let J=`${i}/${zt(E)}`,V=ge(E,xt,r,o,n,s,J,O);V.valid||I.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:O,error:`Property name "${E}" does not match schema.`},...V.errors)}}if(Je!==void 0){let O=`${a}/dependantRequired`;for(let E in Je)if(E in e){let J=Je[E];for(let V of J)V in e||I.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:O,error:`Instance has "${E}" but does not have "${V}".`})}}if(ct!==void 0)for(let O in ct){let E=`${a}/dependentSchemas`;if(O in e){let J=ge(e,ct[O],r,o,n,s,i,`${E}/${zt(O)}`,l);J.valid||I.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:E,error:`Instance has "${O}" but does not match dependant schema.`},...J.errors)}}if(Pt!==void 0){let O=`${a}/dependencies`;for(let E in Pt)if(E in e){let J=Pt[E];if(Array.isArray(J))for(let V of J)V in e||I.push({instanceLocation:i,keyword:"dependencies",keywordLocation:O,error:`Instance has "${E}" but does not have "${V}".`});else{let V=ge(e,J,r,o,n,s,i,`${O}/${zt(E)}`);V.valid||I.push({instanceLocation:i,keyword:"dependencies",keywordLocation:O,error:`Instance has "${E}" but does not match dependant schema.`},...V.errors)}}}let M=Object.create(null),Q=!1;if(pe!==void 0){let O=`${a}/properties`;for(let E in pe){if(!(E in e))continue;let J=`${i}/${zt(E)}`,V=ge(e[E],pe[E],r,o,n,s,J,`${O}/${zt(E)}`);if(V.valid)l[E]=M[E]=!0;else if(Q=n,I.push({instanceLocation:i,keyword:"properties",keywordLocation:O,error:`Property "${E}" does not match schema.`},...V.errors),Q)break}}if(!Q&&Ne!==void 0){let O=`${a}/patternProperties`;for(let E in Ne){let J=new RegExp(E,"u"),V=Ne[E];for(let ve in e){if(!J.test(ve))continue;let Ur=`${i}/${zt(ve)}`,It=ge(e[ve],V,r,o,n,s,Ur,`${O}/${zt(E)}`);It.valid?l[ve]=M[ve]=!0:(Q=n,I.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:O,error:`Property "${ve}" matches pattern "${E}" but does not match associated schema.`},...It.errors))}}}if(!Q&&ae!==void 0){let O=`${a}/additionalProperties`;for(let E in e){if(M[E])continue;let J=`${i}/${zt(E)}`,V=ge(e[E],ae,r,o,n,s,J,O);V.valid?l[E]=!0:(Q=n,I.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:O,error:`Property "${E}" does not match additional properties schema.`},...V.errors))}}else if(!Q&&de!==void 0){let O=`${a}/unevaluatedProperties`;for(let E in e)if(!l[E]){let J=`${i}/${zt(E)}`,V=ge(e[E],de,r,o,n,s,J,O);V.valid?l[E]=!0:I.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:O,error:`Property "${E}" does not match unevaluated properties schema.`},...V.errors)}}}else if(d==="array"){ft!==void 0&&e.length>ft&&I.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${ft}).`}),je!==void 0&&e.length<je&&I.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${je}).`});let H=e.length,M=0,Q=!1;if(Qe!==void 0){let O=`${a}/prefixItems`,E=Math.min(Qe.length,H);for(;M<E;M++){let J=ge(e[M],Qe[M],r,o,n,s,`${i}/${M}`,`${O}/${M}`);if(l[M]=!0,!J.valid&&(Q=n,I.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:O,error:"Items did not match schema."},...J.errors),Q))break}}if(qe!==void 0){let O=`${a}/items`;if(Array.isArray(qe)){let E=Math.min(qe.length,H);for(;M<E;M++){let J=ge(e[M],qe[M],r,o,n,s,`${i}/${M}`,`${O}/${M}`);if(l[M]=!0,!J.valid&&(Q=n,I.push({instanceLocation:i,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...J.errors),Q))break}}else for(;M<H;M++){let E=ge(e[M],qe,r,o,n,s,`${i}/${M}`,O);if(l[M]=!0,!E.valid&&(Q=n,I.push({instanceLocation:i,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...E.errors),Q))break}if(!Q&&Vt!==void 0){let E=`${a}/additionalItems`;for(;M<H;M++){let J=ge(e[M],Vt,r,o,n,s,`${i}/${M}`,E);l[M]=!0,J.valid||(Q=n,I.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:E,error:"Items did not match additional items schema."},...J.errors))}}}if(Tt!==void 0)if(H===0&&Ee===void 0)I.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ee!==void 0&&H<Ee)I.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${H}) than minContains (${Ee}).`});else{let O=`${a}/contains`,E=I.length,J=0;for(let V=0;V<H;V++){let ve=ge(e[V],Tt,r,o,n,s,`${i}/${V}`,O);ve.valid?(l[V]=!0,J++):I.push(...ve.errors)}J>=(Ee||0)&&(I.length=E),Ee===void 0&&Me===void 0&&J===0?I.splice(E,0,{instanceLocation:i,keyword:"contains",keywordLocation:O,error:"Array does not contain item matching schema."}):Ee!==void 0&&J<Ee?I.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Ee} items matching schema. Only ${J} items were found.`}):Me!==void 0&&J>Me&&I.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Me} items matching schema. ${J} items were found.`})}if(!Q&&Jt!==void 0){let O=`${a}/unevaluatedItems`;for(;M<H;M++){if(l[M])continue;let E=ge(e[M],Jt,r,o,n,s,`${i}/${M}`,O);l[M]=!0,E.valid||I.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:O,error:"Items did not match unevaluated items schema."},...E.errors)}}if(jr)for(let O=0;O<H;O++){let E=e[O],J=typeof E=="object"&&E!==null;for(let V=0;V<H;V++){if(O===V)continue;let ve=e[V];(E===ve||J&&typeof ve=="object"&&ve!==null&&Ya(E,ve))&&(I.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${O} and ${V}.`}),O=Number.MAX_SAFE_INTEGER,V=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(r==="4"?(et!==void 0&&(Be===!0&&e<=et||e<et)&&I.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Be?"or equal to ":""} ${et}.`}),tt!==void 0&&(lt===!0&&e>=tt||e>tt)&&I.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${lt?"or equal to ":""} ${tt}.`})):(et!==void 0&&e<et&&I.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${et}.`}),tt!==void 0&&e>tt&&I.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${tt}.`}),Be!==void 0&&e<=Be&&I.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Be}.`}),lt!==void 0&&e>=lt&&I.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${lt}.`})),ut!==void 0){let H=e%ut;Math.abs(0-H)>=11920929e-14&&Math.abs(ut-H)>=11920929e-14&&I.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${ut}.`})}}else if(d==="string"){let H=Et===void 0&&kt===void 0?0:qx(e);Et!==void 0&&H<Et&&I.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${H} < ${Et}).`}),kt!==void 0&&H>kt&&I.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${H} > ${kt}).`}),dr!==void 0&&!new RegExp(dr,"u").test(e)&&I.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),te!==void 0&&hy[te]&&!hy[te](e)&&I.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${te}".`})}return{valid:I.length===0,errors:I}}var Mx=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Ro(e)}validate(e){return ge(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Ro(e,this.lookup)}},Pg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=lS(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Mx(e,this.draft??this._draftFor(e),this.shortcircuit);return r=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map(n=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Sy=!0;var Tg;Tg=globalThis.crypto;async function jx(e){return(await Tg).getRandomValues(new Uint8Array(e))}async function Lx(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let n=await jx(e-o.length);for(let s of n)s<r&&(o+=t[s%t.length])}return o}async function Ux(e){return await Lx(e)}async function Zx(e){let t=await(await Tg).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Eg(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ux(e),r=await Zx(t);return{code_verifier:t,code_challenge:r}}var Xa=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},_y=10,Dx=13,wo=32;function kg(e){}function vy(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=kg,onError:r=kg,onRetry:o=kg,onComment:n,maxBufferSize:s}=e,i=[],a=0,l=!0,u,d="",m=0,h,g=!1;function v(x){if(g)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,x.charCodeAt(0)===239&&x.charCodeAt(1)===187&&x.charCodeAt(2)===191&&(x=x.slice(3))),i.length===0){let oe=y(x);oe!==""&&(i.push(oe),a=oe.length),w();return}if(x.indexOf(`
69
- `)===-1&&x.indexOf("\r")===-1){i.push(x),a+=x.length,w();return}i.push(x);let z=i.join("");i.length=0,a=0;let Z=y(z);Z!==""&&(i.push(Z),a=Z.length),w()}function w(){s!==void 0&&(a+d.length<=s||(g=!0,i.length=0,a=0,u=void 0,d="",m=0,h=void 0,r(new Xa(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(x){let z=0;if(x.indexOf("\r")===-1){let Z=x.indexOf(`
70
- `,z);for(;Z!==-1;){if(z===Z){m>0&&t({id:u,event:h,data:d}),u=void 0,d="",m=0,h=void 0,z=Z+1,Z=x.indexOf(`
71
- `,z);continue}let oe=x.charCodeAt(z);if(by(x,z,oe)){let te=x.charCodeAt(z+5)===wo?z+6:z+5,pe=x.slice(te,Z);if(m===0&&x.charCodeAt(Z+1)===_y){t({id:u,event:h,data:pe}),u=void 0,d="",h=void 0,z=Z+2,Z=x.indexOf(`
72
- `,z);continue}d=m===0?pe:`${d}
73
- ${pe}`,m++}else yy(x,z,oe)?h=x.slice(x.charCodeAt(z+6)===wo?z+7:z+6,Z)||void 0:D(x,z,Z);z=Z+1,Z=x.indexOf(`
74
- `,z)}return x.slice(z)}for(;z<x.length;){let Z=x.indexOf("\r",z),oe=x.indexOf(`
75
- `,z),te=-1;if(Z!==-1&&oe!==-1?te=Z<oe?Z:oe:Z!==-1?Z===x.length-1?te=-1:te=Z:oe!==-1&&(te=oe),te===-1)break;D(x,z,te),z=te+1,x.charCodeAt(z-1)===Dx&&x.charCodeAt(z)===_y&&z++}return x.slice(z)}function D(x,z,Z){if(z===Z){N();return}let oe=x.charCodeAt(z);if(by(x,z,oe)){let we=x.charCodeAt(z+5)===wo?z+6:z+5,Ae=x.slice(we,Z);d=m===0?Ae:`${d}
76
- ${Ae}`,m++;return}if(yy(x,z,oe)){h=x.slice(x.charCodeAt(z+6)===wo?z+7:z+6,Z)||void 0;return}if(oe===105&&x.charCodeAt(z+1)===100&&x.charCodeAt(z+2)===58){let we=x.slice(x.charCodeAt(z+3)===wo?z+4:z+3,Z);we.includes("\0")||(u=we);return}if(oe===58){if(n){let we=x.slice(z,Z);n(we.slice(x.charCodeAt(z+1)===wo?2:1))}return}let te=x.slice(z,Z),pe=te.indexOf(":");if(pe===-1){W(te,"",te);return}let Ne=te.slice(0,pe),ae=te.charCodeAt(pe+1)===wo?2:1,de=te.slice(pe+ae);W(Ne,de,te)}function W(x,z,Z){switch(x){case"event":h=z||void 0;break;case"data":d=m===0?z:`${d}
77
- ${z}`,m++;break;case"id":z.includes("\0")||(u=z);break;case"retry":/^\d+$/.test(z)?o(parseInt(z,10)):r(new Xa(`Invalid \`retry\` value: "${z}"`,{type:"invalid-retry",value:z,line:Z}));break;default:r(new Xa(`Unknown field "${x.length>20?`${x.slice(0,20)}\u2026`:x}"`,{type:"unknown-field",field:x,value:z,line:Z}));break}}function N(){m>0&&t({id:u,event:h,data:d}),u=void 0,d="",m=0,h=void 0}function F(x={}){if(x.consume&&i.length>0){let z=i.join("");D(z,0,z.length)}l=!0,u=void 0,d="",m=0,h=void 0,i.length=0,a=0,g=!1}return{feed:v,reset:F}}function by(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function yy(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Vu=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let s;super({start(i){s=vy({onEvent:a=>{i.enqueue(a)},onError(a){typeof t=="function"&&t(a),(t==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:o,maxBufferSize:n})},transform(i){s.feed(i)}})}};var ec=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return at(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,e)}constructor(e){super(e),this.name=new.target.name,yo(this,new.target)}},qg=class extends ec{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},Fx=class extends ec{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Ny=class extends ec{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Wu=class extends ec{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},zy=class extends ec{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Mg(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Ay(e.issuer,t)?e:void 0}function Ay(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Hx(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function Vx(e,t,r){let{resourceMetadataUrl:o,scope:n}=Qa(t.response);if(await jg(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new Ht}function Jx(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async r=>Vx(e,r,t)}}var Ht=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return at(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",yo(this,new.target)}};function Ug(e){return e?.authorization_response_iss_parameter_supported===!0}function Zg({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new qg("authorization_response",t,void 0);return}if(e!==t)throw new qg("authorization_response",t,e)}}function $g(...e){let t=new Set;for(let r of e)if(r)for(let o of r.split(/\s+/))o&&t.add(o);return t.size>0?[...t].join(" "):void 0}function Bx(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Wx(e,t,r,o,n){if(typeof e=="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Uy(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new Ht("Authorization callback failed and the issuer could not be verified");Zg({iss:s,expectedIssuer:a.issuer,issParameterSupported:Ug(a)});let l=e.get("error");throw l?new vo(l,e.get("error_description")??l,e.get("error_uri")??void 0):new Ht("Authorization callback contained neither `code` nor `error`")}function Kx(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Cg="code",Ig="S256";function Gx(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Kx(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Yx(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":Xx(n,s,r);return;case"client_secret_post":Qx(n,s,o);return;case"none":eP(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Xx(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Qx(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function eP(e,t){t.set("client_id",e)}function qy(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function tP(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!qy(t.hostname))throw new Ny(t.href);return t}function rP(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||qy(r.hostname))return"native"}return"web"}function oP(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??rP(t.redirect_uris)}}async function Ry(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Wn.parse(JSON.parse(r));return vo.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new vo(ar.ServerError,n)}}function wy(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${o}. Cause: ${JSON.stringify(t.message)}`)}async function jg(e,t){try{return await Og(e,t)}catch(r){if(r instanceof vo){if(r.code===ar.InvalidClient||r.code===ar.UnauthorizedClient)return wy(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Og(e,t);if(r.code===ar.InvalidGrant||r.code===ar.InvalidDpopProof)return wy(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Og(e,t)}throw r}}function nP(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}async function Og(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=oP(e),d=await e.discoveryState?.(),m,h,g,v,w=s;if(!w&&d?.resourceMetadataUrl&&(w=new URL(d.resourceMetadataUrl)),d?.authorizationServerUrl){if(h=d.authorizationServerUrl,m=d.resourceMetadata,g=d.authorizationServerMetadata??await Ly(h,{fetchFn:i,skipIssuerValidation:a}),!m)try{m=await My(t,{resourceMetadataUrl:w},i)}catch(ae){if(ae instanceof TypeError)throw ae}(g!==d.authorizationServerMetadata||m!==d.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(h),resourceMetadataUrl:w?.toString(),resourceMetadata:m,authorizationServerMetadata:g})}else{let ae=await Uy(t,{resourceMetadataUrl:w,fetchFn:i,skipIssuerMetadataValidation:a});h=ae.authorizationServerUrl,g=ae.authorizationServerMetadata,m=ae.resourceMetadata,v={authorizationServerUrl:String(h),resourceMetadataUrl:w?.toString(),resourceMetadata:m,authorizationServerMetadata:g}}let y=g?.issuer??String(h),D={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),r!==void 0){let ae=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(ae===void 0){if(e.saveDiscoveryState!==void 0)throw new Wu("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Ay(ae,y))throw new Wu(ae,y)}v&&await e.saveDiscoveryState?.(v);let W=await iP(t,e,m),N=W&&m&&!e.validateResourceURL?m.resource:W;N&&await e.saveResourceUrl?.(Dg(N));let F=nP({requestedScope:n,resourceMetadata:m,authServerMetadata:g,clientMetadata:e.clientMetadata}),x=await Promise.resolve(e.clientInformation(D)),z=Mg(x,y,{canPersistStamp:e.saveClientInformation!==void 0});if(z===void 0&&x?.issuer&&e.saveClientInformation===void 0)throw new Wu(x.issuer,y);if(z&&z.issuer===void 0&&(z={...z,issuer:y},await e.saveClientInformation?.(z,D)),!z){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let ae=g?.client_id_metadata_document_supported===!0,de=e.clientMetadataUrl;if(de&&!sP(de))throw new vo(ar.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${de}`);if(ae&&de)z={client_id:de,issuer:y},await e.saveClientInformation?.(z,D);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");z={...await gP(h,{metadata:g,clientMetadata:u,scope:F,fetchFn:i}),issuer:y},await e.saveClientInformation(z,D)}}let Z=!e.redirectUrl;if(r!==void 0||Z){r!==void 0&&Zg({iss:o,expectedIssuer:g?.issuer,issParameterSupported:Ug(g)});let ae=await fP(e,h,{metadata:g,resource:N,authorizationCode:r,iss:o,scope:F,fetchFn:i});return await e.saveTokens({...ae,issuer:y},D),"AUTHORIZED"}let oe=Mg(await e.tokens(D),y);if(oe&&oe.issuer===void 0&&(oe={...oe,issuer:y},await e.saveTokens(oe,D)),oe?.refresh_token&&!l){let ae;try{ae=await hP(h,{metadata:g,clientInformation:z,refreshToken:oe.refresh_token,resource:N,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(de){if(de instanceof Ny)throw de;if(!(de instanceof vo)||de.code===ar.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(de instanceof Error?de.message:String(de))}`);else throw de}if(ae)return await e.saveTokens({...ae,issuer:y},D),"AUTHORIZED"}let te=e.state?await e.state():void 0,{authorizationUrl:pe,codeVerifier:Ne}=await pP(h,{metadata:g,clientInformation:z,state:te,redirectUrl:e.redirectUrl,scope:F,resource:N});return await e.saveCodeVerifier(Ne),await e.redirectToAuthorization(pe),"REDIRECT"}function sP(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function iP(e,t,r){let o=wb(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!xb({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}var aP=new Set(["bearer","dpop"]);function Qa(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!aP.has(r.toLowerCase())||!o)return{};let n=Ju(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=Ju(e,"scope")||void 0,a=Ju(e,"error")||void 0,l=Ju(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:l}}function Ju(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function My(e,t,r=fetch){let o=await uP(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Vn.parse(await o.json())}async function jy(e,t,r=fetch){let o=Ga(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Sy)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function cP(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function xy(e,t,r=fetch){return await jy(e,{"MCP-Protocol-Version":t},r)}function lP(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}async function uP(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??Sn,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let l=cP(t,n.pathname);i=new URL(l,o?.metadataServerUrl??n),i.search=n.search}let a=await xy(i,s,r);return!o?.metadataUrl&&lP(a,n.pathname)&&(a=await xy(new URL(`/.well-known/${t}`,n),s,r)),a}function dP(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Ly(e,{fetchFn:t=fetch,protocolVersion:r=Sn,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=dP(e);for(let{url:i,type:a}of s){let l=await jy(i,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?bo.parse(await l.json()):Jn.parse(await l.json());if(!o){let d=typeof e=="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new qg("metadata",d,u.issuer)}return u}}async function Uy(e,t){let r,o;try{r=await My(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let n=await Ly(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Dg(e){return typeof e=="string"?e:e.href}async function pP(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Cg))throw new Error(`Incompatible auth server: does not support response type ${Cg}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ig))throw new Error(`Incompatible auth server: does not support code challenge method ${Ig}`)}else a=new URL("/authorize",e);let l=await Eg(),u=l.code_verifier,d=l.code_challenge;return a.searchParams.set("response_type",Cg),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Ig),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),n&&a.searchParams.set("scope",n),n?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",Dg(i)),{authorizationUrl:a,codeVerifier:u}}function mP(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Zy(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let l=tP(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",Dg(s)),!n&&o&&Yx(Gx(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let g=new Headers(u);return n&&await n(g,r,l,t),i&&g.set("DPoP",await i.buildProof({htm:"POST",htu:l})),Ga(a??fetch)(l,{method:"POST",headers:g,body:r})},m=await d();if(i&&m.status===400&&(await m.clone().json().catch(()=>{}))?.error===ar.UseDpopNonce&&(i.observeNonce(m,l),m=await d()),i?.observeNonce(m,l),!m.ok)throw await Ry(m);let h=await m.json();try{return Bn.parse(mg(h))}catch(g){throw typeof h=="object"&&h!==null&&"error"in h?await Ry(JSON.stringify(h)):g}}async function hP(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Zy(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function fP(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){n!==void 0&&Zg({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Ug(r)});let l=r?.issuer??String(t),u=async()=>{let g=await e.clientInformation({issuer:l}),v=Mg(g,l,{canPersistStamp:!1});if(g&&v===void 0)throw new Wu(String(g.issuer),l);return v},d=await u(),m=i??e.clientMetadata.scope,h;if(e.prepareTokenRequest&&(h=await e.prepareTokenRequest(m)),!h){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");h=mP(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Zy(t,{metadata:r,tokenRequestParams:h,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function gP(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Ga(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Fx({status:a.status,body:await a.text(),submittedMetadata:i});return Kn.parse(mg(await a.json()))}var Bu=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),SP=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Ng(e))}set(e,t){let r=Ng(e),o=Bu.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!Bu.has(i.slice(0,i.indexOf("\0")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;return this._entries.set(r,{...t,stamp:s}),n&&!o&&this._cappedSize++,s}delete(e){this._entries.delete(Ng(e))&&!Bu.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,r=Bu.has(e);for(let o of this._entries.keys())o.startsWith(t)&&(this._entries.delete(o),r||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function Ng(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function Ag(e,t){return t===void 0?e:`${e}\0${t}`}var _P=864e5,bP=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Ag(e,t),o=this._evictionGeneration.get(r);o!==void 0&&this._evictionGeneration.set(r,o+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Ag(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Ag(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:yP(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(!(r?.expiresAt===void 0||!(r.expiresAt>this.now())))try{let o=JSON.parse(r.value);if(typeof o!="object"||o===null||Array.isArray(o))throw new TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);i!==void 0&&n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(r=>r!==null&&typeof r=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function yP(e){let t;try{t=JSON.stringify(e)}catch(r){throw new TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Dy=Symbol.for("mcp.authSeamEscape");function mt(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,Dy,{value:!0,configurable:!0})}catch{}return e}function vP(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[Dy]===!0}var zP=-32022,RP=new Set([-32001,-32020,-32021]);function wP(e,t){switch(e.kind){case"result":return xP(e.result,t);case"rpc-error":return Fy(e,t);case"http-error":return PP(e,t);case"network-error":return Py(e.error,t);case"unusable-reply":return{kind:"error",error:new q(A.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Hy(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:Py(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new q(A.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function xP(e,t){let r=ir(Zu).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find(s=>o.includes(s));return n!==void 0?{kind:"modern",version:n,discover:r.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new Uu({supported:[...o],requested:t.requestedVersion})}}function Fy(e,t){let{code:r,message:o,data:n}=e;if(r===zP){let s=EP(n);if(s===void 0)return{kind:"legacy"};let i=new Uu({supported:s,requested:kP(n)??t.requestedVersion},o),a=Ka(s),l=t.clientModernVersions.find(u=>a.includes(u));return l!==void 0?{kind:"corrective",version:l,error:i}:a.length>0?{kind:"error",error:i}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}return RP.has(r)?{kind:"legacy"}:{kind:"legacy"}}function PP(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new Dt(o?A.ClientHttpForbidden:A.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new Dt(A.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=$P(e.body);return r!==void 0?Fy(r,t):{kind:"legacy"}}function Py(e,t){return t.environment==="browser"&&TP(e)?{kind:"legacy"}:{kind:"error",error:new q(A.EraNegotiationFailed,`Version negotiation probe failed: ${Hy(e)}`,{cause:e},{cause:e})}}function TP(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Hy(e){return e instanceof Error?e.message:String(e)}function EP(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r=="string")))return t}function kP(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function $P(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let r=t.error;if(typeof r!="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o=="number")return{code:o,message:typeof n=="string"?n:"",data:s}}var CP="legacy";function IP(e,t){let r=e?.mode??CP;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r=="object"){if(!cr(r.pin))throw new TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Ka(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...hg],fallbackAvailable:t?fg(t).length>0:!0,probe:o}}function Ty(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Ey(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var OP=class Vy{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new Vy(t);t.onmessage=o=>{let n=r._pending;if(n!==void 0&&(Yn(o)||Xn(o))&&o.id===n.id){r._pending=void 0,Yn(o)?n.resolve({kind:"response",result:o.result}):n.resolve({kind:"response",error:o.error});return}},t.onerror=o=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;o!==void 0&&(r._pending=void 0,o.resolve({kind:"closed"})),r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise(n=>{let s=!1,i=l=>{s||(s=!0,clearTimeout(a),this._pending?.id===o&&(this._pending=void 0),n(l))},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch(l=>i({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Lg.set(r,()=>{r.onclose===n&&(r.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Lg=new WeakMap;function ky(e){let t=Lg.get(e);Lg.delete(e),t?.()}function NP(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:ir(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function AP(e){return e instanceof q&&e.code===A.ClientHttpUnexpectedContent?!0:e instanceof Error&&e.name==="SyntaxError"}function qP(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(vP(r)||r instanceof Ht||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Dt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o=="string"?o:void 0,statusText:r.data.statusText}}return AP(r)?{kind:"unusable-reply",error:r}:{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Jy(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await OP.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let h=await i.exchange(w=>NP(w,u,t.clientInfo,t.capabilities),r);if(h.kind==="timeout"&&m>0){m--;continue}let g=qP(h,r),v=wP(g,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(v.kind){case"modern":return{era:"modern",version:v.version,discover:v.discover};case"corrective":if(d)throw v.error;d=!0,u=v.version;continue;case"legacy":{let w=g.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new q(A.EraNegotiationFailed,w===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${w} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new q(A.EraNegotiationFailed,w===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${w} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(w!==void 0&&t.disposableProbe!==!0)throw new q(A.EraNegotiationFailed,`Version negotiation failed: ${w} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw v.error}}},l;try{l=await a()}catch(u){throw i.detach(),u}return i.release(),l}function MP(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r=="object"&&r!==null&&typeof r.command=="string"?r:void 0}async function jP(e,t,r,o){let n=t.constructor,s=new n({...r,stderr:"ignore"}),i=t.close,a=!1,l,u=new Promise((m,h)=>{l=()=>h($y())});t.close=async function(){return a=!0,l?.(),i.call(t)};let d;try{let m=Jy(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await LP(s),t.close=i}if(a)throw $y();return d}function $y(){return new q(A.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function LP(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function Cy(e){let t=e._meta?.[er];return sy.Implementation(t)?t:void 0}function Ku(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,o=e.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&&Ku(s,r[n])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ku(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ku(r,t)}}function UP(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function ZP(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&$r.safeParse(e.discover).success))return e;throw new q(A.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Iy={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},DP=64,By=class extends Hu{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new q(A.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Pg,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=ty(t?.inputRequired),this._cache=new bP(t?.responseCacheStore??new SP,t?.responseCacheStore!==void 0,r=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??DP,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&cr(this._negotiatedProtocolVersion)&&zo(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?ay({getRequestHandler:r=>this._getRequestHandler(r),buildContext:r=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new q(A.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=iy(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(r,o)=>{let n=ir(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era"&&(s=n.validateInputRequest("elicitation/create",r)),!s.ok)throw new ie(s.reason==="not-in-era"?B.InternalError:B.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=UP(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new ie(B.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!l)throw new ie(B.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era"&&(d=n.validateInputResponse("elicitation/create",u)),!d.ok)throw new ie(d.reason==="not-in-era"?B.InternalError:B.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,h=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&m.action==="accept"&&m.content&&h&&this._capabilities.elicitation?.form?.applyDefaults)try{Ku(h,m.content)}catch{}return m}:e==="sampling/createMessage"?async(r,o)=>{let n=ir(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era"&&(s=n.validateInputRequest("sampling/createMessage",r)),!s.ok)throw new ie(s.reason==="not-in-era"?B.InternalError:B.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),l=!!(i.tools||i.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era"&&(u=n.validateInputResponse("sampling/createMessage",a)),!u.ok)throw new ie(u.reason==="not-in-era"?B.InternalError:B.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new q(A.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,ZP(t.prior),t);let r=IP(this._versionNegotiation,this._supportedProtocolVersionsOption);return r.kind!=="legacy"?this._connectNegotiated(e,r,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=fg(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new q(A.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;n!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=Ey(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ty(),defaultTimeoutMs:r?.timeout??Fu},i=n==="stdio"?MP(e):void 0;o=i===void 0?await Jy(t,{...s,transport:e,transportKind:n}):await jP(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),ky(e),n}if(ky(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Cy(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion&&e.setProtocolVersion(o.version),this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:new Error(String(u)))}let l=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);r?.signal?.aborted&&d(),r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:new Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Ka(n).length>0?Ka(n):hg).find(i=>o.supportedVersions.includes(i));if(s===void 0)throw new q(A.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=Cy(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return cr(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new q(A.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new q(A.CapabilityNotSupported,`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 q(A.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new q(A.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new q(A.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new q(A.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new q(A.CapabilityNotSupported,`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){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new q(A.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new q(A.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new q(A.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},$r,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);return r!==void 0?r:this._listAllPages("prompts/list",e,t,o=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/list",e,t,o=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/templates/list",e,t,o=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;for(;l!==void 0;){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new q(A.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}return delete a.nextCursor,n?.(a),s||await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs=="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),_P),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch(n=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof q?n:new q(A.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:zg(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);s.expiresAt>this._cache.now()?await this._cache.write("resources/read",n,o,s):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new q(A.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!cr(r))throw new q(A.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let N=t.signal.reason;throw N instanceof q?N:new q(A.RequestTimeout,String(N))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,l,u,d=new Promise((N,F)=>{l=N,u=F}),m,h=new Promise(N=>{m=N}),g=N=>{if(s==="closed")return;let F=s==="opening";if(i!==void 0&&(clearTimeout(i),i=void 0),"ack"in N){s="open",l(N.ack);return}s="closed",a!==void 0&&t?.signal?.removeEventListener("abort",a),this._listenState.delete(n),o.abort(),m(N.cause),F&&u(N.error??new q(A.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},v=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},w=async()=>{s!=="closed"&&(g({cause:"local"}),await v())};this._listenState.set(n,{settle:g});let y=t?.timeout??Fu;if(i=setTimeout(()=>{g({cause:"remote",error:new q(A.RequestTimeout,"subscriptions/listen ack timed out",{timeout:y})}),v().catch(()=>{})},y),t?.signal){let N=t.signal;a=()=>{if(s==="closed")return;let F=N.reason;g({cause:"local",error:F instanceof Error?F:new Error(String(F??"Aborted"))}),v().catch(()=>{})},N.addEventListener("abort",a,{once:!0})}let D={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},W=N=>{g({cause:"remote",error:N instanceof Error?N:new Error(String(N))})};try{this.transport.send(D,{requestSignal:o.signal,onRequestStreamEnd:()=>g({cause:"remote",error:new Error("subscriptions/listen: stream ended")})}).catch(W)}catch(N){W(N)}return{honoredFilter:await d,close:w,closed:h}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Iy,e.method)?Iy[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;typeof o=="string"&&this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[ui],n=typeof o=="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o=="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t=="string"?this._listenState.get(t):void 0;if(r!==void 0){Xn(e)?r.settle({cause:"remote",error:ie.fromError(e.error.code,e.error.message,e.error.data)}):r.settle({cause:"graceful",error:new q(A.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new q(A.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ty()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=Xb(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,l=>this._compileOutputValidator(l)).catch(l=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ie(B.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ie&&l.code===Gn;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch(m=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,m=>this._compileOutputValidator(m)).catch(m=>void this._reportStoreError(m)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new ie(B.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let l=a(i.structuredContent);if(!l.valid)throw new ie(B.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){throw l instanceof ie?l:new ie(B.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return i}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);return r!==void 0?r:this._listAllPages("tools/list",e,t,o=>o.tools,o=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Ey(this.transport)==="stdio")return;let t=e.tools.filter(r=>{let o=zg(r.inputSchema);return o.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${o.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,r,o){let n=Du(ia,r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:new Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let m=setTimeout(l,i);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function FP(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function HP(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return FP(t)&&/use_dpop_nonce/i.test(t)}var VP=(e,t)=>r=>{let o=typeof e=="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,s);let u=async()=>{let m=await t();if(!m)return r(n,s);let h=new Headers(s?.headers),g=await l.buildProof({htm:i,htu:a,accessToken:m});return h.set("Authorization",`DPoP ${m}`),h.set("DPoP",g),r(n,{...s,headers:h})},d=await u();return HP(d)&&d.headers.has("dpop-nonce")&&(l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u()),l.observeNonce(d,a),d}},JP=e=>VP(async()=>{try{return await e.dpop?.()}catch(t){throw mt(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw mt(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var kk=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return at(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return at(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,yo(this,new.target)}};var BP=1,WP={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},KP=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Oy(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var Wy=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Hx(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Jx(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=JP(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=ly(t?.fetch,t?.requestInit),this._redirectPolicy==="follow"&&(this._fetchWithInit=py(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??WP,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??BP)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw mt(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new zy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new zy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Dt(A.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),o=$g(this._scope,r?.scope,e.scope);this._scope=o;let n=Bx(o,r?.scope);return jg(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ga(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:my(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw mt(r)}return t&&e.set("Authorization",`Bearer ${t}`),this._sessionId&&e.set("mcp-session-id",this._sessionId),this._protocolVersion&&e.set("mcp-protocol-version",this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!zo(t))return;let r=t.params?._meta?.[Qt];if(typeof r!="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=Qb(t.method,t.params);o?.value!==void 0&&e.set("mcp-name",Rg(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!zo(e))return!1;let t=e.params?._meta?.[Qt];return typeof t=="string"&&cr(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map(m=>m.trim().toLowerCase())??[],"text/event-stream"];i.set("accept",[...new Set(a)].join(", ")),o&&i.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Oy(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:h,scope:g}=Qa(d);this._resourceMetadataUrl=h,this._scope=$g(this._scope,g)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(h){throw mt(h)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}throw await d.text?.().catch(()=>{}),mt(t?new Dt(A.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}):new Ht)}if(d.status===403){let{resourceMetadataUrl:h,scope:g,error:v,errorDescription:w}=Qa(d);if(v==="insufficient_scope"){let y=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:g,resourceMetadataUrl:h,errorDescription:w,statusText:d.statusText,text:y},r)!=="AUTHORIZED")throw mt(new Ht);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new Dt(A.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){throw s()||this.onerror?.(i),i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(s=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s=="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new Vu({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:v}=await h.read();if(v)break;if(g.id&&(l=g.id,u=!0,o?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let w=vt.parse(JSON.parse(g.data));(Yn(w)||Xn(w))&&(d=!0,n!==void 0&&(w.id=n)),this.onmessage?.(w)}catch(w){this.onerror?.(w)}}(r||u)&&!d&&this._abortController&&!a()?this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0):a()||i?.()}catch(h){if(a())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${h}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`)),i?.()}else i?.()}})()}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,t){if(!this._oauthProvider)throw new Ht("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Wx(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await jg(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Ht("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:zo(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(y=>this.onerror?.(y));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some(y=>vg(y)):vg(e);if(a&&i.delete("mcp-session-id"),t?.headers!==void 0)for(let[y,D]of Object.entries(t.headers))KP.has(y.toLowerCase())||i.set(y,D);i.set("content-type","application/json");let l=[...i.get("accept")?.split(",").map(y=>y.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Oy(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},h=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&h.ok&&(this._sessionId=h.headers.get("mcp-session-id")||void 0),!h.ok){if(h.status===401&&this._authProvider){if(h.headers.has("www-authenticate")){let{resourceMetadataUrl:W,scope:N}=Qa(h);this._resourceMetadataUrl=W,this._scope=$g(this._scope,N)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:h,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(W){throw mt(W)}return await h.text?.().catch(()=>{}),this._send(e,t,!0,o)}throw await h.text?.().catch(()=>{}),mt(r?new Dt(A.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:h.statusText}):new Ht)}let y=await h.text?.().catch(()=>null);if(h.status===403){let{resourceMetadataUrl:W,scope:N,error:F,errorDescription:x}=Qa(h);if(F==="insufficient_scope"){if(await this._stepUpAuthorize({scope:N,resourceMetadataUrl:W,errorDescription:x,statusText:h.statusText,text:y},o)!=="AUTHORIZED")throw mt(new Ht);return this._send(e,t,r,o+1)}}if(h.status===400&&typeof y=="string"&&this._isModernEnvelopedRequest(e))try{let W=vt.parse(JSON.parse(y)),N=(Array.isArray(e)?e:[e]).filter(F=>zo(F));if(Xn(W)&&N.some(F=>F.id===W.id)){this.onmessage?.(W);return}}catch{}let D=this._unfollowedRedirect(this._url,h)??y;throw new Dt(A.ClientHttpNotImplemented,`Error POSTing to endpoint: ${D}`,{status:h.status,statusText:h.statusText,text:y})}if(h.status===202){await h.text?.().catch(()=>{}),Kb(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>this.onerror?.(y));return}let g=(Array.isArray(e)?e:[e]).some(y=>"method"in y&&"id"in y&&y.id!==void 0),v=h.headers.get("content-type"),w=cy(v);if(g)if(w==="text/event-stream")this._handleSseStream(h.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(w==="application/json"){let y=await h.json(),D=Array.isArray(y)?y.map(W=>vt.parse(W)):[vt.parse(y)];for(let W of D)this.onmessage?.(W)}else throw await h.text?.().catch(()=>{}),new q(A.ClientHttpUnexpectedContent,`Unexpected content type: ${v}`,{contentType:v});else await h.text?.().catch(()=>{})}catch(n){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new Dt(A.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var Fg=class{_eventSlots=new Map;setHandler(t,r){let o=this._ensureEventSlot(t);o.onHandler&&r&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", \u2026) to add multiple listeners without replacing.`),o.onHandler=r}getHandler(t){return this._eventSlots.get(t)?.onHandler}addEventListener(t,r){this._ensureEventSlot(t).listeners.push(r)}removeEventListener(t,r){let o=this._eventSlots.get(t);if(!o)return;let n=o.listeners.indexOf(r);n!==-1&&o.listeners.splice(n,1)}dispatch(t,r){let o=this._eventSlots.get(t);if(o){o.onHandler?.(r);for(let n of[...o.listeners])n(r)}}_ensureEventSlot(t){let r=this._eventSlots.get(t);return r||(r={listeners:[]},this._eventSlots.set(t,r)),r}},Hg=class{_methods=new Set;claim(t,r){if(this._methods.has(t))throw Error(`Handler for "${t}" already registered (via ${r}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(t)}replace(t){this._methods.add(t)}release(t){this._methods.delete(t)}has(t){return this._methods.has(t)}},Ky=new Set;function Gy(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";Ky.has(i)||(Ky.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`));let a=o;return[s,{params:n.params},e==="request"?(l,u)=>a({method:s,params:l},GP(u)):l=>a({method:s,params:l})]}function GP(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var ev="2026-01-26";var YP="ui/notifications/tool-input-partial";var XP=p.union([p.literal("light"),p.literal("dark")]).describe("Color theme preference for the host environment."),tc=p.union([p.literal("inline"),p.literal("fullscreen"),p.literal("pip")]).describe("Display mode for UI presentation."),QP=p.union([p.literal("--color-background-primary"),p.literal("--color-background-secondary"),p.literal("--color-background-tertiary"),p.literal("--color-background-inverse"),p.literal("--color-background-ghost"),p.literal("--color-background-info"),p.literal("--color-background-danger"),p.literal("--color-background-success"),p.literal("--color-background-warning"),p.literal("--color-background-disabled"),p.literal("--color-text-primary"),p.literal("--color-text-secondary"),p.literal("--color-text-tertiary"),p.literal("--color-text-inverse"),p.literal("--color-text-ghost"),p.literal("--color-text-info"),p.literal("--color-text-danger"),p.literal("--color-text-success"),p.literal("--color-text-warning"),p.literal("--color-text-disabled"),p.literal("--color-border-primary"),p.literal("--color-border-secondary"),p.literal("--color-border-tertiary"),p.literal("--color-border-inverse"),p.literal("--color-border-ghost"),p.literal("--color-border-info"),p.literal("--color-border-danger"),p.literal("--color-border-success"),p.literal("--color-border-warning"),p.literal("--color-border-disabled"),p.literal("--color-ring-primary"),p.literal("--color-ring-secondary"),p.literal("--color-ring-inverse"),p.literal("--color-ring-info"),p.literal("--color-ring-danger"),p.literal("--color-ring-success"),p.literal("--color-ring-warning"),p.literal("--font-sans"),p.literal("--font-mono"),p.literal("--font-weight-normal"),p.literal("--font-weight-medium"),p.literal("--font-weight-semibold"),p.literal("--font-weight-bold"),p.literal("--font-text-xs-size"),p.literal("--font-text-sm-size"),p.literal("--font-text-md-size"),p.literal("--font-text-lg-size"),p.literal("--font-heading-xs-size"),p.literal("--font-heading-sm-size"),p.literal("--font-heading-md-size"),p.literal("--font-heading-lg-size"),p.literal("--font-heading-xl-size"),p.literal("--font-heading-2xl-size"),p.literal("--font-heading-3xl-size"),p.literal("--font-text-xs-line-height"),p.literal("--font-text-sm-line-height"),p.literal("--font-text-md-line-height"),p.literal("--font-text-lg-line-height"),p.literal("--font-heading-xs-line-height"),p.literal("--font-heading-sm-line-height"),p.literal("--font-heading-md-line-height"),p.literal("--font-heading-lg-line-height"),p.literal("--font-heading-xl-line-height"),p.literal("--font-heading-2xl-line-height"),p.literal("--font-heading-3xl-line-height"),p.literal("--border-radius-xs"),p.literal("--border-radius-sm"),p.literal("--border-radius-md"),p.literal("--border-radius-lg"),p.literal("--border-radius-xl"),p.literal("--border-radius-full"),p.literal("--border-width-regular"),p.literal("--shadow-hairline"),p.literal("--shadow-sm"),p.literal("--shadow-md"),p.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),eT=p.record(QP.describe(`Style variables for theming MCP apps.
68
+ - `)}`,new Error(N)}let M=`${a}/$ref`,X=fe(e,V,r,o,n,s,i,M,c);if(X.valid||O.push({instanceLocation:i,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...X.errors),r==="4"||r==="7")return{valid:O.length===0,errors:O}}if(Array.isArray(y)){let V=y.length,M=!1;for(let X=0;X<V;X++)if(d===y[X]||y[X]==="integer"&&d==="number"&&e%1===0&&e===e){M=!0;break}M||O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${y.join('", "')}".`})}else y==="integer"?(d!=="number"||e%1||e!==e)&&O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${y}".`}):y!==void 0&&d!==y&&O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${y}".`});if(v!==void 0&&(d==="object"||d==="array"?Qa(e,v)||O.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&O.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),z!==void 0&&(d==="object"||d==="array"?z.some(V=>Qa(e,V))||O.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(z)}.`}):z.some(V=>e===V)||O.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(z)}.`})),H!==void 0){let V=`${a}/not`;fe(e,H,r,o,n,s,i,V).valid&&O.push({instanceLocation:i,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let kt=[];if(T!==void 0){let V=`${a}/anyOf`,M=O.length,X=!1;for(let N=0;N<T.length;N++){let k=T[N],B=Object.create(c),J=fe(e,k,r,o,n,g===!0?s:null,i,`${V}/${N}`,B);O.push(...J.errors),X=X||J.valid,J.valid&&kt.push(B)}X?O.length=M:O.splice(M,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(D!==void 0){let V=`${a}/allOf`,M=O.length,X=!0;for(let N=0;N<D.length;N++){let k=D[N],B=Object.create(c),J=fe(e,k,r,o,n,g===!0?s:null,i,`${V}/${N}`,B);O.push(...J.errors),X=X&&J.valid,J.valid&&kt.push(B)}X?O.length=M:O.splice(M,0,{instanceLocation:i,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(x!==void 0){let V=`${a}/oneOf`,M=O.length,X=x.filter((N,k)=>{let B=Object.create(c),J=fe(e,N,r,o,n,g===!0?s:null,i,`${V}/${k}`,B);return O.push(...J.errors),J.valid&&kt.push(B),J.valid}).length;X===1?O.length=M:O.splice(M,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${X} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...kt),w!==void 0){let V=`${a}/if`;if(fe(e,w,r,o,n,s,i,V,c).valid){if(F!==void 0){let M=fe(e,F,r,o,n,s,i,`${a}/then`,c);M.valid||O.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...M.errors)}}else if(oe!==void 0){let M=fe(e,oe,r,o,n,s,i,`${a}/else`,c);M.valid||O.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...M.errors)}}if(d==="object"){if(U!==void 0)for(let N of U)N in e||O.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${N}".`});let V=Object.keys(e);if(xe!==void 0&&V.length<xe&&O.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${xe} properties.`}),Ne!==void 0&&V.length>Ne&&O.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Ne} properties.`}),wt!==void 0){let N=`${a}/propertyNames`;for(let k in e){let B=`${i}/${yt(k)}`,J=fe(k,wt,r,o,n,s,B,N);J.valid||O.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:N,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(Fe!==void 0){let N=`${a}/dependantRequired`;for(let k in Fe)if(k in e){let B=Fe[k];for(let J of B)J in e||O.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:N,error:`Instance has "${k}" but does not have "${J}".`})}}if(st!==void 0)for(let N in st){let k=`${a}/dependentSchemas`;if(N in e){let B=fe(e,st[N],r,o,n,s,i,`${k}/${yt(N)}`,c);B.valid||O.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${N}" but does not match dependant schema.`},...B.errors)}}if(Rt!==void 0){let N=`${a}/dependencies`;for(let k in Rt)if(k in e){let B=Rt[k];if(Array.isArray(B))for(let J of B)J in e||O.push({instanceLocation:i,keyword:"dependencies",keywordLocation:N,error:`Instance has "${k}" but does not have "${J}".`});else{let J=fe(e,B,r,o,n,s,i,`${N}/${yt(k)}`);J.valid||O.push({instanceLocation:i,keyword:"dependencies",keywordLocation:N,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let M=Object.create(null),X=!1;if(de!==void 0){let N=`${a}/properties`;for(let k in de){if(!(k in e))continue;let B=`${i}/${yt(k)}`,J=fe(e[k],de[k],r,o,n,s,B,`${N}/${yt(k)}`);if(J.valid)c[k]=M[k]=!0;else if(X=n,O.push({instanceLocation:i,keyword:"properties",keywordLocation:N,error:`Property "${k}" does not match schema.`},...J.errors),X)break}}if(!X&&Oe!==void 0){let N=`${a}/patternProperties`;for(let k in Oe){let B=new RegExp(k,"u"),J=Oe[k];for(let ye in e){if(!B.test(ye))continue;let Lr=`${i}/${yt(ye)}`,$t=fe(e[ye],J,r,o,n,s,Lr,`${N}/${yt(k)}`);$t.valid?c[ye]=M[ye]=!0:(X=n,O.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:N,error:`Property "${ye}" matches pattern "${k}" but does not match associated schema.`},...$t.errors))}}}if(!X&&ie!==void 0){let N=`${a}/additionalProperties`;for(let k in e){if(M[k])continue;let B=`${i}/${yt(k)}`,J=fe(e[k],ie,r,o,n,s,B,N);J.valid?c[k]=!0:(X=n,O.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:N,error:`Property "${k}" does not match additional properties schema.`},...J.errors))}}else if(!X&&ue!==void 0){let N=`${a}/unevaluatedProperties`;for(let k in e)if(!c[k]){let B=`${i}/${yt(k)}`,J=fe(e[k],ue,r,o,n,s,B,N);J.valid?c[k]=!0:O.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:N,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){ht!==void 0&&e.length>ht&&O.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${ht}).`}),Me!==void 0&&e.length<Me&&O.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Me}).`});let V=e.length,M=0,X=!1;if(Ge!==void 0){let N=`${a}/prefixItems`,k=Math.min(Ge.length,V);for(;M<k;M++){let B=fe(e[M],Ge[M],r,o,n,s,`${i}/${M}`,`${N}/${M}`);if(c[M]=!0,!B.valid&&(X=n,O.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:N,error:"Items did not match schema."},...B.errors),X))break}}if(qe!==void 0){let N=`${a}/items`;if(Array.isArray(qe)){let k=Math.min(qe.length,V);for(;M<k;M++){let B=fe(e[M],qe[M],r,o,n,s,`${i}/${M}`,`${N}/${M}`);if(c[M]=!0,!B.valid&&(X=n,O.push({instanceLocation:i,keyword:"items",keywordLocation:N,error:"Items did not match schema."},...B.errors),X))break}}else for(;M<V;M++){let k=fe(e[M],qe,r,o,n,s,`${i}/${M}`,N);if(c[M]=!0,!k.valid&&(X=n,O.push({instanceLocation:i,keyword:"items",keywordLocation:N,error:"Items did not match schema."},...k.errors),X))break}if(!X&&Ht!==void 0){let k=`${a}/additionalItems`;for(;M<V;M++){let B=fe(e[M],Ht,r,o,n,s,`${i}/${M}`,k);c[M]=!0,B.valid||(X=n,O.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors))}}}if(xt!==void 0)if(V===0&&Ee===void 0)O.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ee!==void 0&&V<Ee)O.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Ee}).`});else{let N=`${a}/contains`,k=O.length,B=0;for(let J=0;J<V;J++){let ye=fe(e[J],xt,r,o,n,s,`${i}/${J}`,N);ye.valid?(c[J]=!0,B++):O.push(...ye.errors)}B>=(Ee||0)&&(O.length=k),Ee===void 0&&Ae===void 0&&B===0?O.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:N,error:"Array does not contain item matching schema."}):Ee!==void 0&&B<Ee?O.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Ee} items matching schema. Only ${B} items were found.`}):Ae!==void 0&&B>Ae&&O.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ae} items matching schema. ${B} items were found.`})}if(!X&&Vt!==void 0){let N=`${a}/unevaluatedItems`;for(;M<V;M++){if(c[M])continue;let k=fe(e[M],Vt,r,o,n,s,`${i}/${M}`,N);c[M]=!0,k.valid||O.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:N,error:"Items did not match unevaluated items schema."},...k.errors)}}if(Mr)for(let N=0;N<V;N++){let k=e[N],B=typeof k=="object"&&k!==null;for(let J=0;J<V;J++){if(N===J)continue;let ye=e[J];(k===ye||B&&typeof ye=="object"&&ye!==null&&Qa(k,ye))&&(O.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${N} and ${J}.`}),N=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(r==="4"?(Ye!==void 0&&(He===!0&&e<=Ye||e<Ye)&&O.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${He?"or equal to ":""} ${Ye}.`}),Xe!==void 0&&(it===!0&&e>=Xe||e>Xe)&&O.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${it?"or equal to ":""} ${Xe}.`})):(Ye!==void 0&&e<Ye&&O.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ye}.`}),Xe!==void 0&&e>Xe&&O.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Xe}.`}),He!==void 0&&e<=He&&O.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${He}.`}),it!==void 0&&e>=it&&O.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${it}.`})),at!==void 0){let V=e%at;Math.abs(0-V)>=11920929e-14&&Math.abs(at-V)>=11920929e-14&&O.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${at}.`})}}else if(d==="string"){let V=Pt===void 0&&Tt===void 0?0:Qx(e);Pt!==void 0&&V<Pt&&O.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${Pt}).`}),Tt!==void 0&&V>Tt&&O.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${Tt}).`}),ur!==void 0&&!new RegExp(ur,"u").test(e)&&O.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),te!==void 0&&xy[te]&&!xy[te](e)&&O.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${te}".`})}return{valid:O.length===0,errors:O}}var eP=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=zo(e)}validate(e){return fe(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),zo(e,this.lookup)}},Cg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=yS(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new eP(e,this.draft??this._draftFor(e),this.shortcircuit);return r=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map(n=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Ey=!0;var Ig;Ig=globalThis.crypto;async function tP(e){return(await Ig).getRandomValues(new Uint8Array(e))}async function rP(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let n=await tP(e-o.length);for(let s of n)s<r&&(o+=t[s%t.length])}return o}async function oP(e){return await rP(e)}async function nP(e){let t=await(await Ig).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Og(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await oP(e),r=await nP(t);return{code_verifier:t,code_challenge:r}}var ec=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},ky=10,sP=13,wo=32;function Ng(e){}function Iy(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Ng,onError:r=Ng,onRetry:o=Ng,onComment:n,maxBufferSize:s}=e,i=[],a=0,c=!0,u,d="",h=0,m,g=!1;function y(x){if(g)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,x.charCodeAt(0)===239&&x.charCodeAt(1)===187&&x.charCodeAt(2)===191&&(x=x.slice(3))),i.length===0){let oe=z(x);oe!==""&&(i.push(oe),a=oe.length),v();return}if(x.indexOf(`
69
+ `)===-1&&x.indexOf("\r")===-1){i.push(x),a+=x.length,v();return}i.push(x);let w=i.join("");i.length=0,a=0;let F=z(w);F!==""&&(i.push(F),a=F.length),v()}function v(){s!==void 0&&(a+d.length<=s||(g=!0,i.length=0,a=0,u=void 0,d="",h=0,m=void 0,r(new ec(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function z(x){let w=0;if(x.indexOf("\r")===-1){let F=x.indexOf(`
70
+ `,w);for(;F!==-1;){if(w===F){h>0&&t({id:u,event:m,data:d}),u=void 0,d="",h=0,m=void 0,w=F+1,F=x.indexOf(`
71
+ `,w);continue}let oe=x.charCodeAt(w);if($y(x,w,oe)){let te=x.charCodeAt(w+5)===wo?w+6:w+5,de=x.slice(te,F);if(h===0&&x.charCodeAt(F+1)===ky){t({id:u,event:m,data:de}),u=void 0,d="",m=void 0,w=F+2,F=x.indexOf(`
72
+ `,w);continue}d=h===0?de:`${d}
73
+ ${de}`,h++}else Cy(x,w,oe)?m=x.slice(x.charCodeAt(w+6)===wo?w+7:w+6,F)||void 0:U(x,w,F);w=F+1,F=x.indexOf(`
74
+ `,w)}return x.slice(w)}for(;w<x.length;){let F=x.indexOf("\r",w),oe=x.indexOf(`
75
+ `,w),te=-1;if(F!==-1&&oe!==-1?te=F<oe?F:oe:F!==-1?F===x.length-1?te=-1:te=F:oe!==-1&&(te=oe),te===-1)break;U(x,w,te),w=te+1,x.charCodeAt(w-1)===sP&&x.charCodeAt(w)===ky&&w++}return x.slice(w)}function U(x,w,F){if(w===F){T();return}let oe=x.charCodeAt(w);if($y(x,w,oe)){let xe=x.charCodeAt(w+5)===wo?w+6:w+5,Ne=x.slice(xe,F);d=h===0?Ne:`${d}
76
+ ${Ne}`,h++;return}if(Cy(x,w,oe)){m=x.slice(x.charCodeAt(w+6)===wo?w+7:w+6,F)||void 0;return}if(oe===105&&x.charCodeAt(w+1)===100&&x.charCodeAt(w+2)===58){let xe=x.slice(x.charCodeAt(w+3)===wo?w+4:w+3,F);xe.includes("\0")||(u=xe);return}if(oe===58){if(n){let xe=x.slice(w,F);n(xe.slice(x.charCodeAt(w+1)===wo?2:1))}return}let te=x.slice(w,F),de=te.indexOf(":");if(de===-1){H(te,"",te);return}let Oe=te.slice(0,de),ie=te.charCodeAt(de+1)===wo?2:1,ue=te.slice(de+ie);H(Oe,ue,te)}function H(x,w,F){switch(x){case"event":m=w||void 0;break;case"data":d=h===0?w:`${d}
77
+ ${w}`,h++;break;case"id":w.includes("\0")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new ec(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:F}));break;default:r(new ec(`Unknown field "${x.length>20?`${x.slice(0,20)}\u2026`:x}"`,{type:"unknown-field",field:x,value:w,line:F}));break}}function T(){h>0&&t({id:u,event:m,data:d}),u=void 0,d="",h=0,m=void 0}function D(x={}){if(x.consume&&i.length>0){let w=i.join("");U(w,0,w.length)}c=!0,u=void 0,d="",h=0,m=void 0,i.length=0,a=0,g=!1}return{feed:y,reset:D}}function $y(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Cy(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Ku=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let s;super({start(i){s=Iy({onEvent:a=>{i.enqueue(a)},onError(a){typeof t=="function"&&t(a),(t==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:o,maxBufferSize:n})},transform(i){s.feed(i)}})}};var rc=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return nt(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,e)}constructor(e){super(e),this.name=new.target.name,bo(this,new.target)}},Zg=class extends rc{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},iP=class extends rc{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Vy=class extends rc{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Xu=class extends rc{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Oy=class extends rc{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Dg(e,t,r){if(e)return typeof e.issuer!="string"?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Jy(e.issuer,t)?e:void 0}function Jy(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function aP(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function cP(e,t,r){let{resourceMetadataUrl:o,scope:n}=tc(t.response);if(await Fg(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new Dt}function lP(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async r=>cP(e,r,t)}}var Dt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return nt(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",bo(this,new.target)}};function Vg(e){return e?.authorization_response_iss_parameter_supported===!0}function Jg({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Zg("authorization_response",t,void 0);return}if(e!==t)throw new Zg("authorization_response",t,e)}}function qg(...e){let t=new Set;for(let r of e)if(r)for(let o of r.split(/\s+/))o&&t.add(o);return t.size>0?[...t].join(" "):void 0}function uP(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function dP(e,t,r,o,n){if(typeof e=="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Yy(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new Dt("Authorization callback failed and the issuer could not be verified");Jg({iss:s,expectedIssuer:a.issuer,issParameterSupported:Vg(a)});let c=e.get("error");throw c?new yo(c,e.get("error_description")??c,e.get("error_uri")??void 0):new Dt("Authorization callback contained neither `code` nor `error`")}function pP(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Ag="code",Mg="S256";function hP(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&pP(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function mP(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":fP(n,s,r);return;case"client_secret_post":gP(n,s,o);return;case"none":SP(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function fP(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function gP(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function SP(e,t){t.set("client_id",e)}function By(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function _P(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!By(t.hostname))throw new Vy(t.href);return t}function bP(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||By(r.hostname))return"native"}return"web"}function yP(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??bP(t.redirect_uris)}}async function Ny(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Jn.parse(JSON.parse(r));return yo.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new yo(ir.ServerError,n)}}function qy(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Fg(e,t){try{return await jg(e,t)}catch(r){if(r instanceof yo){if(r.code===ir.InvalidClient||r.code===ir.UnauthorizedClient)return qy(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await jg(e,t);if(r.code===ir.InvalidGrant||r.code===ir.InvalidDpopProof)return qy(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await jg(e,t)}throw r}}function vP(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}async function jg(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:c}){let u=yP(e),d=await e.discoveryState?.(),h,m,g,y,v=s;if(!v&&d?.resourceMetadataUrl&&(v=new URL(d.resourceMetadataUrl)),d?.authorizationServerUrl){if(m=d.authorizationServerUrl,h=d.resourceMetadata,g=d.authorizationServerMetadata??await Gy(m,{fetchFn:i,skipIssuerValidation:a}),!h)try{h=await Wy(t,{resourceMetadataUrl:v},i)}catch(ie){if(ie instanceof TypeError)throw ie}(g!==d.authorizationServerMetadata||h!==d.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(m),resourceMetadataUrl:v?.toString(),resourceMetadata:h,authorizationServerMetadata:g})}else{let ie=await Yy(t,{resourceMetadataUrl:v,fetchFn:i,skipIssuerMetadataValidation:a});m=ie.authorizationServerUrl,g=ie.authorizationServerMetadata,h=ie.resourceMetadata,y={authorizationServerUrl:String(m),resourceMetadataUrl:v?.toString(),resourceMetadata:h,authorizationServerMetadata:g}}let z=g?.issuer??String(m),U={issuer:z};if(await e.saveAuthorizationServerUrl?.(z),r!==void 0){let ie=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(ie===void 0){if(e.saveDiscoveryState!==void 0)throw new Xu("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",z);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!Jy(ie,z))throw new Xu(ie,z)}y&&await e.saveDiscoveryState?.(y);let H=await wP(t,e,h),T=H&&h&&!e.validateResourceURL?h.resource:H;T&&await e.saveResourceUrl?.(Bg(T));let D=vP({requestedScope:n,resourceMetadata:h,authServerMetadata:g,clientMetadata:e.clientMetadata}),x=await Promise.resolve(e.clientInformation(U)),w=Dg(x,z,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&x?.issuer&&e.saveClientInformation===void 0)throw new Xu(x.issuer,z);if(w&&w.issuer===void 0&&(w={...w,issuer:z},await e.saveClientInformation?.(w,U)),!w){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let ie=g?.client_id_metadata_document_supported===!0,ue=e.clientMetadataUrl;if(ue&&!zP(ue))throw new yo(ir.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ue}`);if(ie&&ue)w={client_id:ue,issuer:z},await e.saveClientInformation?.(w,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");w={...await OP(m,{metadata:g,clientMetadata:u,scope:D,fetchFn:i}),issuer:z},await e.saveClientInformation(w,U)}}let F=!e.redirectUrl;if(r!==void 0||F){r!==void 0&&Jg({iss:o,expectedIssuer:g?.issuer,issParameterSupported:Vg(g)});let ie=await IP(e,m,{metadata:g,resource:T,authorizationCode:r,iss:o,scope:D,fetchFn:i});return await e.saveTokens({...ie,issuer:z},U),"AUTHORIZED"}let oe=Dg(await e.tokens(U),z);if(oe&&oe.issuer===void 0&&(oe={...oe,issuer:z},await e.saveTokens(oe,U)),oe?.refresh_token&&!c){let ie;try{ie=await CP(m,{metadata:g,clientInformation:w,refreshToken:oe.refresh_token,resource:T,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(ue){if(ue instanceof Vy)throw ue;if(!(ue instanceof yo)||ue.code===ir.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ue instanceof Error?ue.message:String(ue))}`);else throw ue}if(ie)return await e.saveTokens({...ie,issuer:z},U),"AUTHORIZED"}let te=e.state?await e.state():void 0,{authorizationUrl:de,codeVerifier:Oe}=await kP(m,{metadata:g,clientInformation:w,state:te,redirectUrl:e.redirectUrl,scope:D,resource:T});return await e.saveCodeVerifier(Oe),await e.redirectToAuthorization(de),"REDIRECT"}function zP(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function wP(e,t,r){let o=qb(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Ab({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}var RP=new Set(["bearer","dpop"]);function tc(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!RP.has(r.toLowerCase())||!o)return{};let n=Gu(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=Gu(e,"scope")||void 0,a=Gu(e,"error")||void 0,c=Gu(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:c}}function Gu(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function Wy(e,t,r=fetch){let o=await TP(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Fn.parse(await o.json())}async function Ky(e,t,r=fetch){let o=Xa(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Ey)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function xP(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ay(e,t,r=fetch){return await Ky(e,{"MCP-Protocol-Version":t},r)}function PP(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}async function TP(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??fn,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let c=xP(t,n.pathname);i=new URL(c,o?.metadataServerUrl??n),i.search=n.search}let a=await Ay(i,s,r);return!o?.metadataUrl&&PP(a,n.pathname)&&(a=await Ay(new URL(`/.well-known/${t}`,n),s,r)),a}function EP(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Gy(e,{fetchFn:t=fetch,protocolVersion:r=fn,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=EP(e);for(let{url:i,type:a}of s){let c=await Ky(i,n,t);if(!c)continue;if(!c.ok){if(await c.text?.().catch(()=>{}),c.status<500||c.status===502)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?_o.parse(await c.json()):Hn.parse(await c.json());if(!o){let d=typeof e=="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new Zg("metadata",d,u.issuer)}return u}}async function Yy(e,t){let r,o;try{r=await Wy(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let n=await Gy(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Bg(e){return typeof e=="string"?e:e.href}async function kP(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ag))throw new Error(`Incompatible auth server: does not support response type ${Ag}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Mg))throw new Error(`Incompatible auth server: does not support code challenge method ${Mg}`)}else a=new URL("/authorize",e);let c=await Og(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Ag),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Mg),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),n&&a.searchParams.set("scope",n),n?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",Bg(i)),{authorizationUrl:a,codeVerifier:u}}function $P(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Xy(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let c=_P(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",Bg(s)),!n&&o&&mP(hP(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let g=new Headers(u);return n&&await n(g,r,c,t),i&&g.set("DPoP",await i.buildProof({htm:"POST",htu:c})),Xa(a??fetch)(c,{method:"POST",headers:g,body:r})},h=await d();if(i&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===ir.UseDpopNonce&&(i.observeNonce(h,c),h=await d()),i?.observeNonce(h,c),!h.ok)throw await Ny(h);let m=await h.json();try{return Vn.parse(_g(m))}catch(g){throw typeof m=="object"&&m!==null&&"error"in m?await Ny(JSON.stringify(m)):g}}async function CP(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Xy(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function IP(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){n!==void 0&&Jg({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Vg(r)});let c=r?.issuer??String(t),u=async()=>{let g=await e.clientInformation({issuer:c}),y=Dg(g,c,{canPersistStamp:!1});if(g&&y===void 0)throw new Xu(String(g.issuer),c);return y},d=await u(),h=i??e.clientMetadata.scope,m;if(e.prepareTokenRequest&&(m=await e.prepareTokenRequest(h)),!m){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");m=$P(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Xy(t,{metadata:r,tokenRequestParams:m,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function OP(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Xa(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new iP({status:a.status,body:await a.text(),submittedMetadata:i});return Bn.parse(_g(await a.json()))}var Yu=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),NP=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Lg(e))}set(e,t){let r=Lg(e),o=Yu.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!Yu.has(i.slice(0,i.indexOf("\0")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;return this._entries.set(r,{...t,stamp:s}),n&&!o&&this._cappedSize++,s}delete(e){this._entries.delete(Lg(e))&&!Yu.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,r=Yu.has(e);for(let o of this._entries.keys())o.startsWith(t)&&(this._entries.delete(o),r||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function Lg(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function Ug(e,t){return t===void 0?e:`${e}\0${t}`}var qP=864e5,AP=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Ug(e,t),o=this._evictionGeneration.get(r);o!==void 0&&this._evictionGeneration.set(r,o+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Ug(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Ug(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:MP(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(c){this._reportError(c)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(c){this._reportError(c)}}async read(e,t){let r=await this._probe(e,t);if(!(r?.expiresAt===void 0||!(r.expiresAt>this.now())))try{let o=JSON.parse(r.value);if(typeof o!="object"||o===null||Array.isArray(o))throw new TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);i!==void 0&&n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(r=>r!==null&&typeof r=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function MP(e){let t;try{t=JSON.stringify(e)}catch(r){throw new TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Qy=Symbol.for("mcp.authSeamEscape");function ut(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,Qy,{value:!0,configurable:!0})}catch{}return e}function jP(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[Qy]===!0}var LP=-32022,UP=new Set([-32001,-32020,-32021]);function ZP(e,t){switch(e.kind){case"result":return DP(e.result,t);case"rpc-error":return ev(e,t);case"http-error":return FP(e,t);case"network-error":return My(e.error,t);case"unusable-reply":return{kind:"error",error:new A(q.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${tv(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:My(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new A(q.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function DP(e,t){let r=sr(Vu).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find(s=>o.includes(s));return n!==void 0?{kind:"modern",version:n,discover:r.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new Hu({supported:[...o],requested:t.requestedVersion})}}function ev(e,t){let{code:r,message:o,data:n}=e;if(r===LP){let s=VP(n);if(s===void 0)return{kind:"legacy"};let i=new Hu({supported:s,requested:JP(n)??t.requestedVersion},o),a=Ya(s),c=t.clientModernVersions.find(u=>a.includes(u));return c!==void 0?{kind:"corrective",version:c,error:i}:a.length>0?{kind:"error",error:i}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}return UP.has(r)?{kind:"legacy"}:{kind:"legacy"}}function FP(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new Ut(o?q.ClientHttpForbidden:q.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new Ut(q.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=BP(e.body);return r!==void 0?ev(r,t):{kind:"legacy"}}function My(e,t){return t.environment==="browser"&&HP(e)?{kind:"legacy"}:{kind:"error",error:new A(q.EraNegotiationFailed,`Version negotiation probe failed: ${tv(e)}`,{cause:e},{cause:e})}}function HP(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function tv(e){return e instanceof Error?e.message:String(e)}function VP(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r=="string")))return t}function JP(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function BP(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let r=t.error;if(typeof r!="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o=="number")return{code:o,message:typeof n=="string"?n:"",data:s}}var WP="legacy";function KP(e,t){let r=e?.mode??WP;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r=="object"){if(!ar(r.pin))throw new TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Ya(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...bg],fallbackAvailable:t?yg(t).length>0:!0,probe:o}}function jy(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Ly(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var GP=class rv{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new rv(t);t.onmessage=o=>{let n=r._pending;if(n!==void 0&&(Kn(o)||Gn(o))&&o.id===n.id){r._pending=void 0,Kn(o)?n.resolve({kind:"response",result:o.result}):n.resolve({kind:"response",error:o.error});return}},t.onerror=o=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;o!==void 0&&(r._pending=void 0,o.resolve({kind:"closed"})),r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise(n=>{let s=!1,i=c=>{s||(s=!0,clearTimeout(a),this._pending?.id===o&&(this._pending=void 0),n(c))},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch(c=>i({kind:"send-error",error:c}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Hg.set(r,()=>{r.onclose===n&&(r.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Hg=new WeakMap;function Uy(e){let t=Hg.get(e);Hg.delete(e),t?.()}function YP(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:sr(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function XP(e){return e instanceof A&&e.code===q.ClientHttpUnexpectedContent?!0:e instanceof Error&&e.name==="SyntaxError"}function QP(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(jP(r)||r instanceof Dt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Ut){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o=="string"?o:void 0,statusText:r.data.statusText}}return XP(r)?{kind:"unusable-reply",error:r}:{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function ov(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await GP.open(t.transport),a=async()=>{let u=n[0],d=!1,h=o;for(;;){let m=await i.exchange(v=>YP(v,u,t.clientInfo,t.capabilities),r);if(m.kind==="timeout"&&h>0){h--;continue}let g=QP(m,r),y=ZP(g,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(y.kind){case"modern":return{era:"modern",version:y.version,discover:y.discover};case"corrective":if(d)throw y.error;d=!0,u=y.version;continue;case"legacy":{let v=g.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new A(q.EraNegotiationFailed,v===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${v} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new A(q.EraNegotiationFailed,v===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${v} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(v!==void 0&&t.disposableProbe!==!0)throw new A(q.EraNegotiationFailed,`Version negotiation failed: ${v} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw y.error}}},c;try{c=await a()}catch(u){throw i.detach(),u}return i.release(),c}function eT(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r=="object"&&r!==null&&typeof r.command=="string"?r:void 0}async function tT(e,t,r,o){let n=t.constructor,s=new n({...r,stderr:"ignore"}),i=t.close,a=!1,c,u=new Promise((h,m)=>{c=()=>m(Zy())});t.close=async function(){return a=!0,c?.(),i.call(t)};let d;try{let h=ov(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});h.catch(()=>{}),d=await Promise.race([h,u])}finally{await rT(s),t.close=i}if(a)throw Zy();return d}function Zy(){return new A(q.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function rT(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function Dy(e){let t=e._meta?.[Qt];return gy.Implementation(t)?t:void 0}function Qu(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,o=e.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&&Qu(s,r[n])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Qu(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Qu(r,t)}}function oT(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function nT(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&kr.safeParse(e.discover).success))return e;throw new A(q.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Fy={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},sT=64,nv=class extends Wu{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new A(q.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Cg,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=py(t?.inputRequired),this._cache=new AP(t?.responseCacheStore??new NP,t?.responseCacheStore!==void 0,r=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??sT,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&ar(this._negotiatedProtocolVersion)&&vo(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?_y({getRequestHandler:r=>this._getRequestHandler(r),buildContext:r=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new A(q.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Sy(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(r,o)=>{let n=sr(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era"&&(s=n.validateInputRequest("elicitation/create",r)),!s.ok)throw new se(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:c}=oT(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new se(W.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!c)throw new se(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era"&&(d=n.validateInputResponse("elicitation/create",u)),!d.ok)throw new se(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let h=d.value,m=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&h.action==="accept"&&h.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{Qu(m,h.content)}catch{}return h}:e==="sampling/createMessage"?async(r,o)=>{let n=sr(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era"&&(s=n.validateInputRequest("sampling/createMessage",r)),!s.ok)throw new se(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),c=!!(i.tools||i.toolChoice),u=n.samplingResultVariant(c,a);if(!u.ok&&u.reason==="not-in-era"&&(u=n.validateInputResponse("sampling/createMessage",a)),!u.ok)throw new se(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new A(q.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,nT(t.prior),t);let r=KP(this._versionNegotiation,this._supportedProtocolVersionsOption);return r.kind!=="legacy"?this._connectNegotiated(e,r,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=yg(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new A(q.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;n!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=Ly(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:jy(),defaultTimeoutMs:r?.timeout??Bu},i=n==="stdio"?eT(e):void 0;o=i===void 0?await ov(t,{...s,transport:e,transportKind:n}):await tT(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),Uy(e),n}if(Uy(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Dy(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion&&e.setProtocolVersion(o.version),this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:new Error(String(u)))}let c=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(c).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);r?.signal?.aborted&&d(),r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(c,{timeout:r?.timeout,signal:u.signal})}catch(h){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),h;this.onerror?.(h instanceof Error?h:new Error(String(h)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Ya(n).length>0?Ya(n):bg).find(i=>o.supportedVersions.includes(i));if(s===void 0)throw new A(q.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=Dy(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return ar(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new A(q.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new A(q.CapabilityNotSupported,`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 A(q.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new A(q.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new A(q.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new A(q.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new A(q.CapabilityNotSupported,`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){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new A(q.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new A(q.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new A(q.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},kr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);return r!==void 0?r:this._listAllPages("prompts/list",e,t,o=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/list",e,t,o=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/templates/list",e,t,o=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),c=a.nextCursor,u=a,d=1;for(;c!==void 0;){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new A(q.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let h=await this.request({method:e,params:{...t,cursor:c}},r);if(h.nextCursor===c&&JSON.stringify(o(h))===JSON.stringify(o(u)))break;o(a).push(...o(h)),u=h,c=h.nextCursor,d++}return delete a.nextCursor,n?.(a),s||await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs=="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),qP),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch(n=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof A?n:new A(q.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:Tg(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);s.expiresAt>this._cache.now()?await this._cache.write("resources/read",n,o,s):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new A(q.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!ar(r))throw new A(q.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let T=t.signal.reason;throw T instanceof A?T:new A(q.RequestTimeout,String(T))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,c,u,d=new Promise((T,D)=>{c=T,u=D}),h,m=new Promise(T=>{h=T}),g=T=>{if(s==="closed")return;let D=s==="opening";if(i!==void 0&&(clearTimeout(i),i=void 0),"ack"in T){s="open",c(T.ack);return}s="closed",a!==void 0&&t?.signal?.removeEventListener("abort",a),this._listenState.delete(n),o.abort(),h(T.cause),D&&u(T.error??new A(q.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},y=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},v=async()=>{s!=="closed"&&(g({cause:"local"}),await y())};this._listenState.set(n,{settle:g});let z=t?.timeout??Bu;if(i=setTimeout(()=>{g({cause:"remote",error:new A(q.RequestTimeout,"subscriptions/listen ack timed out",{timeout:z})}),y().catch(()=>{})},z),t?.signal){let T=t.signal;a=()=>{if(s==="closed")return;let D=T.reason;g({cause:"local",error:D instanceof Error?D:new Error(String(D??"Aborted"))}),y().catch(()=>{})},T.addEventListener("abort",a,{once:!0})}let U={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=T=>{g({cause:"remote",error:T instanceof Error?T:new Error(String(T))})};try{this.transport.send(U,{requestSignal:o.signal,onRequestStreamEnd:()=>g({cause:"remote",error:new Error("subscriptions/listen: stream ended")})}).catch(H)}catch(T){H(T)}return{honoredFilter:await d,close:v,closed:m}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Fy,e.method)?Fy[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;typeof o=="string"&&this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[pi],n=typeof o=="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o=="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t=="string"?this._listenState.get(t):void 0;if(r!==void 0){Gn(e)?r.settle({cause:"remote",error:se.fromError(e.error.code,e.error.message,e.error.data)}):r.settle({cause:"graceful",error:new A(q.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new A(q.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&jy()!=="browser",o=async()=>{if(!r)return t;let c;try{c=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!c?.valid||c.declarations.length===0)return t;let u=ly(c.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,c=>this._compileOutputValidator(c)).catch(c=>void this._reportStoreError(c)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let c=n.compileError,u=(c instanceof Error?c.message:String(c)).slice(0,200);throw new se(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(c){let u=c instanceof se&&c.code===Wn;if(!r||!u||t?.toolDefinition!==void 0)throw c;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch(h=>this._reportStoreError(h)),n=await this._cache.outputValidator(e.name,h=>this._compileOutputValidator(h)).catch(h=>void this._reportStoreError(h)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new se(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let c=a(i.structuredContent);if(!c.valid)throw new se(W.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)}catch(c){throw c instanceof se?c:new se(W.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)}}return i}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);return r!==void 0?r:this._listAllPages("tools/list",e,t,o=>o.tools,o=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Ly(this.transport)==="stdio")return;let t=e.tools.filter(r=>{let o=Tg(r.inputSchema);return o.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${o.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,r,o){let n=Ju(ca,r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,c=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:new Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let h=setTimeout(c,i);this._listChangedDebounceTimers.set(e,h)}else c()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function iT(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function aT(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return iT(t)&&/use_dpop_nonce/i.test(t)}var cT=(e,t)=>r=>{let o=typeof e=="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),c=await o();if(!c)return r(n,s);let u=async()=>{let h=await t();if(!h)return r(n,s);let m=new Headers(s?.headers),g=await c.buildProof({htm:i,htu:a,accessToken:h});return m.set("Authorization",`DPoP ${h}`),m.set("DPoP",g),r(n,{...s,headers:m})},d=await u();return aT(d)&&d.headers.has("dpop-nonce")&&(c.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u()),c.observeNonce(d,a),d}},lT=e=>cT(async()=>{try{return await e.dpop?.()}catch(t){throw ut(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw ut(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var Bk=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return nt(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return nt(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,bo(this,new.target)}};var uT=1,dT={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},pT=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Hy(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var sv=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,aP(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=lP(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=lT(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=yy(t?.fetch,t?.requestInit),this._redirectPolicy==="follow"&&(this._fetchWithInit=wy(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??dT,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??uT)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw ut(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Oy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Oy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Ut(q.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),o=qg(this._scope,r?.scope,e.scope);this._scope=o;let n=uP(o,r?.scope);return Fg(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Xa(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:Ry(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw ut(r)}return t&&e.set("Authorization",`Bearer ${t}`),this._sessionId&&e.set("mcp-session-id",this._sessionId),this._protocolVersion&&e.set("mcp-protocol-version",this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!vo(t))return;let r=t.params?._meta?.[Xt];if(typeof r!="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=uy(t.method,t.params);o?.value!==void 0&&e.set("mcp-name",Eg(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!vo(e))return!1;let t=e.params?._meta?.[Xt];return typeof t=="string"&&ar(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map(h=>h.trim().toLowerCase())??[],"text/event-stream"];i.set("accept",[...new Set(a)].join(", ")),o&&i.set("last-event-id",o);let c=this._abortController?.signal,u=n!==void 0&&c!==void 0?Hy(c,n):n??c,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:m,scope:g}=tc(d);this._resourceMetadataUrl=m,this._scope=qg(this._scope,g)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(m){throw ut(m)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}throw await d.text?.().catch(()=>{}),ut(t?new Ut(q.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}):new Dt)}if(d.status===403){let{resourceMetadataUrl:m,scope:g,error:y,errorDescription:v}=tc(d);if(y==="insufficient_scope"){let z=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:g,resourceMetadataUrl:m,errorDescription:v,statusText:d.statusText,text:z},r)!=="AUTHORIZED")throw ut(new Dt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let h=this._unfollowedRedirect(this._url,d)??d.statusText;throw new Ut(q.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${h}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){throw s()||this.onerror?.(i),i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(s=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s=="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,c,u=!1,d=!1;(async()=>{try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ku({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:y}=await m.read();if(y)break;if(g.id&&(c=g.id,u=!0,o?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let v=bt.parse(JSON.parse(g.data));(Kn(v)||Gn(v))&&(d=!0,n!==void 0&&(v.id=n)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(r||u)&&!d&&this._abortController&&!a()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0):a()||i?.()}catch(m){if(a())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`)),i?.()}else i?.()}})()}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,t){if(!this._oauthProvider)throw new Dt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await dP(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Fg(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Dt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:vo(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(z=>this.onerror?.(z));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some(z=>Pg(z)):Pg(e);if(a&&i.delete("mcp-session-id"),t?.headers!==void 0)for(let[z,U]of Object.entries(t.headers))pT.has(z.toLowerCase())||i.set(z,U);i.set("content-type","application/json");let c=[...i.get("accept")?.split(",").map(z=>z.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Hy(u,t.requestSignal):t?.requestSignal??u,h={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},m=await this._redirects(this._fetch??fetch)(this._url,h);if(a&&m.ok&&(this._sessionId=m.headers.get("mcp-session-id")||void 0),!m.ok){if(m.status===401&&this._authProvider){if(m.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:T}=tc(m);this._resourceMetadataUrl=H,this._scope=qg(this._scope,T)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:m,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw ut(H)}return await m.text?.().catch(()=>{}),this._send(e,t,!0,o)}throw await m.text?.().catch(()=>{}),ut(r?new Ut(q.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:m.statusText}):new Dt)}let z=await m.text?.().catch(()=>null);if(m.status===403){let{resourceMetadataUrl:H,scope:T,error:D,errorDescription:x}=tc(m);if(D==="insufficient_scope"){if(await this._stepUpAuthorize({scope:T,resourceMetadataUrl:H,errorDescription:x,statusText:m.statusText,text:z},o)!=="AUTHORIZED")throw ut(new Dt);return this._send(e,t,r,o+1)}}if(m.status===400&&typeof z=="string"&&this._isModernEnvelopedRequest(e))try{let H=bt.parse(JSON.parse(z)),T=(Array.isArray(e)?e:[e]).filter(D=>vo(D));if(Gn(H)&&T.some(D=>D.id===H.id)){this.onmessage?.(H);return}}catch{}let U=this._unfollowedRedirect(this._url,m)??z;throw new Ut(q.ClientHttpNotImplemented,`Error POSTing to endpoint: ${U}`,{status:m.status,statusText:m.statusText,text:z})}if(m.status===202){await m.text?.().catch(()=>{}),iy(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(z=>this.onerror?.(z));return}let g=(Array.isArray(e)?e:[e]).some(z=>"method"in z&&"id"in z&&z.id!==void 0),y=m.headers.get("content-type"),v=by(y);if(g)if(v==="text/event-stream")this._handleSseStream(m.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(v==="application/json"){let z=await m.json(),U=Array.isArray(z)?z.map(H=>bt.parse(H)):[bt.parse(z)];for(let H of U)this.onmessage?.(H)}else throw await m.text?.().catch(()=>{}),new A(q.ClientHttpUnexpectedContent,`Unexpected content type: ${y}`,{contentType:y});else await m.text?.().catch(()=>{})}catch(n){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new Ut(q.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var Wg=class{_eventSlots=new Map;setHandler(t,r){let o=this._ensureEventSlot(t);o.onHandler&&r&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", \u2026) to add multiple listeners without replacing.`),o.onHandler=r}getHandler(t){return this._eventSlots.get(t)?.onHandler}addEventListener(t,r){this._ensureEventSlot(t).listeners.push(r)}removeEventListener(t,r){let o=this._eventSlots.get(t);if(!o)return;let n=o.listeners.indexOf(r);n!==-1&&o.listeners.splice(n,1)}dispatch(t,r){let o=this._eventSlots.get(t);if(o){o.onHandler?.(r);for(let n of[...o.listeners])n(r)}}_ensureEventSlot(t){let r=this._eventSlots.get(t);return r||(r={listeners:[]},this._eventSlots.set(t,r)),r}},Kg=class{_methods=new Set;claim(t,r){if(this._methods.has(t))throw Error(`Handler for "${t}" already registered (via ${r}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(t)}replace(t){this._methods.add(t)}release(t){this._methods.delete(t)}has(t){return this._methods.has(t)}},iv=new Set;function av(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";iv.has(i)||(iv.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`));let a=o;return[s,{params:n.params},e==="request"?(c,u)=>a({method:s,params:c},hT(u)):c=>a({method:s,params:c})]}function hT(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var dv="2026-01-26";var mT="ui/notifications/tool-input-partial";var fT=p.union([p.literal("light"),p.literal("dark")]).describe("Color theme preference for the host environment."),oc=p.union([p.literal("inline"),p.literal("fullscreen"),p.literal("pip")]).describe("Display mode for UI presentation."),gT=p.union([p.literal("--color-background-primary"),p.literal("--color-background-secondary"),p.literal("--color-background-tertiary"),p.literal("--color-background-inverse"),p.literal("--color-background-ghost"),p.literal("--color-background-info"),p.literal("--color-background-danger"),p.literal("--color-background-success"),p.literal("--color-background-warning"),p.literal("--color-background-disabled"),p.literal("--color-text-primary"),p.literal("--color-text-secondary"),p.literal("--color-text-tertiary"),p.literal("--color-text-inverse"),p.literal("--color-text-ghost"),p.literal("--color-text-info"),p.literal("--color-text-danger"),p.literal("--color-text-success"),p.literal("--color-text-warning"),p.literal("--color-text-disabled"),p.literal("--color-border-primary"),p.literal("--color-border-secondary"),p.literal("--color-border-tertiary"),p.literal("--color-border-inverse"),p.literal("--color-border-ghost"),p.literal("--color-border-info"),p.literal("--color-border-danger"),p.literal("--color-border-success"),p.literal("--color-border-warning"),p.literal("--color-border-disabled"),p.literal("--color-ring-primary"),p.literal("--color-ring-secondary"),p.literal("--color-ring-inverse"),p.literal("--color-ring-info"),p.literal("--color-ring-danger"),p.literal("--color-ring-success"),p.literal("--color-ring-warning"),p.literal("--font-sans"),p.literal("--font-mono"),p.literal("--font-weight-normal"),p.literal("--font-weight-medium"),p.literal("--font-weight-semibold"),p.literal("--font-weight-bold"),p.literal("--font-text-xs-size"),p.literal("--font-text-sm-size"),p.literal("--font-text-md-size"),p.literal("--font-text-lg-size"),p.literal("--font-heading-xs-size"),p.literal("--font-heading-sm-size"),p.literal("--font-heading-md-size"),p.literal("--font-heading-lg-size"),p.literal("--font-heading-xl-size"),p.literal("--font-heading-2xl-size"),p.literal("--font-heading-3xl-size"),p.literal("--font-text-xs-line-height"),p.literal("--font-text-sm-line-height"),p.literal("--font-text-md-line-height"),p.literal("--font-text-lg-line-height"),p.literal("--font-heading-xs-line-height"),p.literal("--font-heading-sm-line-height"),p.literal("--font-heading-md-line-height"),p.literal("--font-heading-lg-line-height"),p.literal("--font-heading-xl-line-height"),p.literal("--font-heading-2xl-line-height"),p.literal("--font-heading-3xl-line-height"),p.literal("--border-radius-xs"),p.literal("--border-radius-sm"),p.literal("--border-radius-md"),p.literal("--border-radius-lg"),p.literal("--border-radius-xl"),p.literal("--border-radius-full"),p.literal("--border-width-regular"),p.literal("--shadow-hairline"),p.literal("--shadow-sm"),p.literal("--shadow-md"),p.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),ST=p.record(gT.describe(`Style variables for theming MCP apps.
78
78
 
79
79
  Individual style keys are optional - hosts may provide any subset of these values.
80
80
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -92,10 +92,10 @@ Individual style keys are optional - hosts may provide any subset of these value
92
92
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
93
93
 
94
94
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
95
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),tT=p.object({method:p.literal("ui/open-link"),params:p.object({url:p.string().describe("URL to open in the host's browser")})}),rT=p.object({isError:p.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),oT=p.object({isError:p.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),nT=p.object({isError:p.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),sT=p.object({method:p.literal("ui/notifications/sandbox-proxy-ready"),params:p.object({})}),Vg=p.object({connectDomains:p.array(p.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
95
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),_T=p.object({method:p.literal("ui/open-link"),params:p.object({url:p.string().describe("URL to open in the host's browser")})}),bT=p.object({isError:p.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),yT=p.object({isError:p.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),vT=p.object({isError:p.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),zT=p.object({method:p.literal("ui/notifications/sandbox-proxy-ready"),params:p.object({})}),Gg=p.object({connectDomains:p.array(p.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
96
96
 
97
97
  - Maps to CSP \`connect-src\` directive
98
- - Empty or omitted \u2192 no network connections (secure default)`),resourceDomains:p.array(p.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"),frameDomains:p.array(p.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:p.array(p.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)")}),Jg=p.object({camera:p.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),iT=p.object({method:p.literal("ui/notifications/size-changed"),params:p.object({width:p.number().optional().describe("New width in pixels."),height:p.number().optional().describe("New height in pixels.")})}),Kk=p.object({method:p.literal("ui/notifications/tool-input"),params:p.object({arguments:p.record(p.string(),p.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),Gk=p.object({method:p.literal("ui/notifications/tool-input-partial"),params:p.object({arguments:p.record(p.string(),p.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),Yk=p.object({method:p.literal("ui/notifications/tool-cancelled"),params:p.object({reason:p.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),aT=p.object({fonts:p.string().optional()}),cT=p.object({variables:eT.optional().describe("CSS variables for theming the app."),css:aT.optional().describe("CSS blocks that apps can inject.")}),Xk=p.object({method:p.literal("ui/resource-teardown"),params:p.object({})}),lT=p.record(p.string(),p.unknown()),Yy=p.object({text:p.object({}).optional().describe("Host supports text content blocks."),image:p.object({}).optional().describe("Host supports image content blocks."),audio:p.object({}).optional().describe("Host supports audio content blocks."),resource:p.object({}).optional().describe("Host supports resource content blocks."),resourceLink:p.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:p.object({}).optional().describe("Host supports structured content.")}),uT=p.object({method:p.literal("ui/notifications/request-teardown"),params:p.object({}).optional()}),dT=p.object({experimental:p.record(p.string(),p.record(p.string(),p.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p.object({}).optional().describe("Host supports opening external URLs."),downloadFile:p.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p.object({listChanged:p.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p.object({listChanged:p.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p.object({}).optional().describe("Host accepts log messages."),sandbox:p.object({permissions:Jg.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Vg.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Yy.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Yy.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p.object({tools:p.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),pT=p.object({experimental:p.record(p.string(),p.record(p.string(),p.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p.object({listChanged:p.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:p.array(tc).optional().describe("Display modes the app supports.")}),mT=p.object({method:p.literal("ui/notifications/initialized"),params:p.object({}).optional()}),Qk=p.object({csp:Vg.optional().describe("Content Security Policy configuration for UI resources."),permissions:Jg.optional().describe("Sandbox permissions requested by the UI resource."),domain:p.string().optional().describe(`Dedicated origin for view sandbox.
98
+ - Empty or omitted \u2192 no network connections (secure default)`),resourceDomains:p.array(p.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"),frameDomains:p.array(p.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:p.array(p.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)")}),Yg=p.object({camera:p.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),wT=p.object({method:p.literal("ui/notifications/size-changed"),params:p.object({width:p.number().optional().describe("New width in pixels."),height:p.number().optional().describe("New height in pixels.")})}),h0=p.object({method:p.literal("ui/notifications/tool-input"),params:p.object({arguments:p.record(p.string(),p.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),m0=p.object({method:p.literal("ui/notifications/tool-input-partial"),params:p.object({arguments:p.record(p.string(),p.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),f0=p.object({method:p.literal("ui/notifications/tool-cancelled"),params:p.object({reason:p.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),RT=p.object({fonts:p.string().optional()}),xT=p.object({variables:ST.optional().describe("CSS variables for theming the app."),css:RT.optional().describe("CSS blocks that apps can inject.")}),g0=p.object({method:p.literal("ui/resource-teardown"),params:p.object({})}),PT=p.record(p.string(),p.unknown()),cv=p.object({text:p.object({}).optional().describe("Host supports text content blocks."),image:p.object({}).optional().describe("Host supports image content blocks."),audio:p.object({}).optional().describe("Host supports audio content blocks."),resource:p.object({}).optional().describe("Host supports resource content blocks."),resourceLink:p.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:p.object({}).optional().describe("Host supports structured content.")}),TT=p.object({method:p.literal("ui/notifications/request-teardown"),params:p.object({}).optional()}),ET=p.object({experimental:p.record(p.string(),p.record(p.string(),p.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p.object({}).optional().describe("Host supports opening external URLs."),downloadFile:p.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p.object({listChanged:p.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p.object({listChanged:p.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p.object({}).optional().describe("Host accepts log messages."),sandbox:p.object({permissions:Yg.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Gg.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:cv.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:cv.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p.object({tools:p.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),kT=p.object({experimental:p.record(p.string(),p.record(p.string(),p.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p.object({listChanged:p.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:p.array(oc).optional().describe("Display modes the app supports.")}),$T=p.object({method:p.literal("ui/notifications/initialized"),params:p.object({}).optional()}),S0=p.object({csp:Gg.optional().describe("Content Security Policy configuration for UI resources."),permissions:Yg.optional().describe("Sandbox permissions requested by the UI resource."),domain:p.string().optional().describe(`Dedicated origin for view sandbox.
99
99
 
100
100
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
101
101
 
@@ -109,14 +109,14 @@ Boolean requesting whether a visible border and background is provided by the ho
109
109
 
110
110
  - \`true\`: request visible border + background
111
111
  - \`false\`: request no visible border + background
112
- - omitted: host decides border`)}),Xy=p.object({method:p.literal("ui/request-display-mode"),params:p.object({mode:tc.describe("The display mode being requested.")})}),Qy=p.object({mode:tc.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),hT=p.union([p.literal("model"),p.literal("app")]).describe("Tool visibility scope - who can access the tool."),e$=p.object({resourceUri:p.string().optional(),visibility:p.array(hT).optional().describe(`Who can access this tool. Default: ["model", "app"]
112
+ - omitted: host decides border`)}),lv=p.object({method:p.literal("ui/request-display-mode"),params:p.object({mode:oc.describe("The display mode being requested.")})}),uv=p.object({mode:oc.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),CT=p.union([p.literal("model"),p.literal("app")]).describe("Tool visibility scope - who can access the tool."),_0=p.object({resourceUri:p.string().optional(),visibility:p.array(CT).optional().describe(`Who can access this tool. Default: ["model", "app"]
113
113
  - "model": Tool visible to and callable by the agent
114
- - "app": Tool callable by the app from this server only`),csp:p.never().optional(),permissions:p.never().optional()}),t$=p.object({mimeTypes:p.array(p.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),fT=p.object({method:p.literal("ui/download-file"),params:p.object({contents:p.array(p.union([mo,ho])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),gT=p.object({method:p.literal("ui/message"),params:p.object({role:p.literal("user").describe('Message role, currently only "user" is supported.'),content:p.array(Zt).describe("Message content blocks (text, image, etc.).")})}),r$=p.object({method:p.literal("ui/notifications/sandbox-resource-ready"),params:p.object({html:p.string().describe("HTML content to load into the inner iframe."),sandbox:p.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Vg.optional().describe("CSP configuration from resource metadata."),permissions:Jg.optional().describe("Sandbox permissions from resource metadata.")})}),o$=p.object({method:p.literal("ui/notifications/tool-result"),params:Ir.describe("Standard MCP tool execution result.")}),tv=p.object({toolInfo:p.object({id:yt.optional().describe("JSON-RPC id of the tools/call request."),tool:Cr.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:XP.optional().describe("Current color theme preference."),styles:cT.optional().describe("Style configuration for theming the app."),displayMode:tc.optional().describe("How the UI is currently displayed."),availableDisplayModes:p.array(tc).optional().describe("Display modes the host supports."),containerDimensions:p.union([p.object({height:p.number().describe("Fixed container height in pixels.")}),p.object({maxHeight:p.union([p.number(),p.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(p.union([p.object({width:p.number().describe("Fixed container width in pixels.")}),p.object({maxWidth:p.union([p.number(),p.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
115
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:p.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:p.string().optional().describe("User's timezone in IANA format."),userAgent:p.string().optional().describe("Host application identifier."),platform:p.union([p.literal("web"),p.literal("desktop"),p.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p.object({touch:p.boolean().optional().describe("Whether the device supports touch input."),hover:p.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p.object({top:p.number().describe("Top safe area inset in pixels."),right:p.number().describe("Right safe area inset in pixels."),bottom:p.number().describe("Bottom safe area inset in pixels."),left:p.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),n$=p.object({method:p.literal("ui/notifications/host-context-changed"),params:tv.describe("Partial context update containing only changed fields.")}),ST=p.object({method:p.literal("ui/update-model-context"),params:p.object({content:p.array(Zt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:p.record(p.string(),p.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),_T=p.object({method:p.literal("ui/initialize"),params:p.object({appInfo:Lt.describe("App identification (name and version)."),appCapabilities:pT.describe("Features and capabilities this app provides."),protocolVersion:p.string().describe("Protocol version this app supports.")})}),bT=p.object({protocolVersion:p.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Lt.describe("Host application identification and version."),hostCapabilities:dT.describe("Features and capabilities provided by the host."),hostContext:tv.describe("Rich context about the host environment.")}).passthrough();var Qn=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,r){this.eventTarget=t,this.eventSource=r,this.messageListener=o=>{if(r&&o.source!==this.eventSource){console.debug("Ignoring message from unknown source",o);return}let n=vt.safeParse(o.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):o.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,o):(console.error("Failed to parse message",n.error.message,o),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,r){t.method!==YP&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var yT=[ev],es=class extends Hu{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Fg;_methods=new Hg;setRequestHandler=(...t)=>{let[r,...o]=Gy("request",t)??t;this._methods.claim(r,"setRequestHandler"),super.setRequestHandler.call(this,r,...o)};setNotificationHandler=(...t)=>{let[r,...o]=Gy("notification",t)??t;this._methods.claim(r,"setNotificationHandler"),super.setNotificationHandler.call(this,r,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...r)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...r)};_wrapHandler(t,r){let o=super._wrapHandler(t,r);return t==="ui/initialize"||t==="ping"?o:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),o(n,s))}eventSchemas={sizechange:iT,sandboxready:sT,initialized:mT,requestteardown:uT,loggingmessage:fo};setEventHandler(t,r){this._ensureEventSlot(t),this._events.setHandler(t,r)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,r){this._ensureEventSlot(t),this._events.addEventListener(t,r)}removeEventListener(t,r){this._events.removeEventListener(t,r)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let r=this.eventSchemas[t];if(!r)throw Error(`Unknown event: ${String(t)}`);let o=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{o(n.params)}):this.setNotificationHandler(r.shape.method.value,{params:r.shape.params},n=>o(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,r,o){r&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,r,o,n){super(n),this._client=t,this._hostInfo=r,this._hostCapabilities=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:_T.shape.params,result:bT},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,i)=>(this.onping?.(s.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:Xy.shape.params,result:Qy},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:gT.shape.params,result:nT},async(r,o)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(r,o)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:tT.shape.params,result:rT},async(r,o)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(r,o)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:fT.shape.params,result:oT},async(r,o)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(r,o)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:Xy.shape.params,result:Qy},async(r,o)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(r,o)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:ST.shape.params,result:kr},async(r,o)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(r,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(r,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(r.params,o)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(r,o)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(r.params,o)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(r,o)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(r.params,o)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(r,o)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(r.params,o)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(r,o)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(r.params,o)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(r,o)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(r.params,o)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let r=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:yT.includes(r)?r:ev,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let r={},o=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],i=t[n];vT(s,i)||(r[n]=i,o=!0)}o&&(this._hostContext=t,this.sendHostContextChange(r))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,r){return this.request({method:"ui/resource-teardown",params:t},lT,r)}sendResourceTeardown=this.teardownResource;callTool(t,r){return this.request({method:"tools/call",params:t},r)}listTools(t,r){return this.request({method:"tools/list",params:t},r)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let r=this._client.getServerCapabilities();if(!r)throw Error("Client server capabilities not available");r.tools&&(this.oncalltool=async(o,n)=>this._client.request({method:"tools/call",params:o},{signal:n.mcpReq.signal}),r.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",o=>this.sendToolListChanged(o.params))),r.resources&&(this.onlistresources=async(o,n)=>this._client.request({method:"resources/list",params:o},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(o,n)=>this._client.request({method:"resources/templates/list",params:o},{signal:n.mcpReq.signal}),this.onreadresource=async(o,n)=>this._client.request({method:"resources/read",params:o},{signal:n.mcpReq.signal}),r.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",o=>this.sendResourceListChanged(o.params))),r.prompts&&(this.onlistprompts=async(o,n)=>this._client.request({method:"prompts/list",params:o},{signal:n.mcpReq.signal}),r.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",o=>this.sendPromptListChanged(o.params)))}return super.connect(t)}};function vT(e,t){return JSON.stringify(e)===JSON.stringify(t)}var rv=[200,800],zT=e=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function RT(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function ov(e,{signal:t,onDiagnostic:r,wait:o=RT}={}){return async n=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);return t?.throwIfAborted(),s>1&&r?.({state:"recovered",uri:n.uri,attempt:s}),i}catch(i){if(t?.throwIfAborted(),!zT(i))throw i;if(s>rv.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(new Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=rv[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function nv(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}r.has(o.group)||r.set(o.group,[]),r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function sv({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l}){let d=(await s({uri:o})).contents.find(y=>y.mimeType==="text/html;profile=mcp-app"&&typeof y.text=="string");if(!d)throw new Error("Comparison preview App is unavailable.");let m=document.createElement("iframe");m.title=t,m.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),m.src=r,e.append(m);let h=new es(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(m)});h.onreadresource=s,h.oncalltool=i,h.onerror=l,h.onloggingmessage=y=>{y.logger==="ads-preview"&&y.data?.state==="error"&&l(new Error(y.data.message))};let g,v=new Promise((y,D)=>{g=setTimeout(()=>D(new Error("Comparison App initialization timed out.")),15e3),h.oninitialized=()=>{clearTimeout(g),y()}});h.onsandboxready=()=>h.sendSandboxResourceReady({html:d.text,csp:d._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let w=new ResizeObserver(()=>h.setHostContext(a(m)));try{await Promise.all([h.connect(new Qn(m.contentWindow,m.contentWindow)),v]),w.observe(m),await h.sendToolInput({arguments:{}}),await h.sendToolResult(n)}catch(y){throw w.disconnect(),await h.close(),y}finally{clearTimeout(g)}return{updateResult:y=>h.sendToolResult(y),refreshContext:()=>h.setHostContext(a(m)),async close(){w.disconnect();try{await h.teardownResource({},{timeout:500})}catch{}await h.close()}}}var G=e=>document.getElementById(e),ht=new URLSearchParams(location.search),cv=ht.get("scenario")??ht.get("category"),wT=["tokens","components","patterns","composition","drafts"],Xu=[],_e,Oe=cv,To=ht.get("split")==="1",nc=[],xo=0,Qg;async function od(){let e=nc;nc=[],await Promise.allSettled(e.map(t=>t.close()))}var Te=document.createElement("button");Te.id="split-view";Te.setAttribute("aria-label","Split view");Te.setAttribute("aria-pressed","false");Te.disabled=!0;Te.title="Select a draft with an accepted version to compare";Te.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';G("viewport").before(Te);var ne="tokens",He={},iv=new Map,Gu=!0,Kg=[],Gg=[],sc=[],Yu,be,Xe,ts,ic,rc,lr=0,rs=ht.get("capture")!=="1"&&ht.get("viewport")==="phone",Ar=ht.get("capture")==="1"&&ht.get("theme")==="dark"?"dark":"light";ht.get("capture")==="1"&&(document.documentElement.dataset.capture="true");document.documentElement.dataset.theme=Ar;var Bg,lv=!0,Qu=!1,ed,Yg,nd=!1,ac=!1,Po,Nr,Wg=0,oc,td=new AbortController,Rt=new By({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),qr=(e,t={})=>Rt.callTool({name:e,arguments:t}),rd=ov(e=>Rt.readResource(e,{signal:td.signal}),{signal:td.signal,onDiagnostic:e=>{e.state==="retry"&&(document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1)),console.warn("ADS resource transport",e)}}),xT=async e=>JSON.parse((await rd({uri:e})).contents.find(t=>typeof t.text=="string").text);function uv(e){let t=sc.find(r=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw new Error("This tool is not callable from an App.");return Rt.callTool(e)}function Ve(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";G("status").textContent=o,G("status").dataset.error=String(t),G("status").setAttribute("role",t?"alert":"status"),G("preview-status").dataset.phase=r,G("preview-status").title=o,G("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
116
- `)[0]}`)}function dv(){Ve(be?"Updating preview\u2026":"Opening preview\u2026",!1,"reloading")}function Xg(e=be){return e?.key===`${ne}:${He[ne]}`}function ur(e=!1){e&&(rc=be?.key),ic=void 0,G("loader").hidden=!0,G("preview").setAttribute("aria-busy","false")}function av(e){let t=new URL(location.href);for(let r of["scenario","category","draft","split"])t.searchParams.delete(r);return e&&ne==="drafts"?(t.searchParams.set("draft",e),Oe&&t.searchParams.set("scenario",Oe),To&&t.searchParams.set("split","1")):e&&t.searchParams.set("scenario",e),t.pathname+t.search+t.hash}function PT(){return ne==="tokens"?Kg:ne==="drafts"?Xu:Gg.filter(e=>e.kind===ne)}function eS(){return{theme:Ar,displayMode:"inline",containerDimensions:{width:G("frame-slot").clientWidth,height:G("frame-slot").clientHeight}}}function os(){let e=PT();e.some(o=>o.id===He[ne])||(He[ne]=e[0]?.id??null),history.replaceState(null,"",av(He[ne]));let t=G("sidebar").scrollTop;G("entries").setAttribute("aria-label",ne[0].toUpperCase()+ne.slice(1));let r=o=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("button");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title="Open draft preview",s.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),ne="drafts",He.drafts=o.drafts[0].id,Oe=o.id,os(),Mr({force:!0}).catch(wt)}),n.append(s)}return n.href=av(o.id),o.id===He[ne]&&n.setAttribute("aria-current","page"),n.addEventListener("click",s=>{s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),ne==="drafts"&&He.drafts!==o.id&&(Oe=void 0),He[ne]=o.id,os(),Mr().catch(wt))}),n};G("entries").replaceChildren(...nv(e).flatMap(o=>{if(!o.label)return o.entries.map(r);let n=`${ne}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=iv.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{s.isConnected&&iv.set(n,s.open)}),[s]})),G("sidebar").scrollTop=t;for(let o of G("sections").querySelectorAll("button"))o.dataset.section===ne?o.setAttribute("aria-current","page"):o.removeAttribute("aria-current")}function wt(e){!nd&&!ac&&(ur(),G("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),G("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Ve(`${e.message}${be?`
117
- The retained preview is not verified against the current source.`:""}`,!0))}async function Eo(e){if(e){try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}}function pv(){if(nd||ac)return;ac=!0,td.abort(),++lr,clearTimeout(ed),ur(),Ve("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Xe;Xe=void 0,Eo(e),++xo,od()}async function mv(){Yu=(await qr("ads_status")).structuredContent,G("title").textContent=(Yu.drafts?.previewOnly?"Draft \xB7 ":"")+Yu.project.showcase.title,G("title").title=Yu.projectRoot;let e=[],t;do{let i=await Rt.listTools(t?{cursor:t}:{});e.push(...i.tools),t=i.nextCursor}while(t);sc=e,Kg=(await qr("ads_tokens",{limit:1})).structuredContent.categories;let r=[],o=0;do{let i=(await qr("ads_scenarios",{limit:50,offset:o})).structuredContent;r.push(...i.scenarios),o=i.nextOffset}while(o!==void 0);if(Gg=r,sc.some(i=>i.name==="ads_drafts")){let i=[],a=0;do{let l=(await qr("ads_drafts",{limit:50,offset:a})).structuredContent;i.push(...l.drafts),a=l.nextOffset}while(a!==void 0);Xu=i}if(Gu&&ht.get("draft")&&(ne="drafts",He.drafts=ht.get("draft")),ne==="drafts"){Xu.some(a=>a.id===He.drafts)||(_e=void 0);let i=Xu.find(a=>a.id===He.drafts);if(be?.draft&&i&&_e&&i.revision!==_e.revision){let a=await qr("ads_show_draft",{id:i.id,...Oe?{scenario:Oe}:{}});if(a.isError)throw new Error(a.content?.find(l=>l.type==="text")?.text??"Draft preview failed.");_e=a.structuredContent,Qg=a,Oe=_e.scenario,fv();for(let l of nc)l.side==="draft"&&await l.updateResult(a)}}let n=Gu?cv:He[ne],s=Gg.find(i=>i.id===n);ne!=="drafts"&&s&&wT.includes(s.kind)?(ne=s.kind,He[ne]=s.id):Gu&&Kg.some(i=>i.id===n)&&(He.tokens=n),Gu=!1,os()}function Mr({force:e=!1}={}){if(ac)return Promise.resolve();let t=He[ne],r=ne==="drafts"?`${ne}:${t}:${Oe??""}:${To}`:`${ne}:${t}`;if(ts?.key===r)return ts.promise;if(!e&&!ts&&be?.key===r)return Promise.resolve();let o={key:r};return ts=o,o.promise=TT(t,r,ne==="tokens").finally(()=>{ts===o&&(ts=void 0)}),o.promise}async function TT(e,t,r){let o=++lr;ic=!0,G("loader").hidden=t===rc,G("preview").setAttribute("aria-busy","true");try{if(++xo,await od(),G("draft-controls").hidden=ne!=="drafts",ne==="drafts"){if(await Eo(Xe),Xe=void 0,Po=void 0,Nr=void 0,!e){G("frame-slot").replaceChildren(),be=void 0,_e=void 0,Te.disabled=!0,Te.setAttribute("aria-pressed","false"),ur(),Ve("No drafts. Accepted project source is unchanged.");return}let l=await qr("ads_show_draft",{id:e,...Oe?{scenario:Oe}:{}});if(o!==lr)return;if(l.isError)throw new Error(l.content?.find(u=>u.type==="text")?.text??"Draft preview failed");_e=l.structuredContent,Qg=l,Oe=_e.scenario,be={key:`drafts:${e}:${Oe??""}:${To}`,id:e,generation:o,draft:!0},fv(),await hv(),os(),ur(!0),Ve("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Te.disabled=!0,Te.setAttribute("aria-pressed","false"),!e&&!r){if(await Eo(Xe),o!==lr)return;Xe=void 0,be=void 0,rc=void 0,Po=void 0,Nr=void 0,G("frame-slot").replaceChildren(),ur(),Ve("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let n=sc.find(l=>l.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!n?._meta?.ui?.resourceUri)throw new Error("The server did not expose a preview App tool.");let s=r?e?{category:e}:{}:{id:e};n.inputSchema?.properties?.waitFor&&(s.waitFor=ht.get("capture")==="1"||ht.get("waitFor")==="verified"?"verified":"compiled"),dv();let i=await qr(n.name,s);if(o!==lr)return;if(i.isError)throw Object.assign(new Error(i.content?.find(l=>l.type==="text")?.text??"Preview build failed."),i.structuredContent?.failure);be={key:t,id:e,generation:o,token:r&&!i.structuredContent?.scenario,build:i.structuredContent?.build,manifestRevision:i.structuredContent?.manifestRevision};let a=await ET(n._meta.ui.resourceUri);if(o!==lr)return;if(Po==="ui://ads/preview"&&!be.manifestRevision)throw new Error("The resource preview has no manifest revision.");rc!==t&&(rc=void 0),await a.sendToolInput({arguments:s}),await a.sendToolResult(i),o===lr&&!i.structuredContent?.manifestUri&&(ur(!0),Ve(""))}catch(n){o===lr&&wt(n)}}async function ET(e){if(Po===e&&Nr)return Nr;let t=++Wg,r=Xe;Xe=void 0,Po=e,Nr=(async()=>{await Eo(r);let o=await rd({uri:e});if(t!==Wg||nd||ac)throw new Error("Preview opening was superseded.");let n=o.contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=oc,G("frame-slot").replaceChildren(s);let i=new es(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:eS()});Xe=i,i.onreadresource=u=>rd(u),i.oncalltool=uv,i.onloggingmessage=u=>{i!==Xe||u.logger!=="ads-preview"||be?.generation!==lr||!Xg()||u.data?.id!==be?.id||(u.data.state==="ready"&&u.data.revision===be.manifestRevision?(ur(!0),Ve("")):u.data.state==="checking"&&(!ic||u.data.revision===be.manifestRevision)?(ur(!0),Ve("Checking changes\u2026")):u.data.state==="loading"?Ve("Updating preview\u2026",!1,"reloading"):u.data.state==="reverting"?Ve("Restoring the last verified preview\u2026",!1,"reverting"):u.data.code==="ADS_PREVIEW_REOPEN"?(Xe=void 0,Po=void 0,Nr=void 0,dv(),Eo(i).then(()=>Mr({force:!0})).catch(wt)):u.data.state==="error"&&(ur(),Ve(u.data.message,!0)))},i.onerror=wt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(new Error("MCP App initialization timed out.")),15e3),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Qn(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Eo(i),u}finally{clearTimeout(a)}return i})();try{return await Nr}catch(o){throw t===Wg&&(Po=void 0,Nr=void 0),o}}async function kT(){let e=be;if(!e||e.draft||e.token||ic||!Xg(e))return;let t=await xT("ads://project/build");if(be!==e||ic||!Xg(e))return;let r=t.previews.find(o=>o.id===e.id);if(!r){Ve("The selected scenario is no longer registered.",!0);return}if(!(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)){if(r.state==="error"){Ve(`Preview build failed. Showing an earlier view.
114
+ - "app": Tool callable by the app from this server only`),csp:p.never().optional(),permissions:p.never().optional()}),b0=p.object({mimeTypes:p.array(p.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),IT=p.object({method:p.literal("ui/download-file"),params:p.object({contents:p.array(p.union([po,ho])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),OT=p.object({method:p.literal("ui/message"),params:p.object({role:p.literal("user").describe('Message role, currently only "user" is supported.'),content:p.array(Lt).describe("Message content blocks (text, image, etc.).")})}),y0=p.object({method:p.literal("ui/notifications/sandbox-resource-ready"),params:p.object({html:p.string().describe("HTML content to load into the inner iframe."),sandbox:p.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Gg.optional().describe("CSP configuration from resource metadata."),permissions:Yg.optional().describe("Sandbox permissions from resource metadata.")})}),v0=p.object({method:p.literal("ui/notifications/tool-result"),params:Cr.describe("Standard MCP tool execution result.")}),pv=p.object({toolInfo:p.object({id:_t.optional().describe("JSON-RPC id of the tools/call request."),tool:$r.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:fT.optional().describe("Current color theme preference."),styles:xT.optional().describe("Style configuration for theming the app."),displayMode:oc.optional().describe("How the UI is currently displayed."),availableDisplayModes:p.array(oc).optional().describe("Display modes the host supports."),containerDimensions:p.union([p.object({height:p.number().describe("Fixed container height in pixels.")}),p.object({maxHeight:p.union([p.number(),p.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(p.union([p.object({width:p.number().describe("Fixed container width in pixels.")}),p.object({maxWidth:p.union([p.number(),p.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
115
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:p.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:p.string().optional().describe("User's timezone in IANA format."),userAgent:p.string().optional().describe("Host application identifier."),platform:p.union([p.literal("web"),p.literal("desktop"),p.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p.object({touch:p.boolean().optional().describe("Whether the device supports touch input."),hover:p.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p.object({top:p.number().describe("Top safe area inset in pixels."),right:p.number().describe("Right safe area inset in pixels."),bottom:p.number().describe("Bottom safe area inset in pixels."),left:p.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),z0=p.object({method:p.literal("ui/notifications/host-context-changed"),params:pv.describe("Partial context update containing only changed fields.")}),NT=p.object({method:p.literal("ui/update-model-context"),params:p.object({content:p.array(Lt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:p.record(p.string(),p.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),qT=p.object({method:p.literal("ui/initialize"),params:p.object({appInfo:Mt.describe("App identification (name and version)."),appCapabilities:kT.describe("Features and capabilities this app provides."),protocolVersion:p.string().describe("Protocol version this app supports.")})}),AT=p.object({protocolVersion:p.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Mt.describe("Host application identification and version."),hostCapabilities:ET.describe("Features and capabilities provided by the host."),hostContext:pv.describe("Rich context about the host environment.")}).passthrough();var Yn=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,r){this.eventTarget=t,this.eventSource=r,this.messageListener=o=>{if(r&&o.source!==this.eventSource){console.debug("Ignoring message from unknown source",o);return}let n=bt.safeParse(o.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):o.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,o):(console.error("Failed to parse message",n.error.message,o),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,r){t.method!==mT&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var MT=[dv],Xn=class extends Wu{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Wg;_methods=new Kg;setRequestHandler=(...t)=>{let[r,...o]=av("request",t)??t;this._methods.claim(r,"setRequestHandler"),super.setRequestHandler.call(this,r,...o)};setNotificationHandler=(...t)=>{let[r,...o]=av("notification",t)??t;this._methods.claim(r,"setNotificationHandler"),super.setNotificationHandler.call(this,r,...o)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...r)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...r)};_wrapHandler(t,r){let o=super._wrapHandler(t,r);return t==="ui/initialize"||t==="ping"?o:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),o(n,s))}eventSchemas={sizechange:wT,sandboxready:zT,initialized:$T,requestteardown:TT,loggingmessage:mo};setEventHandler(t,r){this._ensureEventSlot(t),this._events.setHandler(t,r)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,r){this._ensureEventSlot(t),this._events.addEventListener(t,r)}removeEventListener(t,r){this._events.removeEventListener(t,r)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let r=this.eventSchemas[t];if(!r)throw Error(`Unknown event: ${String(t)}`);let o=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{o(n.params)}):this.setNotificationHandler(r.shape.method.value,{params:r.shape.params},n=>o(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,r,o){r&&o&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,r,o,n){super(n),this._client=t,this._hostInfo=r,this._hostCapabilities=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:qT.shape.params,result:AT},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,i)=>(this.onping?.(s.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:lv.shape.params,result:uv},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:OT.shape.params,result:vT},async(r,o)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(r,o)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:_T.shape.params,result:bT},async(r,o)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(r,o)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:IT.shape.params,result:yT},async(r,o)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(r,o)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:lv.shape.params,result:uv},async(r,o)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(r,o)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:NT.shape.params,result:Er},async(r,o)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(r,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(r,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(r.params,o)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(r,o)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(r.params,o)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(r,o)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(r.params,o)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(r,o)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(r.params,o)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(r,o)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(r.params,o)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(r,o)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(r.params,o)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let r=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:MT.includes(r)?r:dv,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let r={},o=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],i=t[n];jT(s,i)||(r[n]=i,o=!0)}o&&(this._hostContext=t,this.sendHostContextChange(r))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,r){return this.request({method:"ui/resource-teardown",params:t},PT,r)}sendResourceTeardown=this.teardownResource;callTool(t,r){return this.request({method:"tools/call",params:t},r)}listTools(t,r){return this.request({method:"tools/list",params:t},r)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let r=this._client.getServerCapabilities();if(!r)throw Error("Client server capabilities not available");r.tools&&(this.oncalltool=async(o,n)=>this._client.request({method:"tools/call",params:o},{signal:n.mcpReq.signal}),r.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",o=>this.sendToolListChanged(o.params))),r.resources&&(this.onlistresources=async(o,n)=>this._client.request({method:"resources/list",params:o},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(o,n)=>this._client.request({method:"resources/templates/list",params:o},{signal:n.mcpReq.signal}),this.onreadresource=async(o,n)=>this._client.request({method:"resources/read",params:o},{signal:n.mcpReq.signal}),r.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",o=>this.sendResourceListChanged(o.params))),r.prompts&&(this.onlistprompts=async(o,n)=>this._client.request({method:"prompts/list",params:o},{signal:n.mcpReq.signal}),r.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",o=>this.sendPromptListChanged(o.params)))}return super.connect(t)}};function jT(e,t){return JSON.stringify(e)===JSON.stringify(t)}var hv=[200,800],LT=e=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function UT(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function mv(e,{signal:t,onDiagnostic:r,wait:o=UT}={}){return async n=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);return t?.throwIfAborted(),s>1&&r?.({state:"recovered",uri:n.uri,attempt:s}),i}catch(i){if(t?.throwIfAborted(),!LT(i))throw i;if(s>hv.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(new Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=hv[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function fv(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}r.has(o.group)||r.set(o.group,[]),r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function Sv({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:c,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:s,callTool:i,context:a,onError:c,onState:u},h=n,m,g,y,v=!1;function z(){v||y||(u?.({state:"loading"}),y=Promise.resolve().then(async()=>{if(await g,await m?.close(),!v){g=gv({...d,result:h,onReopen:z});try{m=await g}finally{g=void 0}}}).catch(U=>{v||c(U)}).finally(()=>{y=void 0}))}g=gv({...d,result:h,onReopen:z});try{m=await g}finally{g=void 0}return{async updateResult(U){h=U,await y,v||await m.updateResult(h)},refreshContext(){!v&&!y&&m.refreshContext()},async close(){v=!0,await y,await m?.close()}}}async function gv({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:c,onState:u,onReopen:d}){let h=!1,g=(await s({uri:o})).contents.find(T=>T.mimeType==="text/html;profile=mcp-app"&&typeof T.text=="string");if(!g)throw new Error("Comparison preview App is unavailable.");let y=document.createElement("iframe");y.title=t,y.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),y.src=r,e.append(y);let v=new Xn(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(y)});v.onreadresource=s,v.oncalltool=i,v.onerror=T=>{h||c(T)},v.onloggingmessage=T=>{if(!(h||T.logger!=="ads-preview")){if(T.data?.code==="ADS_PREVIEW_REOPEN"){d();return}u?.(T.data),T.data?.state==="error"&&c(new Error(T.data.message))}};let z,U=new Promise((T,D)=>{z=setTimeout(()=>D(new Error("Comparison App initialization timed out.")),15e3),v.oninitialized=()=>{clearTimeout(z),T()}});v.onsandboxready=()=>v.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>v.setHostContext(a(y)));try{await Promise.all([v.connect(new Yn(y.contentWindow,y.contentWindow)),U]),H.observe(y),await v.sendToolInput({arguments:{}}),await v.sendToolResult(n)}catch(T){throw H.disconnect(),y.remove(),await v.close(),T}finally{clearTimeout(z)}return{updateResult:T=>v.sendToolResult(T),refreshContext:()=>v.setHostContext(a(y)),async close(){h=!0,H.disconnect();try{await v.teardownResource({},{timeout:500})}catch{}await v.close(),y.remove()}}}function Xg(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function _v(e,t,r,o=new Map){let n=new Map(r.map(({id:c,title:u,revision:d,state:h,preview:m})=>[c,{id:c,title:u,revision:d,state:h,...m?{preview:m}:{}}])),s=new Map(e.map(c=>[c.id,{...c,drafts:(c.drafts??[]).flatMap(u=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let c of t){let u=s.get(c.id);s.set(c.id,{...u,...c,kind:"tokens",drafts:u?.drafts??[]})}let i=(c,u)=>c==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===c:Xg(c,u.id)),a=(c,u)=>{c.drafts.some(d=>d.id===u.id)||c.drafts.push(n.get(u.id))};for(let c of r){let u=o.get(c.id);for(let d of u?.scenarios??[]){if(!c.units.some(m=>i(m,d)))continue;let h=s.get(d.id);h||(h={...d,draftOnly:!0,drafts:[]},s.set(d.id,h)),a(h,c)}}for(let c of r)for(let u of c.units){let d=u.split("/")[0];if(!["tokens","components","patterns","composition"].includes(d))continue;let h=[...s.values()].filter(m=>i(u,m));if(h.length)for(let m of h)a(m,c);else s.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(c.id)]})}return{scenarios:[...s.values()],categories:[...s.values()].filter(c=>c.kind==="tokens")}}function bv(e,t,r){let o=e.drafts?.find(c=>c.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find(c=>c.id===o.id)??o.preview),s=o?n?.scenarios?.find(c=>c.id===e.id)??n:t?.previews?.find(c=>c.id===e.id)??e.build,i=s?.state==="error"?"error":s?.state==="checking"||s?.live?"checking":s?.building||["queued","building"].includes(s?.state)?"building":s?.current?"ready":s?.stale?"stale":"unreported";return{state:i,label:`${o?"Draft \xB7 ":""}${{error:"Preview build failed",checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"}[i]}${o&&i==="ready"?" \xB7 unaccepted":""}`}}var yv={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var Q=e=>document.getElementById(e),vt=new URLSearchParams(location.search),vv=vt.get("scenario")??vt.get("category"),ZT=["tokens","components","patterns","composition"],es=[],ze,od=vt.get("draft"),nS=[],Rv=[],sS=new Map,os=vt.get("split")==="1",tS,ns=[],cr=0,ad;async function cd(){let e=ns;ns=[],await Promise.allSettled(e.map(t=>t.close()))}var pt=document.createElement("button");pt.id="split-view";pt.setAttribute("aria-label","Split view");pt.setAttribute("aria-pressed","false");pt.disabled=!0;pt.title="Select a draft with an accepted version to compare";pt.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';Q("viewport").before(pt);var be="tokens",dt={},zv=new Map,ed=!0,iS=[],aS=[],ac=[],nc,cS,Se,Ke,Qn,ts,sc,Ft=0,rs=vt.get("capture")!=="1"&&vt.get("viewport")==="phone",Nr=vt.get("capture")==="1"&&vt.get("theme")==="dark"?"dark":"light";vt.get("capture")==="1"&&(document.documentElement.dataset.capture="true");document.documentElement.dataset.theme=Nr;var Qg,xv=!0,td=!1,nd,rS,ld=!1,cc=!1,Ro,Or,eS=0,ic,sd=new AbortController,zt=new nv({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),qr=(e,t={})=>zt.callTool({name:e,arguments:t}),id=mv(e=>zt.readResource(e,{signal:sd.signal}),{signal:sd.signal,onDiagnostic:e=>{e.state==="retry"&&(document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1)),console.warn("ADS resource transport",e)}}),DT=async e=>JSON.parse((await id({uri:e})).contents.find(t=>typeof t.text=="string").text);function Pv(e){let t=ac.find(r=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw new Error("This tool is not callable from an App.");return zt.callTool(e)}function ve(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";Q("status").textContent=o,Q("status").dataset.error=String(t),Q("status").setAttribute("role",t?"alert":"status"),Q("preview-status").dataset.phase=r,Q("preview-status").title=o,Q("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
116
+ `)[0]}`)}function Tv(){ve(Se?"Updating preview\u2026":"Opening preview\u2026",!1,"reloading")}function ss(){return uc().find(e=>e.id===dt[be])}function lc(e=ss()){let t=es.find(r=>r.id===od&&sS.get(r.id)?.scenario===e?.id);return e?.drafts?.find(r=>r.id===od)??t??e?.drafts?.[0]}function Ev(){return!!(lc()&&(ss()?.draftOnly||os))}function lS(){return`${be}:${dt[be]}${Ev()?`:draft:${lc().id}`:""}`}function rd(e=Se){return e?.key===lS()}function kv(){({scenarios:aS,categories:iS}=_v(nS,Rv,es,sS))}function FT(e){sS.set(e.structuredContent.id,e.structuredContent),kv()}async function uS(e,t){let r=ss()?.id===t&&ss().pendingDraftScenario||e.units?.includes(t)&&!nS.some(n=>n.id===t),o=await qr("ads_show_draft",{id:e.id,...!r&&t?{scenario:t}:{}});if(o.isError)throw new Error(o.content?.find(n=>n.type==="text")?.text??"Draft preview failed.");if(r){let n=o.structuredContent.scenarios.find(s=>t==="tokens"?s.kind==="tokens":s.unit?s.unit===t:Xg(t,s.id));if(!n)throw new Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(n.id!==o.structuredContent.scenario&&(o=await qr("ads_show_draft",{id:e.id,scenario:n.id})),o.isError)throw new Error(o.content?.find(s=>s.type==="text")?.text??"Draft preview failed.")}return FT(o),o}function Ar(e=!1){e&&(sc=Se?.key),ts=void 0,Q("loader").hidden=!0,Q("preview").setAttribute("aria-busy","false")}function wv(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);e&&t.searchParams.set("scenario",e);let r=uc().find(n=>n.id===e),o=lc(r);return o&&(r.draftOnly||os)&&(t.searchParams.set("draft",o.id),r.draftOnly||t.searchParams.set("split","1")),t.pathname+t.search+t.hash}function uc(){return be==="tokens"?iS:aS.filter(e=>e.kind===be)}function $v(e,t){let{state:r,label:o}=bv(t,cS,od),n=e.querySelector(".entry-preview");n||(n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n)),n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${yv[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function dS(){return{theme:Nr,displayMode:"inline",containerDimensions:{width:Q("frame-slot").clientWidth,height:Q("frame-slot").clientHeight}}}function dc(){let e=uc();e.some(o=>o.id===dt[be])||(dt[be]=e[0]?.id??null),history.replaceState(null,"",wv(dt[be]));let t=Q("sidebar").scrollTop;Q("entries").setAttribute("aria-label",be[0].toUpperCase()+be.slice(1));let r=o=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title=o.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",n.append(" ",s)}return n.href=wv(o.id),n.dataset.scenario=o.id,$v(n,o),o.id===dt[be]&&n.setAttribute("aria-current","page"),n.addEventListener("click",s=>{s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),dt[be]=o.id,dc(),Po().catch(lr))}),n};Q("entries").replaceChildren(...fv(e).flatMap(o=>{if(!o.label)return o.entries.map(r);let n=`${be}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=zv.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{s.isConnected&&zv.set(n,s.open)}),[s]})),Q("sidebar").scrollTop=t;for(let o of Q("sections").querySelectorAll("button"))o.dataset.section===be?o.setAttribute("aria-current","page"):o.removeAttribute("aria-current");oS()}function lr(e){!ld&&!cc&&(Ar(),Q("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),Q("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",ve(`${e.message}${Se?`
117
+ The retained preview is not verified against the current source.`:""}`,!0))}async function xo(e){if(e){try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}}function Cv(){if(ld||cc)return;cc=!0,sd.abort(),++Ft,clearTimeout(nd),Ar(),ve("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ke;Ke=void 0,xo(e),++cr,cd()}async function Iv(){nc=(await qr("ads_status")).structuredContent,cS=nc.build,Q("title").textContent=(nc.drafts?.previewOnly?"Draft \xB7 ":"")+nc.project.showcase.title,Q("title").title=nc.projectRoot;let e=[],t;do{let c=await zt.listTools(t?{cursor:t}:{});e.push(...c.tools),t=c.nextCursor}while(t);ac=e,Rv=(await qr("ads_tokens",{limit:1})).structuredContent.categories;let r=[],o=0;do{let c=(await qr("ads_scenarios",{limit:50,offset:o})).structuredContent;r.push(...c.scenarios),o=c.nextOffset}while(o!==void 0);if(nS=r,ac.some(c=>c.name==="ads_drafts")){let c=[],u=0;do{let d=(await qr("ads_drafts",{limit:50,offset:u})).structuredContent;c.push(...d.drafts),u=d.nextOffset}while(u!==void 0);es=c}kv();let n=ed?vv:dt[be],s=ed&&es.find(c=>c.id===od),i=Se?.draft&&es.find(c=>c.id===Se.draftId);if(s||i&&ze&&(i.revision!==ze.revision||ze.discovery?.state==="pending")){let c=await uS(s||i,s?vv:ze.scenario);if(s&&(n=c.structuredContent.scenario),Se?.draft&&i){ze=c.structuredContent,ad=c;for(let u of ns)u.side==="draft"&&await u.updateResult(c)}}let a=aS.find(c=>c.id===n);a&&ZT.includes(a.kind)?(be=a.kind,dt[be]=a.id):ed&&iS.some(c=>c.id===n)&&(dt.tokens=n),ed=!1,dc()}function Po({force:e=!1}={}){if(cc)return Promise.resolve();let t=dt[be],r=lS();if(Qn?.key===r)return Qn.promise;if(!e&&!Qn&&Se?.key===r)return Promise.resolve();let o={key:r};return Qn=o,o.promise=HT(t,r,be==="tokens").finally(()=>{Qn===o&&(Qn=void 0)}),o.promise}async function HT(e,t,r){let o=++Ft;ts=!0,Q("loader").hidden=t===sc,Q("preview").setAttribute("aria-busy","true");try{if(++cr,await cd(),o!==Ft)return;if(Ev()){await xo(Ke),Ke=void 0,Ro=void 0,Or=void 0;let c=lc(),u=await uS(c,e);if(o!==Ft)return;ze=u.structuredContent,ad=u,(ss()?.pendingDraftScenario||!uc().some(d=>d.id===e))&&(dt[be]=ze.scenario),Se={key:lS(),id:ze.scenario,draftId:c.id,generation:o,draft:!0},oS(),await BT(),dc(),Ar(!0),ve("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(ze=void 0,oS(),!e&&!r){if(await xo(Ke),o!==Ft)return;Ke=void 0,Se=void 0,sc=void 0,Ro=void 0,Or=void 0,Q("frame-slot").replaceChildren(),Ar(),ve("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let n=ac.find(c=>c.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!n?._meta?.ui?.resourceUri)throw new Error("The server did not expose a preview App tool.");let s=r?e?{category:e}:{}:{id:e};n.inputSchema?.properties?.waitFor&&(s.waitFor=vt.get("capture")==="1"||vt.get("waitFor")==="verified"?"verified":"compiled"),Tv();let i=await qr(n.name,s);if(o!==Ft)return;if(i.isError)throw Object.assign(new Error(i.content?.find(c=>c.type==="text")?.text??"Preview build failed."),i.structuredContent?.failure);Se={key:t,id:e,generation:o,token:r&&!i.structuredContent?.scenario,build:i.structuredContent?.build,manifestRevision:i.structuredContent?.manifestRevision};let a=await VT(n._meta.ui.resourceUri);if(o!==Ft)return;if(Ro==="ui://ads/preview"&&!Se.manifestRevision)throw new Error("The resource preview has no manifest revision.");sc!==t&&(sc=void 0),await a.sendToolInput({arguments:s}),await a.sendToolResult(i),o===Ft&&!i.structuredContent?.manifestUri&&(Ar(!0),ve(""))}catch(n){o===Ft&&lr(n)}}async function VT(e){if(Ro===e&&Or)return Or;let t=++eS,r=Ke;Ke=void 0,Ro=e,Or=(async()=>{await xo(r);let o=await id({uri:e});if(t!==eS||ld||cc)throw new Error("Preview opening was superseded.");let n=o.contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=ic,Q("frame-slot").replaceChildren(s);let i=new Xn(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:dS()});Ke=i,i.onreadresource=u=>id(u),i.oncalltool=Pv,i.onloggingmessage=u=>{if(i!==Ke||u.logger!=="ads-preview"||Se?.generation!==Ft||!rd()||u.data?.id!==Se?.id)return;let d=u.data.revision===Se.manifestRevision||u.data.selectionRevision===Se.manifestRevision;u.data.state==="ready"&&d?(Se.manifestRevision=u.data.revision,Ar(!0),ve("")):u.data.state==="checking"&&(!ts||d)?(Ar(!0),ve("Checking changes\u2026")):u.data.state==="loading"?ve("Updating preview\u2026",!1,"reloading"):u.data.state==="reverting"?ve("Restoring the last verified preview\u2026",!1,"reverting"):u.data.code==="ADS_PREVIEW_REOPEN"?(Ke=void 0,Ro=void 0,Or=void 0,Tv(),xo(i).then(()=>Po({force:!0})).catch(lr)):u.data.state==="error"&&(Ar(),ve(u.data.message,!0))},i.onerror=lr;let a,c=new Promise((u,d)=>{a=setTimeout(()=>d(new Error("MCP App initialization timed out.")),15e3),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Yn(s.contentWindow,s.contentWindow)),c])}catch(u){throw await xo(i),u}finally{clearTimeout(a)}return i})();try{return await Or}catch(o){throw t===eS&&(Ro=void 0,Or=void 0),o}}async function JT(){let e=Se,t=await DT("ads://project/build");cS=t;for(let o of Q("entries").querySelectorAll("a[data-scenario]")){let n=uc().find(s=>s.id===o.dataset.scenario);n&&$v(o,n)}if(!e||e.token||ts||!rd(e))return;if(e.draft){let o=t.drafts?.find(i=>i.id===e.draftId),n=o?.scenarios?.find(i=>i.id===ze?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=es.find(a=>a.id===e.draftId);if(i){let a=await uS(i,ze.scenario);if(Se!==e||ts||!rd(e))return;ze=a.structuredContent,ad=a;for(let c of ns)c.side==="draft"&&await c.updateResult(a)}}n?.state==="error"?ve("Draft preview build failed. Showing the previous preview.",!0):n?.building?ve(n.live||n.state==="checking"?"Draft preview compiled; checking changes\u2026":"Building draft preview\u2026 Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling"):n?.current&&tS?.state==="ready"&&ve("Draft preview ready \xB7 unaccepted.");return}if(Se!==e||ts||!rd(e))return;let r=t.previews.find(o=>o.id===e.id);if(!r){ve("The selected scenario is no longer registered.",!0);return}if(!(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)){if(r.state==="error"){ve(`Preview build failed. Showing an earlier view.
118
118
  ${r.diagnostics.map(o=>`${o.file??""}${o.line?`:${o.line}`:""}: ${o.message}`).join(`
119
- `)}`,!0);return}if(["idle","building"].includes(r.state)){Ve(r.live?"Checking changes\u2026":"Compiling changes\u2026 The current view is the previous preview.",!1,r.live?"checking":"compiling");return}r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session)&&await Mr({force:!0})}}function cc(e=!1,t=!1){Qu||=e,t&&be?.token&&(be.key="invalidated"),clearTimeout(ed),!lv&&(ed=setTimeout(()=>{if(Bg){cc(e,t);return}Bg=(async()=>{Qu&&(Qu=!1,await mv()),await Mr(),await kT()})().catch(wt).finally(()=>{Bg=void 0})},150))}async function hv(){if(!_e)return;let e=++xo;await od(),Te.disabled=!_e.acceptedExists,Te.title=_e.acceptedExists?"Compare accepted and draft versions":"No accepted version yet";let t=To&&_e.acceptedExists;Te.setAttribute("aria-pressed",String(t));let r=document.createElement("div");r.className="draft-comparison",r.dataset.split=String(t);for(let o of t?["accepted","draft"]:["draft"]){let n=document.createElement("section");n.className="draft-version";let s=document.createElement("h2");s.textContent=o==="accepted"?"Accepted":"Draft \xB7 unaccepted";let i=document.createElement("div");i.className="draft-stage",i.dataset.version=o,n.append(s,i),r.append(n)}G("frame-slot").replaceChildren(r),await Promise.all([...r.querySelectorAll(".draft-stage")].map(async o=>{let n=o.dataset.version,s=n==="draft"?Qg:await qr("ads_show_scenario",{id:Oe,waitFor:"compiled"});if(s.isError)throw new Error(s.content?.find(l=>l.type==="text")?.text??"Comparison build failed.");if(e!==xo)return;let i=sc.find(l=>l.name===(n==="draft"?"ads_show_draft":"ads_show_scenario")),a=await sv({slot:o,title:n==="draft"?"Draft version":"Accepted version",sandboxUrl:oc,resourceUri:i._meta.ui.resourceUri,result:s,readResource:rd,callTool:uv,context:l=>({theme:Ar,displayMode:"inline",containerDimensions:{width:l.clientWidth,height:l.clientHeight}}),onError:l=>{e===xo&&wt(l)}});e!==xo?await a.close():nc.push({...a,side:n})}))}function fv(){let e={draft:"Unaccepted",checking:"Checking acceptance",failed:"Acceptance failed",conflict:"Source conflict",interrupted:"Acceptance interrupted","dependency-error":"Dependency needs attention"};G("draft-state").textContent=`${e[_e.state]??_e.state}${_e.dependencies.length?` \xB7 ${_e.dependencies.length} draft ${_e.dependencies.length===1?"dependency":"dependencies"}`:""}`,G("draft-state").title=_e.dependencies.join(", "),G("draft-scenario").replaceChildren(..._e.scenarios.map(t=>{let r=document.createElement("option");return r.value=t.id,r.textContent=t.title,r.selected=t.id===Oe,r})),Te.disabled=!_e.acceptedExists,Te.title=_e.acceptedExists?"Compare accepted and draft versions":"No accepted version yet"}Te.addEventListener("click",()=>{To=!To,be?.draft&&(be.key=`drafts:${be.id}:${Oe??""}:${To}`),hv().catch(wt),os()});G("draft-scenario").addEventListener("change",()=>{Oe=G("draft-scenario").value,Mr({force:!0}).catch(wt)});for(let e of G("sections").querySelectorAll("button"))e.addEventListener("click",()=>{ne=e.dataset.section,os(),Mr().catch(wt)});var tS=window.matchMedia("(max-width: 760px)");function gv(e){document.body.classList.toggle("collapsed",e),G("pane-toggle").setAttribute("aria-expanded",String(!e)),G("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),G("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",G("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var rS=()=>gv(G("header").hidden||tS.matches);rS();tS.addEventListener("change",rS);G("pane-toggle").addEventListener("click",()=>gv(!document.body.classList.contains("collapsed")));function Sv(){document.documentElement.dataset.viewport=rs?"phone":"auto",G("viewport").setAttribute("aria-pressed",String(rs)),G("viewport").title=rs?"Use available preview width":"Preview at phone width (390 px)"}Sv();G("viewport").addEventListener("click",()=>{rs=!rs,Sv();let e=new URL(location.href);rs?e.searchParams.set("viewport","phone"):e.searchParams.delete("viewport"),history.replaceState(null,"",e.pathname+e.search+e.hash)});G("theme").addEventListener("click",()=>{Ar=Ar==="light"?"dark":"light",document.documentElement.dataset.theme=Ar,G("theme").setAttribute("aria-label",Ar==="dark"?"Use light theme":"Use dark theme"),G("theme").title=G("theme").getAttribute("aria-label"),G("theme").querySelector("svg").innerHTML=Ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Xe?.setHostContext(eS())});G("theme").addEventListener("click",()=>{for(let e of nc)e.refreshContext()});G("minimize").addEventListener("click",()=>{G("header").hidden=!0,document.body.classList.add("collapsed")});var _v=new ResizeObserver(()=>Xe?.setHostContext(eS()));_v.observe(G("frame-slot"));window.addEventListener("pagehide",()=>{nd=!0,td.abort(),clearTimeout(ed),_v.disconnect(),tS.removeEventListener("change",rS),Eo(Xe),++xo,od(),Yg?.close(),Rt.close()},{once:!0});Rt.onclose=pv;Rt.setNotificationHandler("notifications/resources/list_changed",()=>cc(!0));Rt.setNotificationHandler("notifications/tools/list_changed",()=>cc(!0));Rt.setNotificationHandler("notifications/resources/updated",({params:e})=>cc(e.uri==="ads://project/drafts",e.uri==="ads://project/tokens"));try{if(oc=(await fetch("/host.json").then(e=>e.json())).sandboxUrl,!oc||new URL(oc).origin===location.origin)throw new Error("The separate-origin MCP App sandbox is unavailable.");await Rt.connect(new Wy(new URL("/mcp",location.href))),Yg=await Rt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/scenarios","ads://project/status","ads://project/drafts"]}),Yg.closed.then(e=>{e!=="local"&&pv()}),await mv(),lv=!1,await Mr(),Qu&&cc()}catch(e){wt(e)}
119
+ `)}`,!0);return}if(["idle","building"].includes(r.state)){ve(r.live?"Checking changes\u2026":"Compiling changes\u2026 The current view is the previous preview.",!1,r.live?"checking":"compiling");return}r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session)&&await Po({force:!0})}}function pc(e=!1,t=!1){td||=e,t&&Se?.token&&(Se.key="invalidated"),clearTimeout(nd),!xv&&(nd=setTimeout(()=>{if(Qg){pc(e,t);return}Qg=(async()=>{td&&(td=!1,await Iv()),await Po(),await JT()})().catch(lr).finally(()=>{Qg=void 0})},150))}async function BT(){if(!ze)return;let e=ze,t=ad;tS=void 0;let r=++cr;if(await cd(),r!==cr)return;let o=os&&e.acceptedExists;pt.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft \xB7 unaccepted";let c=document.createElement("div");c.className="draft-stage",c.dataset.version=s,i.append(a,c),n.append(i)}Q("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async s=>{let i=s.dataset.version,a=i==="draft"?t:await qr("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw new Error(a.content?.find(d=>d.type==="text")?.text??"Comparison build failed.");if(r!==cr)return;let c=ac.find(d=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await Sv({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:ic,resourceUri:c._meta.ui.resourceUri,result:a,readResource:id,callTool:Pv,context:d=>({theme:Nr,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:d=>{r===cr&&lr(d)},onState:d=>{r!==cr||i!=="draft"||(tS=d,d.state==="ready"?ve("Draft preview ready \xB7 unaccepted."):d.state==="checking"?ve("Draft preview compiled; checking changes\u2026",!1,"checking"):["loading","reverting"].includes(d.state)&&ve("Updating draft preview\u2026",!1,"reloading"))}});r!==cr?await u.close():ns.push({...u,side:i})}))}function oS(){let e=ss(),t=!!lc(e)&&!e?.draftOnly;pt.disabled=!t,pt.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",pt.setAttribute("aria-pressed",String(t&&os));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&ze){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft \xB7 ${o[ze.state]??ze.state}`,r.title=ze.dependencies?.length?`Draft dependencies: ${ze.dependencies.join(", ")}`:""}}pt.addEventListener("click",()=>{os=!os,dc(),Po().catch(lr)});for(let e of Q("sections").querySelectorAll("button"))e.addEventListener("click",()=>{be=e.dataset.section,dc(),Po().catch(lr)});var pS=window.matchMedia("(max-width: 760px)");function Ov(e){document.body.classList.toggle("collapsed",e),Q("pane-toggle").setAttribute("aria-expanded",String(!e)),Q("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),Q("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",Q("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var hS=()=>Ov(Q("header").hidden||pS.matches);hS();pS.addEventListener("change",hS);Q("pane-toggle").addEventListener("click",()=>Ov(!document.body.classList.contains("collapsed")));function Nv(){document.documentElement.dataset.viewport=rs?"phone":"auto",Q("viewport").setAttribute("aria-pressed",String(rs)),Q("viewport").title=rs?"Use available preview width":"Preview at phone width (390 px)"}Nv();Q("viewport").addEventListener("click",()=>{rs=!rs,Nv();let e=new URL(location.href);rs?e.searchParams.set("viewport","phone"):e.searchParams.delete("viewport"),history.replaceState(null,"",e.pathname+e.search+e.hash)});Q("theme").addEventListener("click",()=>{Nr=Nr==="light"?"dark":"light",document.documentElement.dataset.theme=Nr,Q("theme").setAttribute("aria-label",Nr==="dark"?"Use light theme":"Use dark theme"),Q("theme").title=Q("theme").getAttribute("aria-label"),Q("theme").querySelector("svg").innerHTML=Nr==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ke?.setHostContext(dS())});Q("theme").addEventListener("click",()=>{for(let e of ns)e.refreshContext()});Q("minimize").addEventListener("click",()=>{Q("header").hidden=!0,document.body.classList.add("collapsed")});var qv=new ResizeObserver(()=>Ke?.setHostContext(dS()));qv.observe(Q("frame-slot"));window.addEventListener("pagehide",()=>{ld=!0,sd.abort(),clearTimeout(nd),qv.disconnect(),pS.removeEventListener("change",hS),xo(Ke),++cr,cd(),rS?.close(),zt.close()},{once:!0});zt.onclose=Cv;zt.setNotificationHandler("notifications/resources/list_changed",()=>pc(!0));zt.setNotificationHandler("notifications/tools/list_changed",()=>pc(!0));zt.setNotificationHandler("notifications/resources/updated",({params:e})=>pc(e.uri==="ads://project/drafts",e.uri==="ads://project/tokens"));try{if(ic=(await fetch("/host.json").then(e=>e.json())).sandboxUrl,!ic||new URL(ic).origin===location.origin)throw new Error("The separate-origin MCP App sandbox is unavailable.");await zt.connect(new sv(new URL("/mcp",location.href))),rS=await zt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/scenarios","ads://project/status","ads://project/drafts"]}),rS.closed.then(e=>{e!=="local"&&Cv()}),await Iv(),xv=!1,await Po(),td&&pc()}catch(e){lr(e)}
120
120
  /*! Bundled license information:
121
121
 
122
122
  @modelcontextprotocol/client/dist/src-WCy6ifGf.mjs: