@zenku/cli-node 0.1.43 → 0.1.44

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 (2) hide show
  1. package/package.json +1 -1
  2. package/zenku-bundle.mjs +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenku/cli-node",
3
- "version": "0.1.43",
3
+ "version": "0.1.44",
4
4
  "description": "Zenku CLI (Node.js) — runs under node, no native binary.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "bin": {
package/zenku-bundle.mjs CHANGED
@@ -925,7 +925,7 @@ ${new Date().toISOString()}
925
925
  `),process.stdout.write(`Last Exit: ${u?.lastExitCode??"-"}
926
926
  `),process.stdout.write(`Last Err: ${u?.lastError||"-"}
927
927
  `)}})}catch(a){ot("%s",Gr(a))}}),t.command("remove").description("Remove a schedule").option("--scope <scope>","scope: user|system","user").argument("<id>","schedule ID").action((r,i)=>{try{let a=IA(i.scope);T2(a,!1);let o=pb(a),s=o.findIndex(u=>u.id===r);s===-1&&ot('schedule "%s" not found',r),o.splice(s,1),P$(a,o);let l=aw(a);RLe(l,r),Xk(a,l),Nt({json:()=>({success:!0,id:r,scope:a}),human:()=>On('Schedule "%s" removed',r)})}catch(a){ot("%s",Gr(a))}});function e(r,i,a){T2(i,!1);let o=pb(i),s=cle(o,r);s.enabled=a,s.updatedAt=new Date().toISOString(),P$(i,o)}t.command("enable").description("Enable a schedule").option("--scope <scope>","scope: user|system","user").argument("<id>","schedule ID").action((r,i)=>{try{let a=IA(i.scope);e(r,a,!0),Nt({json:()=>({success:!0,id:r,enabled:!0,scope:a}),human:()=>On('Schedule "%s" enabled',r)})}catch(a){ot("%s",Gr(a))}}),t.command("disable").description("Disable a schedule").option("--scope <scope>","scope: user|system","user").argument("<id>","schedule ID").action((r,i)=>{try{let a=IA(i.scope);e(r,a,!1),Nt({json:()=>({success:!0,id:r,enabled:!1,scope:a}),human:()=>On('Schedule "%s" disabled',r)})}catch(a){ot("%s",Gr(a))}}),t.command("run").description("Run a schedule immediately").option("--scope <scope>","scope: user|system","user").option("--dry-run","print execution details without running").argument("<id>","schedule ID").action(async(r,i)=>{try{let a=IA(i.scope),o=!!i.dryRun;T2(a,o);let s=pb(a),l=cle(s,r),u=await kLe(a,l,o);Nt({json:()=>u,human:()=>{if(u.dryRun){mn("Dry run: %s",lle(l));return}(u.exitCode??1)===0?On('Schedule "%s" ran successfully',r):mn('Schedule "%s" finished with exit code %s',r,eo(u.exitCode??"null"))}})}catch(a){ot("%s",Gr(a))}}),t.command("tick").description("Run one scheduler tick (intended for host scheduler integration)").option("--scope <scope>","scope: user|system","user").action(async r=>{try{let i=IA(r.scope);T2(i,!1);let a=await OLe(i);Nt({json:()=>a,human:()=>{a.locked?mn("Tick skipped: another tick is already running."):mn("Tick completed: executed=%s skipped=%s",String(a.executed),String(a.skipped))}})}catch(i){ot("%s",Gr(i))}});let n=new Jn("host").description("Manage host scheduler integration");return n.command("install").description("Install host scheduler integration").option("--scope <scope>","scope: user|system","user").option("--dry-run","show generated artifacts and commands").action(r=>{try{let i=IA(r.scope),a=!!r.dryRun;T2(i,a);let s=k$().install(i,a);Nt({json:()=>s,human:()=>{On("%s host scheduler %s",a?"Previewed":"Installed",i);for(let l of s.actions)mn("- %s",l)}})}catch(i){ot("%s",Gr(i))}}),n.command("uninstall").description("Remove host scheduler integration").option("--scope <scope>","scope: user|system","user").option("--dry-run","show generated commands").action(r=>{try{let i=IA(r.scope),a=!!r.dryRun;T2(i,a);let s=k$().uninstall(i,a);Nt({json:()=>s,human:()=>{On("%s host scheduler %s",a?"Previewed uninstall for":"Uninstalled",i);for(let l of s.actions)mn("- %s",l)}})}catch(i){ot("%s",Gr(i))}}),n.command("status").description("Show host scheduler status").option("--scope <scope>","scope: user|system","user").action(r=>{try{let i=IA(r.scope),o=k$().status(i);Nt({json:()=>o,human:()=>{mn("Platform: %s",o.platform),mn("Scope: %s",o.scope),mn("Installed: %s",o.installed?"yes":"no");for(let[s,l]of Object.entries(o.details))mn("%s: %s",s,eo(l))}})}catch(i){ot("%s",Gr(i))}}),t.addCommand(n),t}function PLe(t){t.addCommand(CNt())}import{mkdirSync as TNt,readFileSync as zLe,readdirSync as INt,statSync as DR,unlinkSync as wNt,writeFileSync as xNt}from"node:fs";import{basename as DNt,dirname as RNt,join as RR,relative as QLe}from"node:path";import{homedir as GLe,hostname as NNt}from"node:os";function ule(t){if(t)return t;let e=Si("CLAUDE_CONFIG_DIR");return e||RR(GLe(),".claude")}function LLe(t){if(t)return t;let e=Si("ZENKU_MACHINE_ID");return e||NNt()}function dle(t){let e=[],n;try{n=INt(t,{withFileTypes:!0})}catch{return e}for(let r of n){let i=RR(t,r.name);r.isDirectory()?e.push(...dle(i)):r.isFile()&&r.name.endsWith(".jsonl")&&e.push(i)}return e}function F0(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function ONt(t,e){let n=DR(t);return Date.now()-n.mtimeMs>=e*86400*1e3}function FLe(t,e,n){let r=QLe(e,t);return`${n}/${r}`}function ple(t){return t.replace(/'/g,"\\'")}async function ULe(t,e,n,r,i,a,o){let l=DR(e).size,u=null;try{let h=await t.collection("session_files").getFirstListItem(`key='${ple(n)}'`);u={id:h.id,size:h.size}}catch{}if(u&&u.size===l)return{status:"skipped",key:n,size:l};if(o)return u?mn("[DRY-RUN] Would update: %s (%s -> %s)",n,F0(u.size),F0(l)):mn("[DRY-RUN] Would upload: %s (%s)",n,F0(l)),{status:u?"updated":"uploaded",key:n,size:l};let p=zLe(e),f=new File([p],DNt(e),{type:"application/x-ndjson"});try{return u?(await t.collection("session_files").update(u.id,{size:l,file:f}),On("Updated: %s (%s -> %s)",n,F0(u.size),F0(l)),{status:"updated",key:n,size:l}):(await t.collection("session_files").create({key:n,machine_id:r,size:l,tenant_id:i,account_id:a,file:f}),On("Uploaded: %s (%s)",n,F0(l)),{status:"uploaded",key:n,size:l})}catch(h){let _=h instanceof Error?h.message:String(h);return{status:"failed",key:n,size:l,error:_}}}function kNt(){let t=new Jn("sessions").description("Upload and manage Claude Code session transcripts");return t.command("sync").description("Scan local Claude Code sessions and upload new/changed files").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").option("--dry-run","show what would be uploaded without uploading").option("--cleanup-days <days>","delete local files older than N days after successful upload").action(async e=>{let n=ule(e.claudeDir),r=LLe(e.machineId),i=e.dryRun??!1,a=e.cleanupDays?Number(e.cleanupDays):0;a&&(Number.isNaN(a)||a<1)&&ot("--cleanup-days requires a positive integer");let o=RR(n,"projects"),s=dle(o);if(s.length===0){mn("No session files found in %s",o);return}let{client:l,profile:u}=await ii("library"),p=mp(u),f=cc(u);a>0&&mn("Cleanup mode: syncing files older than %s days",a),mn("Scanning %s sessions in %s",s.length,o);let h=0,_=0,y=0,E=0,S=0,T=0;for(let N of s){if(a>0&&!ONt(N,a)){T++;continue}let O=FLe(N,o,r),M=await ULe(l,N,O,r,p,f,i);switch(M.status){case"uploaded":h++;break;case"updated":_++;break;case"skipped":y++;break;case"failed":mn("Failed: %s \u2014 %s",O,M.error),E++;continue}if(a>0)if(i)mn("[DRY-RUN] Would delete local: %s",N);else try{wNt(N),S++}catch{mn("Failed to delete local: %s",N)}}mn(""),a>0?mn("Summary: %s total, %s too new (<%sd), %s uploaded, %s updated, %s unchanged, %s deleted locally, %s failed",s.length,T,a,h,_,y,S,E):mn("Summary: %s total, %s uploaded, %s updated, %s unchanged, %s failed",s.length,h,_,y,E)}),t.command("list").description("List Claude Code session files").option("--remote","list uploaded session files from PocketBase").option("--claude-dir <path>","Claude config directory").action(async e=>{if(e.remote){let{client:n}=await ii("library"),r=await dn("Fetching session files...",()=>n.collection("session_files").getList(1,200,{sort:"-created"}));Nt({json:()=>r.items,human:()=>{let i=r.items.map(a=>[a.id,a.key,a.machine_id,F0(a.size),a.created]);Yi(["ID","KEY","MACHINE","SIZE","CREATED"],i)}})}else{let n=ule(e.claudeDir),r=RR(n,"projects"),i=dle(r);Nt({json:()=>i.map(a=>{let o=DR(a);return{path:a,size:o.size,modified:o.mtime}}),human:()=>{let a=i.map(o=>{let s=DR(o);return[QLe(r,o),F0(s.size),s.mtime.toISOString().slice(0,19)]});Yi(["PATH","SIZE","MODIFIED"],a),mn(`
928
- %s files, %s total`,i.length,F0(i.reduce((o,s)=>o+DR(s).size,0)))}})}}),t.command("upload").description("Upload a single session file").option("--hook","hook mode: read session path from stdin JSON").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").argument("[file]","path to .jsonl file (when not using --hook)").action(async(e,n)=>{let r=ule(n.claudeDir),i=LLe(n.machineId),a=RR(r,"projects"),o;if(n.hook){let _;try{_=zLe(0,"utf-8")}catch{ot("failed to read from stdin")}let y;try{y=JSON.parse(_)}catch{ot("invalid JSON on stdin")}let E=y.transcript_path;E||ot("no transcript_path in hook input"),o=E.replace(/^~/,GLe())}else e?o=e:ot("provide a file path or use --hook to read from stdin");try{DR(o)}catch{ot("file not found: %s",o)}let s=FLe(o,a,i),{client:l,profile:u}=await ii("library"),p=mp(u),f=cc(u),h=await ULe(l,o,s,i,p,f,!1);h.status==="failed"&&ot("upload failed: %s",h.error),Nt({json:()=>h,human:()=>{h.status==="skipped"&&mn("Skipped (unchanged): %s",s)}})}),t.command("download").description("Download session files from PocketBase").argument("[dir]","output directory",".").option("--key <key>","download a specific file by key").option("--machine-id <id>","download all files from a specific machine").action(async(e,n)=>{let{client:r}=await ii("library"),i=[];n.key&&i.push(`key='${ple(n.key)}'`),n.machineId&&i.push(`machine_id='${ple(n.machineId)}'`);let a=i.length>0?i.join(" && "):"",o=await dn("Fetching session files...",()=>r.collection("session_files").getFullList({sort:"key",filter:a}));if(o.length===0){mn("No session files found");return}mn("Downloading %s files to %s",o.length,e);let s=await r.files.getToken(),l=0,u=0;for(let p of o){let f=p.key,h=p.file,_=RR(e,f),y=r.files.getURL(p,h,{token:s});try{let E=await fetch(y);if(!E.ok){mn("Failed: %s \u2014 HTTP %s",f,E.status),u++;continue}let S=Buffer.from(await E.arrayBuffer());TNt(RNt(_),{recursive:!0}),xNt(_,S),On("Downloaded: %s (%s)",f,F0(S.length)),l++}catch(E){let S=E instanceof Error?E.message:String(E);mn("Failed: %s \u2014 %s",f,S),u++}}mn(""),mn("Summary: %s total, %s downloaded, %s failed",o.length,l,u),Nt({json:()=>o.map(p=>({id:p.id,key:p.key,machine_id:p.machine_id,size:p.size})),human:()=>{}})}),t}function HLe(t){t.addCommand(kNt())}import{readFileSync as BNt}from"node:fs";import{dirname as MNt,join as PNt}from"node:path";import{fileURLToPath as LNt}from"node:url";function I2(){return"0.1.43"}import{basename as FNt}from"node:path";function $Le(){return!0}var UNt="@zenku";function jLe(t){return t.replace(/\\/g,"/")}function zNt(t){let e=t.toLowerCase();return e==="node"||e==="node.exe"||e==="bun"}function L$(){let{platform:t,arch:e}=process,n=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64"]),r=`${t}-${e}`;if(!n.has(r))throw new Error(`Unsupported platform: ${r}`);return`cli-${r}`}function qLe(t){return`${UNt}/${t}`}function F$(){if($Le())return"bundle";let t=jLe(process.execPath),e=jLe(process.argv[1]??""),n=FNt(process.execPath).toLowerCase();return n==="zenku-test"||n==="zenku-test.exe"||n.includes("zenku-test")||e.length>0&&(e.endsWith(".js")||e.endsWith(".cjs")||e.endsWith(".mjs"))||zNt(n)?"development":t.includes("/node_modules/")&&t.includes("/@zenku/")&&t.includes("/cli-")?"npm-managed":t.includes("/apps/zenku-cli/")||t.includes("/apps\\zenku-cli\\")?"development":"standalone"}function NR(t){return t==="bundle"?{command:"npm update -g @zenku/cli-node",message:"Self-upgrade is not available in bundle mode. Update via npm: npm update -g @zenku/cli-node"}:t==="npm-managed"?{command:"npm update -g @zenku/cli",message:"This install is npm-managed. Update via npm: npm update -g @zenku/cli"}:t==="development"?{command:"pnpm --filter @hikari/zenku-cli compile",message:"Development/test builds are not self-updated. Rebuild locally: pnpm --filter @hikari/zenku-cli compile"}:{command:"zenku upgrade",message:"Run `zenku upgrade` to install the latest binary."}}import{execFileSync as VLe}from"node:child_process";import{createHash as QNt}from"node:crypto";import{accessSync as GNt,chmodSync as HNt,constants as $Nt,copyFileSync as jNt,existsSync as qNt,mkdtempSync as VNt,readFileSync as YNt,renameSync as KNt,rmSync as WNt,unlinkSync as ZNt,writeFileSync as JNt}from"node:fs";import{tmpdir as XNt}from"node:os";import{dirname as fle,join as U$}from"node:path";function e9t(t){let e=t.trim().split(/\s+/)[0]??"",n=e.indexOf("-");if(n<=0||n>=e.length-1)throw new Error("invalid integrity format");let r=e.slice(0,n),i=e.slice(n+1);return{algo:r,hash:i}}function t9t(t,e){let{algo:n,hash:r}=e9t(e),i=YNt(t);if(QNt(n).update(i).digest("base64")!==r)throw new Error("checksum mismatch")}function YLe(t){try{return GNt(t,$Nt.W_OK),!0}catch{return!1}}function n9t(t,e){let n=fle(e),r=U$(n,`.zenku-upgrade-${process.pid}`);jNt(t,r),HNt(r,493);try{KNt(r,e)}catch{try{ZNt(r)}catch{}throw new Error(`failed to replace binary at ${e}`)}}async function r9t(t,e){let n=await fetch(t);if(!n.ok)throw new Error(`download failed: HTTP ${n.status}`);let r=Buffer.from(await n.arrayBuffer());JNt(e,r)}function KLe(t){return YLe(fle(t))}async function z$(t,e,n){let r=`${t.version}.tgz`,i=VNt(U$(XNt(),"zenku-upgrade-")),a=U$(i,r);try{await r9t(t.tarball,a),t9t(a,t.integrity),VLe("tar",["xzf",a,"-C",i],{stdio:"pipe"});let o=U$(i,"package","zenku");if(!qNt(o))throw new Error("downloaded package is missing binary");let s=fle(e);if(YLe(s)){n9t(o,e);return}if(!n.allowSudo)throw new Error(`no write permission for ${s}`);VLe("sudo",["install","-m","755",o,e],{stdio:"inherit"})}finally{WNt(i,{recursive:!0,force:!0})}}var WLe="https://registry.npmjs.org",i9t=15e3;async function ZLe(t){let e=new AbortController,n=setTimeout(()=>e.abort(),i9t);try{let r=await fetch(t,{signal:e.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);return await r.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("request timed out"):r}finally{clearTimeout(n)}}function JLe(t,e){if(!t.version)throw new Error(`registry response missing version for tag "${e}"`);if(!t.dist?.tarball)throw new Error(`registry response missing dist.tarball for v${t.version}`);if(!t.dist?.integrity)throw new Error(`registry response missing dist.integrity for v${t.version}`);return{version:t.version,tarball:t.dist.tarball,integrity:t.dist.integrity,tag:e}}async function Q$(t,e){let n=qLe(t),r=encodeURIComponent(n),i=e==="stable"?"stable":"latest";try{let a=await ZLe(`${WLe}/${r}/${i}`);return JLe(a,i)}catch(a){if(e==="stable"){let o=await ZLe(`${WLe}/${r}/latest`);return JLe(o,"latest")}throw a}}function a9t(){try{let t=cf(),{effective:e}=m2(t,void 0);return e.channel}catch{return"latest"}}function o9t(t){return t==="bundle"?"cli-node":L$()}function XLe(t){t.addCommand(new Jn("upgrade").description("Upgrade zenku to the latest version").action(async()=>{let e=F$(),n=NR(e),r=I2(),i=a9t();if(e==="development"){Nt({json:()=>({mode:e,message:n.message,previous:r,latest:r,upgraded:!1,command:n.command}),human:()=>{mn("%s",n.message)}});return}let a=o9t(e),o=await dn("Checking for updates...",()=>Q$(a,i));if(r===o.version){let s=`Already up to date (v${r}).`;Nt({json:()=>({previous:r,latest:o.version,upgraded:!1,mode:e,message:s}),human:()=>mn("%s",s)});return}if(e!=="standalone"){Nt({json:()=>({previous:r,latest:o.version,upgraded:!1,mode:e,command:n.command,message:n.message}),human:()=>{mn("v%s -> v%s",r,o.version),mn("%s",n.message),mn("Run: %s",n.command)}});return}mn("v%s -> v%s",r,o.version),await dn(`Downloading v${o.version}...`,async()=>{await z$(o,process.execPath,{allowSudo:!0})}),Nt({json:()=>({previous:r,latest:o.version,upgraded:!0,mode:e}),human:()=>mn("Upgraded zenku to v%s.",o.version)})}))}function s9t(t){return{name:t.name(),description:t.description??"",required:t.required,variadic:t.variadic,defaultValue:t.defaultValue}}function l9t(t){return{name:t.name(),flags:t.flags,description:t.description??"",short:t.short,long:t.long,required:t.required,optional:t.optional,variadic:t.variadic,mandatory:t.mandatory,defaultValue:t.defaultValue}}function eFe(t,e){let n=[...e,t.name()].filter(Boolean),r=t.commands.map(i=>eFe(i,n)).sort((i,a)=>i.commandPath.localeCompare(a.commandPath));return{name:t.name(),commandPath:n.join(" "),summary:t.summary(),description:t.description(),aliases:t.aliases(),usage:t.usage(),arguments:t.registeredArguments.map(s9t),options:t.options.filter(i=>i.long!=="--help").map(l9t),subcommands:r}}function tFe(t){let e=new Jn("meta").description("Machine-readable metadata for CLI integrations");e.command("commands").description("Print CLI command tree metadata").action(()=>{Nt({json:()=>eFe(t,[]),human:()=>{process.stdout.write("Use `zenku --json meta commands` for command metadata.\n")}})}),t.addCommand(e)}import{randomUUID as S$e}from"node:crypto";import uzt from"node:http";var Wi;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=r,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Wi||(Wi={}));var nFe;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(nFe||(nFe={}));var zn=Wi.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fb=t=>{switch(typeof t){case"undefined":return zn.undefined;case"string":return zn.string;case"number":return Number.isNaN(t)?zn.nan:zn.number;case"boolean":return zn.boolean;case"function":return zn.function;case"bigint":return zn.bigint;case"symbol":return zn.symbol;case"object":return Array.isArray(t)?zn.array:t===null?zn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?zn.promise:typeof Map<"u"&&t instanceof Map?zn.map:typeof Set<"u"&&t instanceof Set?zn.set:typeof Date<"u"&&t instanceof Date?zn.date:zn.object;default:return zn.unknown}};var en=Wi.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var fh=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(a){return a.message},r={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let s=r,l=0;for(;l<o.path.length;){let u=o.path[l];l===o.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(n(o))):s[u]=s[u]||{_errors:[]},s=s[u],l++}}};return i(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Wi.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];n[a]=n[a]||[],n[a].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fh.create=t=>new fh(t);var c9t=(t,e)=>{let n;switch(t.code){case en.invalid_type:t.received===zn.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case en.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Wi.jsonStringifyReplacer)}`;break;case en.unrecognized_keys:n=`Unrecognized key(s) in object: ${Wi.joinValues(t.keys,", ")}`;break;case en.invalid_union:n="Invalid input";break;case en.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Wi.joinValues(t.options)}`;break;case en.invalid_enum_value:n=`Invalid enum value. Expected ${Wi.joinValues(t.options)}, received '${t.received}'`;break;case en.invalid_arguments:n="Invalid function arguments";break;case en.invalid_return_type:n="Invalid function return type";break;case en.invalid_date:n="Invalid date";break;case en.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Wi.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case en.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case en.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case en.custom:n="Invalid input";break;case en.invalid_intersection_types:n="Intersection results could not be merged";break;case en.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case en.not_finite:n="Number must be finite";break;default:n=e.defaultError,Wi.assertNever(t)}return{message:n}},w2=c9t;var u9t=w2;function e8(){return u9t}var G$=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function Dn(t,e){let n=e8(),r=G$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===w2?void 0:w2].filter(i=>!!i)});t.common.issues.push(r)}var _p=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let i of n){if(i.status==="aborted")return Dr;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let a=await i.key,o=await i.value;r.push({key:a,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Dr;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[a.value]=o.value)}return{status:e.value,value:r}}},Dr=Object.freeze({status:"aborted"}),OR=t=>({status:"dirty",value:t}),mf=t=>({status:"valid",value:t}),mle=t=>t.status==="aborted",hle=t=>t.status==="dirty",ow=t=>t.status==="valid",t8=t=>typeof Promise<"u"&&t instanceof Promise;var nr;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(nr||(nr={}));var $g=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},rFe=(t,e)=>{if(ow(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fh(t.common.issues);return this._error=n,this._error}}};function li(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,s)=>{let{message:l}=t;return o.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:l??n??s.defaultError}},description:i}}var Ti=class{get description(){return this._def.description}_getType(e){return fb(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:fb(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _p,ctx:{common:e.parent.common,data:e.data,parsedType:fb(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(t8(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)},i=this._parseSync({data:e,path:r.path,parent:r});return rFe(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ow(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>ow(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)},i=this._parse({data:e,path:r.path,parent:r}),a=await(t8(i)?i:Promise.resolve(i));return rFe(r,a)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:en.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new xA({schema:this,typeName:Cr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return wA.create(this,this._def)}nullable(){return gb.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return D2.create(this)}promise(){return sw.create(this,this._def)}or(e){return LR.create([this,e],this._def)}and(e){return FR.create(this,e,this._def)}transform(e){return new xA({...li(this._def),schema:this,typeName:Cr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new HR({...li(this._def),innerType:this,defaultValue:n,typeName:Cr.ZodDefault})}brand(){return new H$({typeName:Cr.ZodBranded,type:this,...li(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new $R({...li(this._def),innerType:this,catchValue:n,typeName:Cr.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return $$.create(this,e)}readonly(){return jR.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},d9t=/^c[^\s-]{8,}$/i,p9t=/^[0-9a-z]+$/,f9t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,m9t=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,h9t=/^[a-z0-9_-]{21}$/i,g9t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A9t=/^[-+]?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)?)??$/,_9t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,y9t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gle,E9t=/^(?:(?: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])$/,b9t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,v9t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,S9t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,C9t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T9t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,iFe="((\\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])))",I9t=new RegExp(`^${iFe}$`);function aFe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function w9t(t){return new RegExp(`^${aFe(t)}$`)}function x9t(t){let e=`${iFe}T${aFe(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function D9t(t,e){return!!((e==="v4"||!e)&&E9t.test(t)||(e==="v6"||!e)&&v9t.test(t))}function R9t(t,e){if(!g9t.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function N9t(t,e){return!!((e==="v4"||!e)&&b9t.test(t)||(e==="v6"||!e)&&S9t.test(t))}var BR=class t extends Ti{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==zn.string){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.string,received:a.parsedType}),Dr}let r=new _p,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.length<a.value;(o||s)&&(i=this._getOrReturnCtx(e,i),o?Dn(i,{code:en.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&Dn(i,{code:en.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")_9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"email",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")gle||(gle=new RegExp(y9t,"u")),gle.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"emoji",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")m9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"uuid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")h9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"nanoid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")d9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cuid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")p9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cuid2",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")f9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"ulid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Dn(i,{validation:"url",code:en.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"regex",code:en.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?x9t(a).test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?I9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?w9t(a).test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?A9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"duration",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?D9t(e.data,a.version)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"ip",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?R9t(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"jwt",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?N9t(e.data,a.version)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cidr",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?C9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"base64",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?T9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"base64url",code:en.invalid_string,message:a.message}),r.dirty()):Wi.assertNever(a);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:en.invalid_string,...nr.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...nr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...nr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...nr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...nr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...nr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...nr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...nr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...nr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...nr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...nr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...nr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...nr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...nr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...nr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...nr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...nr.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...nr.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...nr.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...nr.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...nr.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...nr.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...nr.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...nr.errToObj(n)})}nonempty(e){return this.min(1,nr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};BR.create=t=>new BR({checks:[],typeName:Cr.ZodString,coerce:t?.coerce??!1,...li(t)});function O9t(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var n8=class t extends Ti{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==zn.number){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.number,received:a.parsedType}),Dr}let r,i=new _p;for(let a of this._def.checks)a.kind==="int"?Wi.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?O9t(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_finite,message:a.message}),i.dirty()):Wi.assertNever(a);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,nr.toString(n))}gt(e,n){return this.setLimit("min",e,!1,nr.toString(n))}lte(e,n){return this.setLimit("max",e,!0,nr.toString(n))}lt(e,n){return this.setLimit("max",e,!1,nr.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:nr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:nr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:nr.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:nr.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:nr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:nr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:nr.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Wi.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};n8.create=t=>new n8({checks:[],typeName:Cr.ZodNumber,coerce:t?.coerce||!1,...li(t)});var r8=class t extends Ti{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==zn.bigint)return this._getInvalidInput(e);let r,i=new _p;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Wi.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return Dn(n,{code:en.invalid_type,expected:zn.bigint,received:n.parsedType}),Dr}gte(e,n){return this.setLimit("min",e,!0,nr.toString(n))}gt(e,n){return this.setLimit("min",e,!1,nr.toString(n))}lte(e,n){return this.setLimit("max",e,!0,nr.toString(n))}lt(e,n){return this.setLimit("max",e,!1,nr.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:nr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:nr.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:nr.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};r8.create=t=>new r8({checks:[],typeName:Cr.ZodBigInt,coerce:t?.coerce??!1,...li(t)});var i8=class extends Ti{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==zn.boolean){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.boolean,received:r.parsedType}),Dr}return mf(e.data)}};i8.create=t=>new i8({typeName:Cr.ZodBoolean,coerce:t?.coerce||!1,...li(t)});var a8=class t extends Ti{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==zn.date){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.date,received:a.parsedType}),Dr}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_date}),Dr}let r=new _p,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):Wi.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:nr.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:nr.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};a8.create=t=>new a8({checks:[],coerce:t?.coerce||!1,typeName:Cr.ZodDate,...li(t)});var o8=class extends Ti{_parse(e){if(this._getType(e)!==zn.symbol){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.symbol,received:r.parsedType}),Dr}return mf(e.data)}};o8.create=t=>new o8({typeName:Cr.ZodSymbol,...li(t)});var MR=class extends Ti{_parse(e){if(this._getType(e)!==zn.undefined){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.undefined,received:r.parsedType}),Dr}return mf(e.data)}};MR.create=t=>new MR({typeName:Cr.ZodUndefined,...li(t)});var PR=class extends Ti{_parse(e){if(this._getType(e)!==zn.null){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.null,received:r.parsedType}),Dr}return mf(e.data)}};PR.create=t=>new PR({typeName:Cr.ZodNull,...li(t)});var s8=class extends Ti{constructor(){super(...arguments),this._any=!0}_parse(e){return mf(e.data)}};s8.create=t=>new s8({typeName:Cr.ZodAny,...li(t)});var x2=class extends Ti{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mf(e.data)}};x2.create=t=>new x2({typeName:Cr.ZodUnknown,...li(t)});var U0=class extends Ti{_parse(e){let n=this._getOrReturnCtx(e);return Dn(n,{code:en.invalid_type,expected:zn.never,received:n.parsedType}),Dr}};U0.create=t=>new U0({typeName:Cr.ZodNever,...li(t)});var l8=class extends Ti{_parse(e){if(this._getType(e)!==zn.undefined){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.void,received:r.parsedType}),Dr}return mf(e.data)}};l8.create=t=>new l8({typeName:Cr.ZodVoid,...li(t)});var D2=class t extends Ti{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==zn.array)return Dn(n,{code:en.invalid_type,expected:zn.array,received:n.parsedType}),Dr;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,s=n.data.length<i.exactLength.value;(o||s)&&(Dn(n,{code:o?en.too_big:en.too_small,minimum:s?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(Dn(n,{code:en.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(Dn(n,{code:en.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,s)=>i.type._parseAsync(new $g(n,o,n.path,s)))).then(o=>_p.mergeArray(r,o));let a=[...n.data].map((o,s)=>i.type._parseSync(new $g(n,o,n.path,s)));return _p.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:nr.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:nr.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:nr.toString(n)}})}nonempty(e){return this.min(1,e)}};D2.create=(t,e)=>new D2({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Cr.ZodArray,...li(e)});function kR(t){if(t instanceof mh){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=wA.create(kR(r))}return new mh({...t._def,shape:()=>e})}else return t instanceof D2?new D2({...t._def,type:kR(t.element)}):t instanceof wA?wA.create(kR(t.unwrap())):t instanceof gb?gb.create(kR(t.unwrap())):t instanceof hb?hb.create(t.items.map(e=>kR(e))):t}var mh=class t extends Ti{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=Wi.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==zn.object){let u=this._getOrReturnCtx(e);return Dn(u,{code:en.invalid_type,expected:zn.object,received:u.parsedType}),Dr}let{status:r,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof U0&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let l=[];for(let u of o){let p=a[u],f=i.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new $g(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof U0){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of s)l.push({key:{status:"valid",value:p},value:{status:"valid",value:i.data[p]}});else if(u==="strict")s.length>0&&(Dn(i,{code:en.unrecognized_keys,keys:s}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of s){let f=i.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new $g(i,f,i.path,p)),alwaysSet:p in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,h=await p.value;u.push({key:f,value:h,alwaysSet:p.alwaysSet})}return u}).then(u=>_p.mergeObjectSync(r,u)):_p.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return nr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:nr.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Cr.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of Wi.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of Wi.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return kR(this)}partial(e){let n={};for(let r of Wi.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of Wi.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof wA;)a=a._def.innerType;n[r]=a}return new t({...this._def,shape:()=>n})}keyof(){return oFe(Wi.objectKeys(this.shape))}};mh.create=(t,e)=>new mh({shape:()=>t,unknownKeys:"strip",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});mh.strictCreate=(t,e)=>new mh({shape:()=>t,unknownKeys:"strict",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});mh.lazycreate=(t,e)=>new mh({shape:t,unknownKeys:"strip",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});var LR=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new fh(s.ctx.common.issues));return Dn(n,{code:en.invalid_union,unionErrors:o}),Dr}if(n.common.async)return Promise.all(r.map(async a=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(l=>new fh(l));return Dn(n,{code:en.invalid_union,unionErrors:s}),Dr}}get options(){return this._def.options}};LR.create=(t,e)=>new LR({options:t,typeName:Cr.ZodUnion,...li(e)});var mb=t=>t instanceof UR?mb(t.schema):t instanceof xA?mb(t.innerType()):t instanceof zR?[t.value]:t instanceof QR?t.options:t instanceof GR?Wi.objectValues(t.enum):t instanceof HR?mb(t._def.innerType):t instanceof MR?[void 0]:t instanceof PR?[null]:t instanceof wA?[void 0,...mb(t.unwrap())]:t instanceof gb?[null,...mb(t.unwrap())]:t instanceof H$||t instanceof jR?mb(t.unwrap()):t instanceof $R?mb(t._def.innerType):[],Ale=class t extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.object)return Dn(n,{code:en.invalid_type,expected:zn.object,received:n.parsedType}),Dr;let r=this.discriminator,i=n.data[r],a=this.optionsMap.get(i);return a?n.common.async?a._parseAsync({data:n.data,path:n.path,parent:n}):a._parseSync({data:n.data,path:n.path,parent:n}):(Dn(n,{code:en.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Dr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let a of n){let o=mb(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:Cr.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...li(r)})}};function _le(t,e){let n=fb(t),r=fb(e);if(t===e)return{valid:!0,data:t};if(n===zn.object&&r===zn.object){let i=Wi.objectKeys(e),a=Wi.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let l=_le(t[s],e[s]);if(!l.valid)return{valid:!1};o[s]=l.data}return{valid:!0,data:o}}else if(n===zn.array&&r===zn.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let o=t[a],s=e[a],l=_le(o,s);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===zn.date&&r===zn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var FR=class extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(a,o)=>{if(mle(a)||mle(o))return Dr;let s=_le(a.value,o.value);return s.valid?((hle(a)||hle(o))&&n.dirty(),{status:n.value,value:s.data}):(Dn(r,{code:en.invalid_intersection_types}),Dr)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};FR.create=(t,e,n)=>new FR({left:t,right:e,typeName:Cr.ZodIntersection,...li(n)});var hb=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.array)return Dn(r,{code:en.invalid_type,expected:zn.array,received:r.parsedType}),Dr;if(r.data.length<this._def.items.length)return Dn(r,{code:en.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Dr;!this._def.rest&&r.data.length>this._def.items.length&&(Dn(r,{code:en.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let a=[...r.data].map((o,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new $g(r,o,r.path,s)):null}).filter(o=>!!o);return r.common.async?Promise.all(a).then(o=>_p.mergeArray(n,o)):_p.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};hb.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hb({items:t,typeName:Cr.ZodTuple,rest:null,...li(e)})};var yle=class t extends Ti{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.object)return Dn(r,{code:en.invalid_type,expected:zn.object,received:r.parsedType}),Dr;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in r.data)i.push({key:a._parse(new $g(r,s,r.path,s)),value:o._parse(new $g(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?_p.mergeObjectAsync(n,i):_p.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Ti?new t({keyType:e,valueType:n,typeName:Cr.ZodRecord,...li(r)}):new t({keyType:BR.create(),valueType:e,typeName:Cr.ZodRecord,...li(n)})}},c8=class extends Ti{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.map)return Dn(r,{code:en.invalid_type,expected:zn.map,received:r.parsedType}),Dr;let i=this._def.keyType,a=this._def.valueType,o=[...r.data.entries()].map(([s,l],u)=>({key:i._parse(new $g(r,s,r.path,[u,"key"])),value:a._parse(new $g(r,l,r.path,[u,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of o){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return Dr;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(u.value,p.value)}return{status:n.value,value:s}})}else{let s=new Map;for(let l of o){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return Dr;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(u.value,p.value)}return{status:n.value,value:s}}}};c8.create=(t,e,n)=>new c8({valueType:e,keyType:t,typeName:Cr.ZodMap,...li(n)});var u8=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.set)return Dn(r,{code:en.invalid_type,expected:zn.set,received:r.parsedType}),Dr;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(Dn(r,{code:en.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(Dn(r,{code:en.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let a=this._def.valueType;function o(l){let u=new Set;for(let p of l){if(p.status==="aborted")return Dr;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let s=[...r.data.values()].map((l,u)=>a._parse(new $g(r,l,r.path,u)));return r.common.async?Promise.all(s).then(l=>o(l)):o(s)}min(e,n){return new t({...this._def,minSize:{value:e,message:nr.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:nr.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};u8.create=(t,e)=>new u8({valueType:t,minSize:null,maxSize:null,typeName:Cr.ZodSet,...li(e)});var Ele=class t extends Ti{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.function)return Dn(n,{code:en.invalid_type,expected:zn.function,received:n.parsedType}),Dr;function r(s,l){return G$({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,e8(),w2].filter(u=>!!u),issueData:{code:en.invalid_arguments,argumentsError:l}})}function i(s,l){return G$({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,e8(),w2].filter(u=>!!u),issueData:{code:en.invalid_return_type,returnTypeError:l}})}let a={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof sw){let s=this;return mf(async function(...l){let u=new fh([]),p=await s._def.args.parseAsync(l,a).catch(_=>{throw u.addIssue(r(l,_)),u}),f=await Reflect.apply(o,this,p);return await s._def.returns._def.type.parseAsync(f,a).catch(_=>{throw u.addIssue(i(f,_)),u})})}else{let s=this;return mf(function(...l){let u=s._def.args.safeParse(l,a);if(!u.success)throw new fh([r(l,u.error)]);let p=Reflect.apply(o,this,u.data),f=s._def.returns.safeParse(p,a);if(!f.success)throw new fh([i(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:hb.create(e).rest(x2.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||hb.create([]).rest(x2.create()),returns:n||x2.create(),typeName:Cr.ZodFunction,...li(r)})}},UR=class extends Ti{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};UR.create=(t,e)=>new UR({getter:t,typeName:Cr.ZodLazy,...li(e)});var zR=class extends Ti{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return Dn(n,{received:n.data,code:en.invalid_literal,expected:this._def.value}),Dr}return{status:"valid",value:e.data}}get value(){return this._def.value}};zR.create=(t,e)=>new zR({value:t,typeName:Cr.ZodLiteral,...li(e)});function oFe(t,e){return new QR({values:t,typeName:Cr.ZodEnum,...li(e)})}var QR=class t extends Ti{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return Dn(n,{expected:Wi.joinValues(r),received:n.parsedType,code:en.invalid_type}),Dr}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return Dn(n,{received:n.data,code:en.invalid_enum_value,options:r}),Dr}return mf(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};QR.create=oFe;var GR=class extends Ti{_parse(e){let n=Wi.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==zn.string&&r.parsedType!==zn.number){let i=Wi.objectValues(n);return Dn(r,{expected:Wi.joinValues(i),received:r.parsedType,code:en.invalid_type}),Dr}if(this._cache||(this._cache=new Set(Wi.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Wi.objectValues(n);return Dn(r,{received:r.data,code:en.invalid_enum_value,options:i}),Dr}return mf(e.data)}get enum(){return this._def.values}};GR.create=(t,e)=>new GR({values:t,typeName:Cr.ZodNativeEnum,...li(e)});var sw=class extends Ti{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.promise&&n.common.async===!1)return Dn(n,{code:en.invalid_type,expected:zn.promise,received:n.parsedType}),Dr;let r=n.parsedType===zn.promise?n.data:Promise.resolve(n.data);return mf(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};sw.create=(t,e)=>new sw({type:t,typeName:Cr.ZodPromise,...li(e)});var xA=class extends Ti{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Cr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{Dn(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(r.data,a);if(r.common.async)return Promise.resolve(o).then(async s=>{if(n.value==="aborted")return Dr;let l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?Dr:l.status==="dirty"?OR(l.value):n.value==="dirty"?OR(l.value):l});{if(n.value==="aborted")return Dr;let s=this._def.schema._parseSync({data:o,path:r.path,parent:r});return s.status==="aborted"?Dr:s.status==="dirty"?OR(s.value):n.value==="dirty"?OR(s.value):s}}if(i.type==="refinement"){let o=s=>{let l=i.refinement(s,a);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Dr:(s.status==="dirty"&&n.dirty(),o(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?Dr:(s.status==="dirty"&&n.dirty(),o(s.value).then(()=>({status:n.value,value:s.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ow(o))return Dr;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ow(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:n.value,value:s})):Dr);Wi.assertNever(i)}};xA.create=(t,e,n)=>new xA({schema:t,typeName:Cr.ZodEffects,effect:e,...li(n)});xA.createWithPreprocess=(t,e,n)=>new xA({schema:e,effect:{type:"preprocess",transform:t},typeName:Cr.ZodEffects,...li(n)});var wA=class extends Ti{_parse(e){return this._getType(e)===zn.undefined?mf(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wA.create=(t,e)=>new wA({innerType:t,typeName:Cr.ZodOptional,...li(e)});var gb=class extends Ti{_parse(e){return this._getType(e)===zn.null?mf(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gb.create=(t,e)=>new gb({innerType:t,typeName:Cr.ZodNullable,...li(e)});var HR=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===zn.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};HR.create=(t,e)=>new HR({innerType:t,typeName:Cr.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...li(e)});var $R=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return t8(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new fh(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new fh(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};$R.create=(t,e)=>new $R({innerType:t,typeName:Cr.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...li(e)});var d8=class extends Ti{_parse(e){if(this._getType(e)!==zn.nan){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.nan,received:r.parsedType}),Dr}return{status:"valid",value:e.data}}};d8.create=t=>new d8({typeName:Cr.ZodNaN,...li(t)});var H$=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},$$=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Dr:a.status==="dirty"?(n.dirty(),OR(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Dr:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Cr.ZodPipeline})}},jR=class extends Ti{_parse(e){let n=this._def.innerType._parse(e),r=i=>(ow(i)&&(i.value=Object.freeze(i.value)),i);return t8(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};jR.create=(t,e)=>new jR({innerType:t,typeName:Cr.ZodReadonly,...li(e)});var J4n={object:mh.lazycreate},Cr;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Cr||(Cr={}));var X4n=BR.create,eRn=n8.create,tRn=d8.create,nRn=r8.create,rRn=i8.create,iRn=a8.create,aRn=o8.create,oRn=MR.create,sRn=PR.create,lRn=s8.create,cRn=x2.create,uRn=U0.create,dRn=l8.create,pRn=D2.create,k9t=mh.create,fRn=mh.strictCreate,mRn=LR.create,hRn=Ale.create,gRn=FR.create,ARn=hb.create,_Rn=yle.create,yRn=c8.create,ERn=u8.create,bRn=Ele.create,vRn=UR.create,SRn=zR.create,CRn=QR.create,TRn=GR.create,IRn=sw.create,wRn=xA.create,xRn=wA.create,DRn=gb.create,RRn=xA.createWithPreprocess,NRn=$$.create;sc();sc();sc();or();sc();sc();s4();ez();sc();sc();function qR(t){return!!t._zod}function R2(t,e){return qR(t)?dI(t,e):t.safeParse(e)}function j$(t){if(!t)return;let e;if(qR(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function cFe(t){if(qR(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}s5();var vle="2025-11-25",uFe="2025-03-26",p8=[vle,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],N2="io.modelcontextprotocol/related-task",V$="2.0",wd=SQ(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dFe=po([vt(),Ba().int()]),pFe=vt(),l6n=bd({ttl:po([Ba(),m4()]).optional(),pollInterval:Ba().optional()}),z9t=Ln({ttl:Ba().optional()}),Q9t=Ln({taskId:vt()}),Sle=bd({progressToken:dFe.optional(),[N2]:Q9t.optional()}),hh=Ln({_meta:Sle.optional()}),f8=hh.extend({task:z9t.optional()}),fFe=t=>f8.safeParse(t).success,xd=Ln({method:vt(),params:hh.loose().optional()}),jg=Ln({_meta:Sle.optional()}),qg=Ln({method:vt(),params:jg.loose().optional()}),Dd=bd({_meta:Sle.optional()}),Y$=po([vt(),Ba().int()]),mFe=Ln({jsonrpc:ir(V$),id:Y$,...xd.shape}).strict(),O2=t=>mFe.safeParse(t).success,hFe=Ln({jsonrpc:ir(V$),...qg.shape}).strict(),gFe=t=>hFe.safeParse(t).success,Cle=Ln({jsonrpc:ir(V$),id:Y$,result:Dd}).strict(),Ab=t=>Cle.safeParse(t).success;var Zi;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Zi||(Zi={}));var Tle=Ln({jsonrpc:ir(V$),id:Y$.optional(),error:Ln({code:Ba().int(),message:vt(),data:Do().optional()})}).strict();var YR=t=>Tle.safeParse(t).success;var m8=po([mFe,hFe,Cle,Tle]),c6n=po([Cle,Tle]),K$=Dd.strict(),G9t=jg.extend({requestId:Y$.optional(),reason:vt().optional()}),W$=qg.extend({method:ir("notifications/cancelled"),params:G9t}),H9t=Ln({src:vt(),mimeType:vt().optional(),sizes:vi(vt()).optional(),theme:vd(["light","dark"]).optional()}),h8=Ln({icons:vi(H9t).optional()}),VR=Ln({name:vt(),title:vt().optional()}),AFe=VR.extend({...VR.shape,...h8.shape,version:vt(),websiteUrl:vt().optional(),description:vt().optional()}),$9t=h4(Ln({applyDefaults:lc().optional()}),Go(vt(),Do())),j9t=a5(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,h4(Ln({form:$9t.optional(),url:wd.optional()}),Go(vt(),Do()).optional())),q9t=bd({list:wd.optional(),cancel:wd.optional(),requests:bd({sampling:bd({createMessage:wd.optional()}).optional(),elicitation:bd({create:wd.optional()}).optional()}).optional()}),V9t=bd({list:wd.optional(),cancel:wd.optional(),requests:bd({tools:bd({call:wd.optional()}).optional()}).optional()}),Y9t=Ln({experimental:Go(vt(),wd).optional(),sampling:Ln({context:wd.optional(),tools:wd.optional()}).optional(),elicitation:j9t.optional(),roots:Ln({listChanged:lc().optional()}).optional(),tasks:q9t.optional()}),K9t=hh.extend({protocolVersion:vt(),capabilities:Y9t,clientInfo:AFe}),Z$=xd.extend({method:ir("initialize"),params:K9t}),Ile=t=>Z$.safeParse(t).success,W9t=Ln({experimental:Go(vt(),wd).optional(),logging:wd.optional(),completions:wd.optional(),prompts:Ln({listChanged:lc().optional()}).optional(),resources:Ln({subscribe:lc().optional(),listChanged:lc().optional()}).optional(),tools:Ln({listChanged:lc().optional()}).optional(),tasks:V9t.optional()}),Z9t=Dd.extend({protocolVersion:vt(),capabilities:W9t,serverInfo:AFe,instructions:vt().optional()}),wle=qg.extend({method:ir("notifications/initialized"),params:jg.optional()});var J$=xd.extend({method:ir("ping"),params:hh.optional()}),J9t=Ln({progress:Ba(),total:as(Ba()),message:as(vt())}),X9t=Ln({...jg.shape,...J9t.shape,progressToken:dFe}),X$=qg.extend({method:ir("notifications/progress"),params:X9t}),e3t=hh.extend({cursor:pFe.optional()}),g8=xd.extend({params:e3t.optional()}),A8=Dd.extend({nextCursor:pFe.optional()}),t3t=vd(["working","input_required","completed","failed","cancelled"]),_8=Ln({taskId:vt(),status:t3t,ttl:po([Ba(),m4()]),createdAt:vt(),lastUpdatedAt:vt(),pollInterval:as(Ba()),statusMessage:as(vt())}),KR=Dd.extend({task:_8}),n3t=jg.merge(_8),y8=qg.extend({method:ir("notifications/tasks/status"),params:n3t}),ej=xd.extend({method:ir("tasks/get"),params:hh.extend({taskId:vt()})}),tj=Dd.merge(_8),nj=xd.extend({method:ir("tasks/result"),params:hh.extend({taskId:vt()})}),u6n=Dd.loose(),rj=g8.extend({method:ir("tasks/list")}),ij=A8.extend({tasks:vi(_8)}),aj=xd.extend({method:ir("tasks/cancel"),params:hh.extend({taskId:vt()})}),_Fe=Dd.merge(_8),yFe=Ln({uri:vt(),mimeType:as(vt()),_meta:Go(vt(),Do()).optional()}),EFe=yFe.extend({text:vt()}),xle=vt().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bFe=yFe.extend({blob:xle}),E8=vd(["user","assistant"]),WR=Ln({audience:vi(E8).optional(),priority:Ba().min(0).max(1).optional(),lastModified:e2.datetime({offset:!0}).optional()}),vFe=Ln({...VR.shape,...h8.shape,uri:vt(),description:as(vt()),mimeType:as(vt()),annotations:WR.optional(),_meta:as(bd({}))}),r3t=Ln({...VR.shape,...h8.shape,uriTemplate:vt(),description:as(vt()),mimeType:as(vt()),annotations:WR.optional(),_meta:as(bd({}))}),Dle=g8.extend({method:ir("resources/list")}),i3t=A8.extend({resources:vi(vFe)}),a3t=g8.extend({method:ir("resources/templates/list")}),o3t=A8.extend({resourceTemplates:vi(r3t)}),Rle=hh.extend({uri:vt()}),s3t=Rle,Nle=xd.extend({method:ir("resources/read"),params:s3t}),l3t=Dd.extend({contents:vi(po([EFe,bFe]))}),c3t=qg.extend({method:ir("notifications/resources/list_changed"),params:jg.optional()}),u3t=Rle,d3t=xd.extend({method:ir("resources/subscribe"),params:u3t}),p3t=Rle,f3t=xd.extend({method:ir("resources/unsubscribe"),params:p3t}),m3t=jg.extend({uri:vt()}),h3t=qg.extend({method:ir("notifications/resources/updated"),params:m3t}),g3t=Ln({name:vt(),description:as(vt()),required:as(lc())}),A3t=Ln({...VR.shape,...h8.shape,description:as(vt()),arguments:as(vi(g3t)),_meta:as(bd({}))}),Ole=g8.extend({method:ir("prompts/list")}),_3t=A8.extend({prompts:vi(A3t)}),y3t=hh.extend({name:vt(),arguments:Go(vt(),vt()).optional()}),kle=xd.extend({method:ir("prompts/get"),params:y3t}),Ble=Ln({type:ir("text"),text:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),Mle=Ln({type:ir("image"),data:xle,mimeType:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),Ple=Ln({type:ir("audio"),data:xle,mimeType:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),E3t=Ln({type:ir("tool_use"),name:vt(),id:vt(),input:Go(vt(),Do()),_meta:Go(vt(),Do()).optional()}),b3t=Ln({type:ir("resource"),resource:po([EFe,bFe]),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),v3t=vFe.extend({type:ir("resource_link")}),Lle=po([Ble,Mle,Ple,v3t,b3t]),S3t=Ln({role:E8,content:Lle}),C3t=Dd.extend({description:vt().optional(),messages:vi(S3t)}),T3t=qg.extend({method:ir("notifications/prompts/list_changed"),params:jg.optional()}),I3t=Ln({title:vt().optional(),readOnlyHint:lc().optional(),destructiveHint:lc().optional(),idempotentHint:lc().optional(),openWorldHint:lc().optional()}),w3t=Ln({taskSupport:vd(["required","optional","forbidden"]).optional()}),SFe=Ln({...VR.shape,...h8.shape,description:vt().optional(),inputSchema:Ln({type:ir("object"),properties:Go(vt(),wd).optional(),required:vi(vt()).optional()}).catchall(Do()),outputSchema:Ln({type:ir("object"),properties:Go(vt(),wd).optional(),required:vi(vt()).optional()}).catchall(Do()).optional(),annotations:I3t.optional(),execution:w3t.optional(),_meta:Go(vt(),Do()).optional()}),Fle=g8.extend({method:ir("tools/list")}),x3t=A8.extend({tools:vi(SFe)}),oj=Dd.extend({content:vi(Lle).default([]),structuredContent:Go(vt(),Do()).optional(),isError:lc().optional()}),d6n=oj.or(Dd.extend({toolResult:Do()})),D3t=f8.extend({name:vt(),arguments:Go(vt(),Do()).optional()}),b8=xd.extend({method:ir("tools/call"),params:D3t}),R3t=qg.extend({method:ir("notifications/tools/list_changed"),params:jg.optional()}),p6n=Ln({autoRefresh:lc().default(!0),debounceMs:Ba().int().nonnegative().default(300)}),v8=vd(["debug","info","notice","warning","error","critical","alert","emergency"]),N3t=hh.extend({level:v8}),Ule=xd.extend({method:ir("logging/setLevel"),params:N3t}),O3t=jg.extend({level:v8,logger:vt().optional(),data:Do()}),k3t=qg.extend({method:ir("notifications/message"),params:O3t}),B3t=Ln({name:vt().optional()}),M3t=Ln({hints:vi(B3t).optional(),costPriority:Ba().min(0).max(1).optional(),speedPriority:Ba().min(0).max(1).optional(),intelligencePriority:Ba().min(0).max(1).optional()}),P3t=Ln({mode:vd(["auto","required","none"]).optional()}),L3t=Ln({type:ir("tool_result"),toolUseId:vt().describe("The unique identifier for the corresponding tool call."),content:vi(Lle).default([]),structuredContent:Ln({}).loose().optional(),isError:lc().optional(),_meta:Go(vt(),Do()).optional()}),F3t=n5("type",[Ble,Mle,Ple]),q$=n5("type",[Ble,Mle,Ple,E3t,L3t]),U3t=Ln({role:E8,content:po([q$,vi(q$)]),_meta:Go(vt(),Do()).optional()}),z3t=f8.extend({messages:vi(U3t),modelPreferences:M3t.optional(),systemPrompt:vt().optional(),includeContext:vd(["none","thisServer","allServers"]).optional(),temperature:Ba().optional(),maxTokens:Ba().int(),stopSequences:vi(vt()).optional(),metadata:wd.optional(),tools:vi(SFe).optional(),toolChoice:P3t.optional()}),Q3t=xd.extend({method:ir("sampling/createMessage"),params:z3t}),zle=Dd.extend({model:vt(),stopReason:as(vd(["endTurn","stopSequence","maxTokens"]).or(vt())),role:E8,content:F3t}),Qle=Dd.extend({model:vt(),stopReason:as(vd(["endTurn","stopSequence","maxTokens","toolUse"]).or(vt())),role:E8,content:po([q$,vi(q$)])}),G3t=Ln({type:ir("boolean"),title:vt().optional(),description:vt().optional(),default:lc().optional()}),H3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),minLength:Ba().optional(),maxLength:Ba().optional(),format:vd(["email","uri","date","date-time"]).optional(),default:vt().optional()}),$3t=Ln({type:vd(["number","integer"]),title:vt().optional(),description:vt().optional(),minimum:Ba().optional(),maximum:Ba().optional(),default:Ba().optional()}),j3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),enum:vi(vt()),default:vt().optional()}),q3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),oneOf:vi(Ln({const:vt(),title:vt()})),default:vt().optional()}),V3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),enum:vi(vt()),enumNames:vi(vt()).optional(),default:vt().optional()}),Y3t=po([j3t,q3t]),K3t=Ln({type:ir("array"),title:vt().optional(),description:vt().optional(),minItems:Ba().optional(),maxItems:Ba().optional(),items:Ln({type:ir("string"),enum:vi(vt())}),default:vi(vt()).optional()}),W3t=Ln({type:ir("array"),title:vt().optional(),description:vt().optional(),minItems:Ba().optional(),maxItems:Ba().optional(),items:Ln({anyOf:vi(Ln({const:vt(),title:vt()}))}),default:vi(vt()).optional()}),Z3t=po([K3t,W3t]),J3t=po([V3t,Y3t,Z3t]),X3t=po([J3t,G3t,H3t,$3t]),eOt=f8.extend({mode:ir("form").optional(),message:vt(),requestedSchema:Ln({type:ir("object"),properties:Go(vt(),X3t),required:vi(vt()).optional()})}),tOt=f8.extend({mode:ir("url"),message:vt(),elicitationId:vt(),url:vt().url()}),nOt=po([eOt,tOt]),rOt=xd.extend({method:ir("elicitation/create"),params:nOt}),iOt=jg.extend({elicitationId:vt()}),aOt=qg.extend({method:ir("notifications/elicitation/complete"),params:iOt}),sj=Dd.extend({action:vd(["accept","decline","cancel"]),content:a5(t=>t===null?void 0:t,Go(vt(),po([vt(),Ba(),lc(),vi(vt())])).optional())}),oOt=Ln({type:ir("ref/resource"),uri:vt()});var sOt=Ln({type:ir("ref/prompt"),name:vt()}),lOt=hh.extend({ref:po([sOt,oOt]),argument:Ln({name:vt(),value:vt()}),context:Ln({arguments:Go(vt(),vt()).optional()}).optional()}),cOt=xd.extend({method:ir("completion/complete"),params:lOt});var uOt=Dd.extend({completion:bd({values:vi(vt()).max(100),total:as(Ba().int()),hasMore:as(lc())})}),dOt=Ln({uri:vt().startsWith("file://"),name:vt().optional(),_meta:Go(vt(),Do()).optional()}),pOt=xd.extend({method:ir("roots/list"),params:hh.optional()}),Gle=Dd.extend({roots:vi(dOt)}),fOt=qg.extend({method:ir("notifications/roots/list_changed"),params:jg.optional()}),f6n=po([J$,Z$,cOt,Ule,kle,Ole,Dle,a3t,Nle,d3t,f3t,b8,Fle,ej,nj,rj,aj]),m6n=po([W$,X$,wle,fOt,y8]),h6n=po([K$,zle,Qle,sj,Gle,tj,ij,KR]),g6n=po([J$,Q3t,rOt,pOt,ej,nj,rj,aj]),A6n=po([W$,X$,k3t,h3t,c3t,R3t,T3t,y8,aOt]),_6n=po([K$,Z9t,uOt,C3t,_3t,i3t,o3t,l3t,oj,x3t,tj,ij,KR]),gi=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===Zi.UrlElicitationRequired&&r){let i=r;if(i.elicitations)return new ble(i.elicitations,n)}return new t(e,n,r)}},ble=class extends gi{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Zi.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function k2(t){return t==="completed"||t==="failed"||t==="cancelled"}var J6n=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Hle(t){let n=j$(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=cFe(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function $le(t,e){let n=R2(t,e);if(!n.success)throw n.error;return n.data}var yOt=6e4,lj=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(W$,n=>{this._oncancel(n)}),this.setNotificationHandler(X$,n=>{this._onprogress(n)}),this.setRequestHandler(J$,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ej,async(n,r)=>{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new gi(Zi.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(nj,async(n,r)=>{let i=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,r.sessionId);){if(s.type==="response"||s.type==="error"){let l=s.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),s.type==="response")p(l);else{let f=l,h=new gi(f.error.code,f.error.message,f.error.data);p(h)}else{let f=s.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let o=await this._taskStore.getTask(a,r.sessionId);if(!o)throw new gi(Zi.InvalidParams,`Task not found: ${a}`);if(!k2(o.status))return await this._waitForTaskUpdate(a,r.signal),await i();if(k2(o.status)){let s=await this._taskStore.getTaskResult(a,r.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[N2]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(rj,async(n,r)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new gi(Zi.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(aj,async(n,r)=>{try{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new gi(Zi.InvalidParams,`Task not found: ${n.params.taskId}`);if(k2(i.status))throw new gi(Zi.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!a)throw new gi(Zi.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof gi?i:new gi(Zi.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),gi.fromError(Zi.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=a=>{r?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Ab(a)||YR(a)?this._onresponse(a):O2(a)?this._onrequest(a,o):gFe(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=gi.fromError(Zi.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[N2]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:Zi.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},i?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):i?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=fFe(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(o.signal.aborted)return;let f={relatedRequestId:e.id};a&&(f.relatedTask={taskId:a}),await this.notification(p,f)},sendRequest:async(p,f,h)=>{if(o.signal.aborted)throw new gi(Zi.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};a&&!_.relatedTask&&(_.relatedTask={taskId:a});let y=_.relatedTask?.taskId??a;return y&&l&&await l.updateTaskStatus(y,"input_required"),await this.request(p,f,_)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async p=>{if(o.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:f,timestamp:Date.now()},i?.sessionId):await i?.send(f)},async p=>{if(o.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:Zi.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:f,timestamp:Date.now()},i?.sessionId):await i?.send(f)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,i=Number(n),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(l);return}a(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Ab(e))r(e);else{let o=new gi(e.error.code,e.error.message,e.error.data);r(o)}return}let i=this._responseHandlers.get(n);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(Ab(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,n))}}if(a||this._progressHandlers.delete(n),Ab(e))i(e);else{let o=gi.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:i}=r??{};if(!i){try{yield{type:"result",result:await this.request(e,n,r)}}catch(o){yield{type:"error",error:o instanceof gi?o:new gi(Zi.InternalError,String(o))}}return}let a;try{let o=await this.request(e,KR,r);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new gi(Zi.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},r);if(yield{type:"taskStatus",task:s},k2(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)}:s.status==="failed"?yield{type:"error",error:new gi(Zi.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new gi(Zi.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)};return}let l=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),r?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof gi?o:new gi(Zi.InternalError,String(o))}}}request(e,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:l}=r??{};return new Promise((u,p)=>{let f=N=>{p(N)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(N){f(N);return}r?.signal?.throwIfAborted();let h=this._requestMessageId++,_={...e,jsonrpc:"2.0",id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),_.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),s&&(_.params={..._.params,task:s}),l&&(_.params={..._.params,_meta:{..._.params?._meta||{},[N2]:l}});let y=N=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(N)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let O=N instanceof gi?N:new gi(Zi.RequestTimeout,String(N));p(O)};this._responseHandlers.set(h,N=>{if(!r?.signal?.aborted){if(N instanceof Error)return p(N);try{let O=R2(n,N.result);O.success?u(O.data):p(O.error)}catch(O){p(O)}}}),r?.signal?.addEventListener("abort",()=>{y(r?.signal?.reason)});let E=r?.timeout??yOt,S=()=>y(gi.fromError(Zi.RequestTimeout,"Request timed out",{timeout:E}));this._setupTimeout(h,E,r?.maxTotalTimeout,S,r?.resetTimeoutOnProgress??!1);let T=l?.taskId;if(T){let N=O=>{let M=this._responseHandlers.get(h);M?M(O):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,N),this._enqueueTaskMessage(T,{type:"request",message:_,timestamp:Date.now()}).catch(O=>{this._cleanupTimeout(h),p(O)})}else this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(N=>{this._cleanupTimeout(h),p(N)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},tj,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},ij,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},_Fe,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[N2]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[N2]:n.relatedTask}}}),this._transport?.send(s,n).catch(l=>this._onerror(l))});return}let o={...e,jsonrpc:"2.0"};n?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[N2]:n.relatedTask}}}),await this._transport.send(o,n)}setRequestHandler(e,n){let r=Hle(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(i,a)=>{let o=$le(e,i);return Promise.resolve(n(o,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=Hle(e);this._notificationHandlers.set(r,i=>{let a=$le(e,i);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,i)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let i of r)if(i.type==="request"&&O2(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new gi(Zi.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(r=i.pollInterval)}catch{}return new Promise((i,a)=>{if(n.aborted){a(new gi(Zi.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,r);n.addEventListener("abort",()=>{clearTimeout(o),a(new gi(Zi.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await r.createTask(i,e.id,{method:e.method,params:e.params},n)},getTask:async i=>{let a=await r.getTask(i,n);if(!a)throw new gi(Zi.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await r.storeTaskResult(i,a,o,n);let s=await r.getTask(i,n);if(s){let l=y8.parse({method:"notifications/tasks/status",params:s});await this.notification(l),k2(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>r.getTaskResult(i,n),updateTaskStatus:async(i,a,o)=>{let s=await r.getTask(i,n);if(!s)throw new gi(Zi.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(k2(s.status))throw new gi(Zi.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(i,a,o,n);let l=await r.getTask(i,n);if(l){let u=y8.parse({method:"notifications/tasks/status",params:l});await this.notification(u),k2(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>r.listTasks(i,n)}}};function CFe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function TFe(t,e){let n={...t};for(let r in e){let i=r,a=e[i];if(a===void 0)continue;let o=n[i];CFe(o)&&CFe(a)?n[i]={...o,...a}:n[i]=a}return n}var dQe=Lt(Due(),1),pQe=Lt(uQe(),1);function u7t(){let t=new dQe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,pQe.default)(t),t}var $j=class{constructor(e){this._ajv=e??u7t()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var jj=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function fQe(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function mQe(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var qj=class extends lj{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v8.options.map((r,i)=>[r,i])),this.isMessageIgnored=(r,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new $j,this.setRequestHandler(Z$,r=>this._oninitialize(r)),this.setNotificationHandler(wle,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ule,async(r,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=r.params,s=v8.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jj(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=TFe(this._capabilities,e)}setRequestHandler(e,n){let i=j$(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(qR(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(l,u)=>{let p=R2(b8,l);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new gi(Zi.InvalidParams,`Invalid tools/call request: ${y}`)}let{params:f}=p.data,h=await Promise.resolve(n(l,u));if(f.task){let y=R2(KR,h);if(!y.success){let E=y.error instanceof Error?y.error.message:String(y.error);throw new gi(Zi.InvalidParams,`Invalid task creation result: ${E}`)}return y.data}let _=R2(oj,h);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new gi(Zi.InvalidParams,`Invalid tools/call result: ${y}`)}return _.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){mQe(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&fQe(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:p8.includes(n)?n:vle,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},K$)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],i=Array.isArray(r.content)?r.content:[r.content],a=i.some(u=>u.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],l=s.some(u=>u.type==="tool_use");if(a){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(s.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==p.size||![...u].every(f=>p.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Qle,n):this.request({method:"sampling/createMessage",params:e},zle,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},sj,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:i},sj,n);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new gi(Zi.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof gi?o:new gi(Zi.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Gle,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import gQe from"node:process";var Vj=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
928
+ %s files, %s total`,i.length,F0(i.reduce((o,s)=>o+DR(s).size,0)))}})}}),t.command("upload").description("Upload a single session file").option("--hook","hook mode: read session path from stdin JSON").option("--machine-id <id>","machine identifier for R2 key namespacing").option("--claude-dir <path>","Claude config directory").argument("[file]","path to .jsonl file (when not using --hook)").action(async(e,n)=>{let r=ule(n.claudeDir),i=LLe(n.machineId),a=RR(r,"projects"),o;if(n.hook){let _;try{_=zLe(0,"utf-8")}catch{ot("failed to read from stdin")}let y;try{y=JSON.parse(_)}catch{ot("invalid JSON on stdin")}let E=y.transcript_path;E||ot("no transcript_path in hook input"),o=E.replace(/^~/,GLe())}else e?o=e:ot("provide a file path or use --hook to read from stdin");try{DR(o)}catch{ot("file not found: %s",o)}let s=FLe(o,a,i),{client:l,profile:u}=await ii("library"),p=mp(u),f=cc(u),h=await ULe(l,o,s,i,p,f,!1);h.status==="failed"&&ot("upload failed: %s",h.error),Nt({json:()=>h,human:()=>{h.status==="skipped"&&mn("Skipped (unchanged): %s",s)}})}),t.command("download").description("Download session files from PocketBase").argument("[dir]","output directory",".").option("--key <key>","download a specific file by key").option("--machine-id <id>","download all files from a specific machine").action(async(e,n)=>{let{client:r}=await ii("library"),i=[];n.key&&i.push(`key='${ple(n.key)}'`),n.machineId&&i.push(`machine_id='${ple(n.machineId)}'`);let a=i.length>0?i.join(" && "):"",o=await dn("Fetching session files...",()=>r.collection("session_files").getFullList({sort:"key",filter:a}));if(o.length===0){mn("No session files found");return}mn("Downloading %s files to %s",o.length,e);let s=await r.files.getToken(),l=0,u=0;for(let p of o){let f=p.key,h=p.file,_=RR(e,f),y=r.files.getURL(p,h,{token:s});try{let E=await fetch(y);if(!E.ok){mn("Failed: %s \u2014 HTTP %s",f,E.status),u++;continue}let S=Buffer.from(await E.arrayBuffer());TNt(RNt(_),{recursive:!0}),xNt(_,S),On("Downloaded: %s (%s)",f,F0(S.length)),l++}catch(E){let S=E instanceof Error?E.message:String(E);mn("Failed: %s \u2014 %s",f,S),u++}}mn(""),mn("Summary: %s total, %s downloaded, %s failed",o.length,l,u),Nt({json:()=>o.map(p=>({id:p.id,key:p.key,machine_id:p.machine_id,size:p.size})),human:()=>{}})}),t}function HLe(t){t.addCommand(kNt())}import{readFileSync as BNt}from"node:fs";import{dirname as MNt,join as PNt}from"node:path";import{fileURLToPath as LNt}from"node:url";function I2(){return"0.1.44"}import{basename as FNt}from"node:path";function $Le(){return!0}var UNt="@zenku";function jLe(t){return t.replace(/\\/g,"/")}function zNt(t){let e=t.toLowerCase();return e==="node"||e==="node.exe"||e==="bun"}function L$(){let{platform:t,arch:e}=process,n=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64"]),r=`${t}-${e}`;if(!n.has(r))throw new Error(`Unsupported platform: ${r}`);return`cli-${r}`}function qLe(t){return`${UNt}/${t}`}function F$(){if($Le())return"bundle";let t=jLe(process.execPath),e=jLe(process.argv[1]??""),n=FNt(process.execPath).toLowerCase();return n==="zenku-test"||n==="zenku-test.exe"||n.includes("zenku-test")||e.length>0&&(e.endsWith(".js")||e.endsWith(".cjs")||e.endsWith(".mjs"))||zNt(n)?"development":t.includes("/node_modules/")&&t.includes("/@zenku/")&&t.includes("/cli-")?"npm-managed":t.includes("/apps/zenku-cli/")||t.includes("/apps\\zenku-cli\\")?"development":"standalone"}function NR(t){return t==="bundle"?{command:"npm update -g @zenku/cli-node",message:"Self-upgrade is not available in bundle mode. Update via npm: npm update -g @zenku/cli-node"}:t==="npm-managed"?{command:"npm update -g @zenku/cli",message:"This install is npm-managed. Update via npm: npm update -g @zenku/cli"}:t==="development"?{command:"pnpm --filter @hikari/zenku-cli compile",message:"Development/test builds are not self-updated. Rebuild locally: pnpm --filter @hikari/zenku-cli compile"}:{command:"zenku upgrade",message:"Run `zenku upgrade` to install the latest binary."}}import{execFileSync as VLe}from"node:child_process";import{createHash as QNt}from"node:crypto";import{accessSync as GNt,chmodSync as HNt,constants as $Nt,copyFileSync as jNt,existsSync as qNt,mkdtempSync as VNt,readFileSync as YNt,renameSync as KNt,rmSync as WNt,unlinkSync as ZNt,writeFileSync as JNt}from"node:fs";import{tmpdir as XNt}from"node:os";import{dirname as fle,join as U$}from"node:path";function e9t(t){let e=t.trim().split(/\s+/)[0]??"",n=e.indexOf("-");if(n<=0||n>=e.length-1)throw new Error("invalid integrity format");let r=e.slice(0,n),i=e.slice(n+1);return{algo:r,hash:i}}function t9t(t,e){let{algo:n,hash:r}=e9t(e),i=YNt(t);if(QNt(n).update(i).digest("base64")!==r)throw new Error("checksum mismatch")}function YLe(t){try{return GNt(t,$Nt.W_OK),!0}catch{return!1}}function n9t(t,e){let n=fle(e),r=U$(n,`.zenku-upgrade-${process.pid}`);jNt(t,r),HNt(r,493);try{KNt(r,e)}catch{try{ZNt(r)}catch{}throw new Error(`failed to replace binary at ${e}`)}}async function r9t(t,e){let n=await fetch(t);if(!n.ok)throw new Error(`download failed: HTTP ${n.status}`);let r=Buffer.from(await n.arrayBuffer());JNt(e,r)}function KLe(t){return YLe(fle(t))}async function z$(t,e,n){let r=`${t.version}.tgz`,i=VNt(U$(XNt(),"zenku-upgrade-")),a=U$(i,r);try{await r9t(t.tarball,a),t9t(a,t.integrity),VLe("tar",["xzf",a,"-C",i],{stdio:"pipe"});let o=U$(i,"package","zenku");if(!qNt(o))throw new Error("downloaded package is missing binary");let s=fle(e);if(YLe(s)){n9t(o,e);return}if(!n.allowSudo)throw new Error(`no write permission for ${s}`);VLe("sudo",["install","-m","755",o,e],{stdio:"inherit"})}finally{WNt(i,{recursive:!0,force:!0})}}var WLe="https://registry.npmjs.org",i9t=15e3;async function ZLe(t){let e=new AbortController,n=setTimeout(()=>e.abort(),i9t);try{let r=await fetch(t,{signal:e.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);return await r.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("request timed out"):r}finally{clearTimeout(n)}}function JLe(t,e){if(!t.version)throw new Error(`registry response missing version for tag "${e}"`);if(!t.dist?.tarball)throw new Error(`registry response missing dist.tarball for v${t.version}`);if(!t.dist?.integrity)throw new Error(`registry response missing dist.integrity for v${t.version}`);return{version:t.version,tarball:t.dist.tarball,integrity:t.dist.integrity,tag:e}}async function Q$(t,e){let n=qLe(t),r=encodeURIComponent(n),i=e==="stable"?"stable":"latest";try{let a=await ZLe(`${WLe}/${r}/${i}`);return JLe(a,i)}catch(a){if(e==="stable"){let o=await ZLe(`${WLe}/${r}/latest`);return JLe(o,"latest")}throw a}}function a9t(){try{let t=cf(),{effective:e}=m2(t,void 0);return e.channel}catch{return"latest"}}function o9t(t){return t==="bundle"?"cli-node":L$()}function XLe(t){t.addCommand(new Jn("upgrade").description("Upgrade zenku to the latest version").action(async()=>{let e=F$(),n=NR(e),r=I2(),i=a9t();if(e==="development"){Nt({json:()=>({mode:e,message:n.message,previous:r,latest:r,upgraded:!1,command:n.command}),human:()=>{mn("%s",n.message)}});return}let a=o9t(e),o=await dn("Checking for updates...",()=>Q$(a,i));if(r===o.version){let s=`Already up to date (v${r}).`;Nt({json:()=>({previous:r,latest:o.version,upgraded:!1,mode:e,message:s}),human:()=>mn("%s",s)});return}if(e!=="standalone"){Nt({json:()=>({previous:r,latest:o.version,upgraded:!1,mode:e,command:n.command,message:n.message}),human:()=>{mn("v%s -> v%s",r,o.version),mn("%s",n.message),mn("Run: %s",n.command)}});return}mn("v%s -> v%s",r,o.version),await dn(`Downloading v${o.version}...`,async()=>{await z$(o,process.execPath,{allowSudo:!0})}),Nt({json:()=>({previous:r,latest:o.version,upgraded:!0,mode:e}),human:()=>mn("Upgraded zenku to v%s.",o.version)})}))}function s9t(t){return{name:t.name(),description:t.description??"",required:t.required,variadic:t.variadic,defaultValue:t.defaultValue}}function l9t(t){return{name:t.name(),flags:t.flags,description:t.description??"",short:t.short,long:t.long,required:t.required,optional:t.optional,variadic:t.variadic,mandatory:t.mandatory,defaultValue:t.defaultValue}}function eFe(t,e){let n=[...e,t.name()].filter(Boolean),r=t.commands.map(i=>eFe(i,n)).sort((i,a)=>i.commandPath.localeCompare(a.commandPath));return{name:t.name(),commandPath:n.join(" "),summary:t.summary(),description:t.description(),aliases:t.aliases(),usage:t.usage(),arguments:t.registeredArguments.map(s9t),options:t.options.filter(i=>i.long!=="--help").map(l9t),subcommands:r}}function tFe(t){let e=new Jn("meta").description("Machine-readable metadata for CLI integrations");e.command("commands").description("Print CLI command tree metadata").action(()=>{Nt({json:()=>eFe(t,[]),human:()=>{process.stdout.write("Use `zenku --json meta commands` for command metadata.\n")}})}),t.addCommand(e)}import{randomUUID as S$e}from"node:crypto";import uzt from"node:http";var Wi;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=r,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(Wi||(Wi={}));var nFe;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(nFe||(nFe={}));var zn=Wi.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fb=t=>{switch(typeof t){case"undefined":return zn.undefined;case"string":return zn.string;case"number":return Number.isNaN(t)?zn.nan:zn.number;case"boolean":return zn.boolean;case"function":return zn.function;case"bigint":return zn.bigint;case"symbol":return zn.symbol;case"object":return Array.isArray(t)?zn.array:t===null?zn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?zn.promise:typeof Map<"u"&&t instanceof Map?zn.map:typeof Set<"u"&&t instanceof Set?zn.set:typeof Date<"u"&&t instanceof Date?zn.date:zn.object;default:return zn.unknown}};var en=Wi.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var fh=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(a){return a.message},r={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let s=r,l=0;for(;l<o.path.length;){let u=o.path[l];l===o.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(n(o))):s[u]=s[u]||{_errors:[]},s=s[u],l++}}};return i(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Wi.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];n[a]=n[a]||[],n[a].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fh.create=t=>new fh(t);var c9t=(t,e)=>{let n;switch(t.code){case en.invalid_type:t.received===zn.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case en.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Wi.jsonStringifyReplacer)}`;break;case en.unrecognized_keys:n=`Unrecognized key(s) in object: ${Wi.joinValues(t.keys,", ")}`;break;case en.invalid_union:n="Invalid input";break;case en.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Wi.joinValues(t.options)}`;break;case en.invalid_enum_value:n=`Invalid enum value. Expected ${Wi.joinValues(t.options)}, received '${t.received}'`;break;case en.invalid_arguments:n="Invalid function arguments";break;case en.invalid_return_type:n="Invalid function return type";break;case en.invalid_date:n="Invalid date";break;case en.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Wi.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case en.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case en.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case en.custom:n="Invalid input";break;case en.invalid_intersection_types:n="Intersection results could not be merged";break;case en.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case en.not_finite:n="Number must be finite";break;default:n=e.defaultError,Wi.assertNever(t)}return{message:n}},w2=c9t;var u9t=w2;function e8(){return u9t}var G$=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)s=u(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}};function Dn(t,e){let n=e8(),r=G$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===w2?void 0:w2].filter(i=>!!i)});t.common.issues.push(r)}var _p=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let i of n){if(i.status==="aborted")return Dr;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let a=await i.key,o=await i.value;r.push({key:a,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return Dr;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[a.value]=o.value)}return{status:e.value,value:r}}},Dr=Object.freeze({status:"aborted"}),OR=t=>({status:"dirty",value:t}),mf=t=>({status:"valid",value:t}),mle=t=>t.status==="aborted",hle=t=>t.status==="dirty",ow=t=>t.status==="valid",t8=t=>typeof Promise<"u"&&t instanceof Promise;var nr;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(nr||(nr={}));var $g=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},rFe=(t,e)=>{if(ow(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fh(t.common.issues);return this._error=n,this._error}}};function li(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,s)=>{let{message:l}=t;return o.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:l??n??s.defaultError}},description:i}}var Ti=class{get description(){return this._def.description}_getType(e){return fb(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:fb(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _p,ctx:{common:e.parent.common,data:e.data,parsedType:fb(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(t8(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)},i=this._parseSync({data:e,path:r.path,parent:r});return rFe(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ow(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>ow(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:fb(e)},i=this._parse({data:e,path:r.path,parent:r}),a=await(t8(i)?i:Promise.resolve(i));return rFe(r,a)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:en.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new xA({schema:this,typeName:Cr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return wA.create(this,this._def)}nullable(){return gb.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return D2.create(this)}promise(){return sw.create(this,this._def)}or(e){return LR.create([this,e],this._def)}and(e){return FR.create(this,e,this._def)}transform(e){return new xA({...li(this._def),schema:this,typeName:Cr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new HR({...li(this._def),innerType:this,defaultValue:n,typeName:Cr.ZodDefault})}brand(){return new H$({typeName:Cr.ZodBranded,type:this,...li(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new $R({...li(this._def),innerType:this,catchValue:n,typeName:Cr.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return $$.create(this,e)}readonly(){return jR.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},d9t=/^c[^\s-]{8,}$/i,p9t=/^[0-9a-z]+$/,f9t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,m9t=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,h9t=/^[a-z0-9_-]{21}$/i,g9t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A9t=/^[-+]?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)?)??$/,_9t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,y9t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gle,E9t=/^(?:(?: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])$/,b9t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,v9t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,S9t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,C9t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T9t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,iFe="((\\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])))",I9t=new RegExp(`^${iFe}$`);function aFe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function w9t(t){return new RegExp(`^${aFe(t)}$`)}function x9t(t){let e=`${iFe}T${aFe(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function D9t(t,e){return!!((e==="v4"||!e)&&E9t.test(t)||(e==="v6"||!e)&&v9t.test(t))}function R9t(t,e){if(!g9t.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function N9t(t,e){return!!((e==="v4"||!e)&&b9t.test(t)||(e==="v6"||!e)&&S9t.test(t))}var BR=class t extends Ti{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==zn.string){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.string,received:a.parsedType}),Dr}let r=new _p,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.length<a.value;(o||s)&&(i=this._getOrReturnCtx(e,i),o?Dn(i,{code:en.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&Dn(i,{code:en.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")_9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"email",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")gle||(gle=new RegExp(y9t,"u")),gle.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"emoji",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")m9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"uuid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")h9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"nanoid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")d9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cuid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")p9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cuid2",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")f9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"ulid",code:en.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Dn(i,{validation:"url",code:en.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"regex",code:en.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?x9t(a).test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?I9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?w9t(a).test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?A9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"duration",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?D9t(e.data,a.version)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"ip",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?R9t(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"jwt",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?N9t(e.data,a.version)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"cidr",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?C9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"base64",code:en.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?T9t.test(e.data)||(i=this._getOrReturnCtx(e,i),Dn(i,{validation:"base64url",code:en.invalid_string,message:a.message}),r.dirty()):Wi.assertNever(a);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:en.invalid_string,...nr.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...nr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...nr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...nr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...nr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...nr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...nr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...nr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...nr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...nr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...nr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...nr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...nr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...nr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...nr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...nr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...nr.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...nr.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...nr.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...nr.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...nr.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...nr.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...nr.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...nr.errToObj(n)})}nonempty(e){return this.min(1,nr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};BR.create=t=>new BR({checks:[],typeName:Cr.ZodString,coerce:t?.coerce??!1,...li(t)});function O9t(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var n8=class t extends Ti{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==zn.number){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.number,received:a.parsedType}),Dr}let r,i=new _p;for(let a of this._def.checks)a.kind==="int"?Wi.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?O9t(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_finite,message:a.message}),i.dirty()):Wi.assertNever(a);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,nr.toString(n))}gt(e,n){return this.setLimit("min",e,!1,nr.toString(n))}lte(e,n){return this.setLimit("max",e,!0,nr.toString(n))}lt(e,n){return this.setLimit("max",e,!1,nr.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:nr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:nr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:nr.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:nr.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:nr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:nr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:nr.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Wi.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};n8.create=t=>new n8({checks:[],typeName:Cr.ZodNumber,coerce:t?.coerce||!1,...li(t)});var r8=class t extends Ti{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==zn.bigint)return this._getInvalidInput(e);let r,i=new _p;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Dn(r,{code:en.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):Wi.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return Dn(n,{code:en.invalid_type,expected:zn.bigint,received:n.parsedType}),Dr}gte(e,n){return this.setLimit("min",e,!0,nr.toString(n))}gt(e,n){return this.setLimit("min",e,!1,nr.toString(n))}lte(e,n){return this.setLimit("max",e,!0,nr.toString(n))}lt(e,n){return this.setLimit("max",e,!1,nr.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:nr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:nr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:nr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:nr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:nr.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:nr.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};r8.create=t=>new r8({checks:[],typeName:Cr.ZodBigInt,coerce:t?.coerce??!1,...li(t)});var i8=class extends Ti{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==zn.boolean){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.boolean,received:r.parsedType}),Dr}return mf(e.data)}};i8.create=t=>new i8({typeName:Cr.ZodBoolean,coerce:t?.coerce||!1,...li(t)});var a8=class t extends Ti{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==zn.date){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_type,expected:zn.date,received:a.parsedType}),Dr}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return Dn(a,{code:en.invalid_date}),Dr}let r=new _p,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),Dn(i,{code:en.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):Wi.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:nr.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:nr.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};a8.create=t=>new a8({checks:[],coerce:t?.coerce||!1,typeName:Cr.ZodDate,...li(t)});var o8=class extends Ti{_parse(e){if(this._getType(e)!==zn.symbol){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.symbol,received:r.parsedType}),Dr}return mf(e.data)}};o8.create=t=>new o8({typeName:Cr.ZodSymbol,...li(t)});var MR=class extends Ti{_parse(e){if(this._getType(e)!==zn.undefined){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.undefined,received:r.parsedType}),Dr}return mf(e.data)}};MR.create=t=>new MR({typeName:Cr.ZodUndefined,...li(t)});var PR=class extends Ti{_parse(e){if(this._getType(e)!==zn.null){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.null,received:r.parsedType}),Dr}return mf(e.data)}};PR.create=t=>new PR({typeName:Cr.ZodNull,...li(t)});var s8=class extends Ti{constructor(){super(...arguments),this._any=!0}_parse(e){return mf(e.data)}};s8.create=t=>new s8({typeName:Cr.ZodAny,...li(t)});var x2=class extends Ti{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mf(e.data)}};x2.create=t=>new x2({typeName:Cr.ZodUnknown,...li(t)});var U0=class extends Ti{_parse(e){let n=this._getOrReturnCtx(e);return Dn(n,{code:en.invalid_type,expected:zn.never,received:n.parsedType}),Dr}};U0.create=t=>new U0({typeName:Cr.ZodNever,...li(t)});var l8=class extends Ti{_parse(e){if(this._getType(e)!==zn.undefined){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.void,received:r.parsedType}),Dr}return mf(e.data)}};l8.create=t=>new l8({typeName:Cr.ZodVoid,...li(t)});var D2=class t extends Ti{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==zn.array)return Dn(n,{code:en.invalid_type,expected:zn.array,received:n.parsedType}),Dr;if(i.exactLength!==null){let o=n.data.length>i.exactLength.value,s=n.data.length<i.exactLength.value;(o||s)&&(Dn(n,{code:o?en.too_big:en.too_small,minimum:s?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(Dn(n,{code:en.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(Dn(n,{code:en.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,s)=>i.type._parseAsync(new $g(n,o,n.path,s)))).then(o=>_p.mergeArray(r,o));let a=[...n.data].map((o,s)=>i.type._parseSync(new $g(n,o,n.path,s)));return _p.mergeArray(r,a)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:nr.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:nr.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:nr.toString(n)}})}nonempty(e){return this.min(1,e)}};D2.create=(t,e)=>new D2({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Cr.ZodArray,...li(e)});function kR(t){if(t instanceof mh){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=wA.create(kR(r))}return new mh({...t._def,shape:()=>e})}else return t instanceof D2?new D2({...t._def,type:kR(t.element)}):t instanceof wA?wA.create(kR(t.unwrap())):t instanceof gb?gb.create(kR(t.unwrap())):t instanceof hb?hb.create(t.items.map(e=>kR(e))):t}var mh=class t extends Ti{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=Wi.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==zn.object){let u=this._getOrReturnCtx(e);return Dn(u,{code:en.invalid_type,expected:zn.object,received:u.parsedType}),Dr}let{status:r,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof U0&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||s.push(u);let l=[];for(let u of o){let p=a[u],f=i.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new $g(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof U0){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of s)l.push({key:{status:"valid",value:p},value:{status:"valid",value:i.data[p]}});else if(u==="strict")s.length>0&&(Dn(i,{code:en.unrecognized_keys,keys:s}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of s){let f=i.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new $g(i,f,i.path,p)),alwaysSet:p in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of l){let f=await p.key,h=await p.value;u.push({key:f,value:h,alwaysSet:p.alwaysSet})}return u}).then(u=>_p.mergeObjectSync(r,u)):_p.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return nr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:nr.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Cr.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of Wi.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of Wi.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return kR(this)}partial(e){let n={};for(let r of Wi.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of Wi.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof wA;)a=a._def.innerType;n[r]=a}return new t({...this._def,shape:()=>n})}keyof(){return oFe(Wi.objectKeys(this.shape))}};mh.create=(t,e)=>new mh({shape:()=>t,unknownKeys:"strip",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});mh.strictCreate=(t,e)=>new mh({shape:()=>t,unknownKeys:"strict",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});mh.lazycreate=(t,e)=>new mh({shape:t,unknownKeys:"strip",catchall:U0.create(),typeName:Cr.ZodObject,...li(e)});var LR=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new fh(s.ctx.common.issues));return Dn(n,{code:en.invalid_union,unionErrors:o}),Dr}if(n.common.async)return Promise.all(r.map(async a=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(l=>new fh(l));return Dn(n,{code:en.invalid_union,unionErrors:s}),Dr}}get options(){return this._def.options}};LR.create=(t,e)=>new LR({options:t,typeName:Cr.ZodUnion,...li(e)});var mb=t=>t instanceof UR?mb(t.schema):t instanceof xA?mb(t.innerType()):t instanceof zR?[t.value]:t instanceof QR?t.options:t instanceof GR?Wi.objectValues(t.enum):t instanceof HR?mb(t._def.innerType):t instanceof MR?[void 0]:t instanceof PR?[null]:t instanceof wA?[void 0,...mb(t.unwrap())]:t instanceof gb?[null,...mb(t.unwrap())]:t instanceof H$||t instanceof jR?mb(t.unwrap()):t instanceof $R?mb(t._def.innerType):[],Ale=class t extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.object)return Dn(n,{code:en.invalid_type,expected:zn.object,received:n.parsedType}),Dr;let r=this.discriminator,i=n.data[r],a=this.optionsMap.get(i);return a?n.common.async?a._parseAsync({data:n.data,path:n.path,parent:n}):a._parseSync({data:n.data,path:n.path,parent:n}):(Dn(n,{code:en.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Dr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let a of n){let o=mb(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:Cr.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...li(r)})}};function _le(t,e){let n=fb(t),r=fb(e);if(t===e)return{valid:!0,data:t};if(n===zn.object&&r===zn.object){let i=Wi.objectKeys(e),a=Wi.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let l=_le(t[s],e[s]);if(!l.valid)return{valid:!1};o[s]=l.data}return{valid:!0,data:o}}else if(n===zn.array&&r===zn.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let o=t[a],s=e[a],l=_le(o,s);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===zn.date&&r===zn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var FR=class extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(a,o)=>{if(mle(a)||mle(o))return Dr;let s=_le(a.value,o.value);return s.valid?((hle(a)||hle(o))&&n.dirty(),{status:n.value,value:s.data}):(Dn(r,{code:en.invalid_intersection_types}),Dr)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};FR.create=(t,e,n)=>new FR({left:t,right:e,typeName:Cr.ZodIntersection,...li(n)});var hb=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.array)return Dn(r,{code:en.invalid_type,expected:zn.array,received:r.parsedType}),Dr;if(r.data.length<this._def.items.length)return Dn(r,{code:en.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Dr;!this._def.rest&&r.data.length>this._def.items.length&&(Dn(r,{code:en.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let a=[...r.data].map((o,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new $g(r,o,r.path,s)):null}).filter(o=>!!o);return r.common.async?Promise.all(a).then(o=>_p.mergeArray(n,o)):_p.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};hb.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hb({items:t,typeName:Cr.ZodTuple,rest:null,...li(e)})};var yle=class t extends Ti{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.object)return Dn(r,{code:en.invalid_type,expected:zn.object,received:r.parsedType}),Dr;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in r.data)i.push({key:a._parse(new $g(r,s,r.path,s)),value:o._parse(new $g(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?_p.mergeObjectAsync(n,i):_p.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Ti?new t({keyType:e,valueType:n,typeName:Cr.ZodRecord,...li(r)}):new t({keyType:BR.create(),valueType:e,typeName:Cr.ZodRecord,...li(n)})}},c8=class extends Ti{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.map)return Dn(r,{code:en.invalid_type,expected:zn.map,received:r.parsedType}),Dr;let i=this._def.keyType,a=this._def.valueType,o=[...r.data.entries()].map(([s,l],u)=>({key:i._parse(new $g(r,s,r.path,[u,"key"])),value:a._parse(new $g(r,l,r.path,[u,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of o){let u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return Dr;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(u.value,p.value)}return{status:n.value,value:s}})}else{let s=new Map;for(let l of o){let u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return Dr;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(u.value,p.value)}return{status:n.value,value:s}}}};c8.create=(t,e,n)=>new c8({valueType:e,keyType:t,typeName:Cr.ZodMap,...li(n)});var u8=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==zn.set)return Dn(r,{code:en.invalid_type,expected:zn.set,received:r.parsedType}),Dr;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(Dn(r,{code:en.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(Dn(r,{code:en.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let a=this._def.valueType;function o(l){let u=new Set;for(let p of l){if(p.status==="aborted")return Dr;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let s=[...r.data.values()].map((l,u)=>a._parse(new $g(r,l,r.path,u)));return r.common.async?Promise.all(s).then(l=>o(l)):o(s)}min(e,n){return new t({...this._def,minSize:{value:e,message:nr.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:nr.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};u8.create=(t,e)=>new u8({valueType:t,minSize:null,maxSize:null,typeName:Cr.ZodSet,...li(e)});var Ele=class t extends Ti{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.function)return Dn(n,{code:en.invalid_type,expected:zn.function,received:n.parsedType}),Dr;function r(s,l){return G$({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,e8(),w2].filter(u=>!!u),issueData:{code:en.invalid_arguments,argumentsError:l}})}function i(s,l){return G$({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,e8(),w2].filter(u=>!!u),issueData:{code:en.invalid_return_type,returnTypeError:l}})}let a={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof sw){let s=this;return mf(async function(...l){let u=new fh([]),p=await s._def.args.parseAsync(l,a).catch(_=>{throw u.addIssue(r(l,_)),u}),f=await Reflect.apply(o,this,p);return await s._def.returns._def.type.parseAsync(f,a).catch(_=>{throw u.addIssue(i(f,_)),u})})}else{let s=this;return mf(function(...l){let u=s._def.args.safeParse(l,a);if(!u.success)throw new fh([r(l,u.error)]);let p=Reflect.apply(o,this,u.data),f=s._def.returns.safeParse(p,a);if(!f.success)throw new fh([i(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:hb.create(e).rest(x2.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||hb.create([]).rest(x2.create()),returns:n||x2.create(),typeName:Cr.ZodFunction,...li(r)})}},UR=class extends Ti{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};UR.create=(t,e)=>new UR({getter:t,typeName:Cr.ZodLazy,...li(e)});var zR=class extends Ti{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return Dn(n,{received:n.data,code:en.invalid_literal,expected:this._def.value}),Dr}return{status:"valid",value:e.data}}get value(){return this._def.value}};zR.create=(t,e)=>new zR({value:t,typeName:Cr.ZodLiteral,...li(e)});function oFe(t,e){return new QR({values:t,typeName:Cr.ZodEnum,...li(e)})}var QR=class t extends Ti{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return Dn(n,{expected:Wi.joinValues(r),received:n.parsedType,code:en.invalid_type}),Dr}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return Dn(n,{received:n.data,code:en.invalid_enum_value,options:r}),Dr}return mf(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};QR.create=oFe;var GR=class extends Ti{_parse(e){let n=Wi.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==zn.string&&r.parsedType!==zn.number){let i=Wi.objectValues(n);return Dn(r,{expected:Wi.joinValues(i),received:r.parsedType,code:en.invalid_type}),Dr}if(this._cache||(this._cache=new Set(Wi.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Wi.objectValues(n);return Dn(r,{received:r.data,code:en.invalid_enum_value,options:i}),Dr}return mf(e.data)}get enum(){return this._def.values}};GR.create=(t,e)=>new GR({values:t,typeName:Cr.ZodNativeEnum,...li(e)});var sw=class extends Ti{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==zn.promise&&n.common.async===!1)return Dn(n,{code:en.invalid_type,expected:zn.promise,received:n.parsedType}),Dr;let r=n.parsedType===zn.promise?n.data:Promise.resolve(n.data);return mf(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};sw.create=(t,e)=>new sw({type:t,typeName:Cr.ZodPromise,...li(e)});var xA=class extends Ti{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Cr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{Dn(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(r.data,a);if(r.common.async)return Promise.resolve(o).then(async s=>{if(n.value==="aborted")return Dr;let l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?Dr:l.status==="dirty"?OR(l.value):n.value==="dirty"?OR(l.value):l});{if(n.value==="aborted")return Dr;let s=this._def.schema._parseSync({data:o,path:r.path,parent:r});return s.status==="aborted"?Dr:s.status==="dirty"?OR(s.value):n.value==="dirty"?OR(s.value):s}}if(i.type==="refinement"){let o=s=>{let l=i.refinement(s,a);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Dr:(s.status==="dirty"&&n.dirty(),o(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?Dr:(s.status==="dirty"&&n.dirty(),o(s.value).then(()=>({status:n.value,value:s.value}))))}if(i.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ow(o))return Dr;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ow(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:n.value,value:s})):Dr);Wi.assertNever(i)}};xA.create=(t,e,n)=>new xA({schema:t,typeName:Cr.ZodEffects,effect:e,...li(n)});xA.createWithPreprocess=(t,e,n)=>new xA({schema:e,effect:{type:"preprocess",transform:t},typeName:Cr.ZodEffects,...li(n)});var wA=class extends Ti{_parse(e){return this._getType(e)===zn.undefined?mf(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wA.create=(t,e)=>new wA({innerType:t,typeName:Cr.ZodOptional,...li(e)});var gb=class extends Ti{_parse(e){return this._getType(e)===zn.null?mf(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gb.create=(t,e)=>new gb({innerType:t,typeName:Cr.ZodNullable,...li(e)});var HR=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===zn.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};HR.create=(t,e)=>new HR({innerType:t,typeName:Cr.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...li(e)});var $R=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return t8(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new fh(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new fh(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};$R.create=(t,e)=>new $R({innerType:t,typeName:Cr.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...li(e)});var d8=class extends Ti{_parse(e){if(this._getType(e)!==zn.nan){let r=this._getOrReturnCtx(e);return Dn(r,{code:en.invalid_type,expected:zn.nan,received:r.parsedType}),Dr}return{status:"valid",value:e.data}}};d8.create=t=>new d8({typeName:Cr.ZodNaN,...li(t)});var H$=class extends Ti{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},$$=class t extends Ti{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Dr:a.status==="dirty"?(n.dirty(),OR(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Dr:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Cr.ZodPipeline})}},jR=class extends Ti{_parse(e){let n=this._def.innerType._parse(e),r=i=>(ow(i)&&(i.value=Object.freeze(i.value)),i);return t8(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};jR.create=(t,e)=>new jR({innerType:t,typeName:Cr.ZodReadonly,...li(e)});var J4n={object:mh.lazycreate},Cr;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Cr||(Cr={}));var X4n=BR.create,eRn=n8.create,tRn=d8.create,nRn=r8.create,rRn=i8.create,iRn=a8.create,aRn=o8.create,oRn=MR.create,sRn=PR.create,lRn=s8.create,cRn=x2.create,uRn=U0.create,dRn=l8.create,pRn=D2.create,k9t=mh.create,fRn=mh.strictCreate,mRn=LR.create,hRn=Ale.create,gRn=FR.create,ARn=hb.create,_Rn=yle.create,yRn=c8.create,ERn=u8.create,bRn=Ele.create,vRn=UR.create,SRn=zR.create,CRn=QR.create,TRn=GR.create,IRn=sw.create,wRn=xA.create,xRn=wA.create,DRn=gb.create,RRn=xA.createWithPreprocess,NRn=$$.create;sc();sc();sc();or();sc();sc();s4();ez();sc();sc();function qR(t){return!!t._zod}function R2(t,e){return qR(t)?dI(t,e):t.safeParse(e)}function j$(t){if(!t)return;let e;if(qR(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function cFe(t){if(qR(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}s5();var vle="2025-11-25",uFe="2025-03-26",p8=[vle,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],N2="io.modelcontextprotocol/related-task",V$="2.0",wd=SQ(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dFe=po([vt(),Ba().int()]),pFe=vt(),l6n=bd({ttl:po([Ba(),m4()]).optional(),pollInterval:Ba().optional()}),z9t=Ln({ttl:Ba().optional()}),Q9t=Ln({taskId:vt()}),Sle=bd({progressToken:dFe.optional(),[N2]:Q9t.optional()}),hh=Ln({_meta:Sle.optional()}),f8=hh.extend({task:z9t.optional()}),fFe=t=>f8.safeParse(t).success,xd=Ln({method:vt(),params:hh.loose().optional()}),jg=Ln({_meta:Sle.optional()}),qg=Ln({method:vt(),params:jg.loose().optional()}),Dd=bd({_meta:Sle.optional()}),Y$=po([vt(),Ba().int()]),mFe=Ln({jsonrpc:ir(V$),id:Y$,...xd.shape}).strict(),O2=t=>mFe.safeParse(t).success,hFe=Ln({jsonrpc:ir(V$),...qg.shape}).strict(),gFe=t=>hFe.safeParse(t).success,Cle=Ln({jsonrpc:ir(V$),id:Y$,result:Dd}).strict(),Ab=t=>Cle.safeParse(t).success;var Zi;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Zi||(Zi={}));var Tle=Ln({jsonrpc:ir(V$),id:Y$.optional(),error:Ln({code:Ba().int(),message:vt(),data:Do().optional()})}).strict();var YR=t=>Tle.safeParse(t).success;var m8=po([mFe,hFe,Cle,Tle]),c6n=po([Cle,Tle]),K$=Dd.strict(),G9t=jg.extend({requestId:Y$.optional(),reason:vt().optional()}),W$=qg.extend({method:ir("notifications/cancelled"),params:G9t}),H9t=Ln({src:vt(),mimeType:vt().optional(),sizes:vi(vt()).optional(),theme:vd(["light","dark"]).optional()}),h8=Ln({icons:vi(H9t).optional()}),VR=Ln({name:vt(),title:vt().optional()}),AFe=VR.extend({...VR.shape,...h8.shape,version:vt(),websiteUrl:vt().optional(),description:vt().optional()}),$9t=h4(Ln({applyDefaults:lc().optional()}),Go(vt(),Do())),j9t=a5(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,h4(Ln({form:$9t.optional(),url:wd.optional()}),Go(vt(),Do()).optional())),q9t=bd({list:wd.optional(),cancel:wd.optional(),requests:bd({sampling:bd({createMessage:wd.optional()}).optional(),elicitation:bd({create:wd.optional()}).optional()}).optional()}),V9t=bd({list:wd.optional(),cancel:wd.optional(),requests:bd({tools:bd({call:wd.optional()}).optional()}).optional()}),Y9t=Ln({experimental:Go(vt(),wd).optional(),sampling:Ln({context:wd.optional(),tools:wd.optional()}).optional(),elicitation:j9t.optional(),roots:Ln({listChanged:lc().optional()}).optional(),tasks:q9t.optional()}),K9t=hh.extend({protocolVersion:vt(),capabilities:Y9t,clientInfo:AFe}),Z$=xd.extend({method:ir("initialize"),params:K9t}),Ile=t=>Z$.safeParse(t).success,W9t=Ln({experimental:Go(vt(),wd).optional(),logging:wd.optional(),completions:wd.optional(),prompts:Ln({listChanged:lc().optional()}).optional(),resources:Ln({subscribe:lc().optional(),listChanged:lc().optional()}).optional(),tools:Ln({listChanged:lc().optional()}).optional(),tasks:V9t.optional()}),Z9t=Dd.extend({protocolVersion:vt(),capabilities:W9t,serverInfo:AFe,instructions:vt().optional()}),wle=qg.extend({method:ir("notifications/initialized"),params:jg.optional()});var J$=xd.extend({method:ir("ping"),params:hh.optional()}),J9t=Ln({progress:Ba(),total:as(Ba()),message:as(vt())}),X9t=Ln({...jg.shape,...J9t.shape,progressToken:dFe}),X$=qg.extend({method:ir("notifications/progress"),params:X9t}),e3t=hh.extend({cursor:pFe.optional()}),g8=xd.extend({params:e3t.optional()}),A8=Dd.extend({nextCursor:pFe.optional()}),t3t=vd(["working","input_required","completed","failed","cancelled"]),_8=Ln({taskId:vt(),status:t3t,ttl:po([Ba(),m4()]),createdAt:vt(),lastUpdatedAt:vt(),pollInterval:as(Ba()),statusMessage:as(vt())}),KR=Dd.extend({task:_8}),n3t=jg.merge(_8),y8=qg.extend({method:ir("notifications/tasks/status"),params:n3t}),ej=xd.extend({method:ir("tasks/get"),params:hh.extend({taskId:vt()})}),tj=Dd.merge(_8),nj=xd.extend({method:ir("tasks/result"),params:hh.extend({taskId:vt()})}),u6n=Dd.loose(),rj=g8.extend({method:ir("tasks/list")}),ij=A8.extend({tasks:vi(_8)}),aj=xd.extend({method:ir("tasks/cancel"),params:hh.extend({taskId:vt()})}),_Fe=Dd.merge(_8),yFe=Ln({uri:vt(),mimeType:as(vt()),_meta:Go(vt(),Do()).optional()}),EFe=yFe.extend({text:vt()}),xle=vt().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bFe=yFe.extend({blob:xle}),E8=vd(["user","assistant"]),WR=Ln({audience:vi(E8).optional(),priority:Ba().min(0).max(1).optional(),lastModified:e2.datetime({offset:!0}).optional()}),vFe=Ln({...VR.shape,...h8.shape,uri:vt(),description:as(vt()),mimeType:as(vt()),annotations:WR.optional(),_meta:as(bd({}))}),r3t=Ln({...VR.shape,...h8.shape,uriTemplate:vt(),description:as(vt()),mimeType:as(vt()),annotations:WR.optional(),_meta:as(bd({}))}),Dle=g8.extend({method:ir("resources/list")}),i3t=A8.extend({resources:vi(vFe)}),a3t=g8.extend({method:ir("resources/templates/list")}),o3t=A8.extend({resourceTemplates:vi(r3t)}),Rle=hh.extend({uri:vt()}),s3t=Rle,Nle=xd.extend({method:ir("resources/read"),params:s3t}),l3t=Dd.extend({contents:vi(po([EFe,bFe]))}),c3t=qg.extend({method:ir("notifications/resources/list_changed"),params:jg.optional()}),u3t=Rle,d3t=xd.extend({method:ir("resources/subscribe"),params:u3t}),p3t=Rle,f3t=xd.extend({method:ir("resources/unsubscribe"),params:p3t}),m3t=jg.extend({uri:vt()}),h3t=qg.extend({method:ir("notifications/resources/updated"),params:m3t}),g3t=Ln({name:vt(),description:as(vt()),required:as(lc())}),A3t=Ln({...VR.shape,...h8.shape,description:as(vt()),arguments:as(vi(g3t)),_meta:as(bd({}))}),Ole=g8.extend({method:ir("prompts/list")}),_3t=A8.extend({prompts:vi(A3t)}),y3t=hh.extend({name:vt(),arguments:Go(vt(),vt()).optional()}),kle=xd.extend({method:ir("prompts/get"),params:y3t}),Ble=Ln({type:ir("text"),text:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),Mle=Ln({type:ir("image"),data:xle,mimeType:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),Ple=Ln({type:ir("audio"),data:xle,mimeType:vt(),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),E3t=Ln({type:ir("tool_use"),name:vt(),id:vt(),input:Go(vt(),Do()),_meta:Go(vt(),Do()).optional()}),b3t=Ln({type:ir("resource"),resource:po([EFe,bFe]),annotations:WR.optional(),_meta:Go(vt(),Do()).optional()}),v3t=vFe.extend({type:ir("resource_link")}),Lle=po([Ble,Mle,Ple,v3t,b3t]),S3t=Ln({role:E8,content:Lle}),C3t=Dd.extend({description:vt().optional(),messages:vi(S3t)}),T3t=qg.extend({method:ir("notifications/prompts/list_changed"),params:jg.optional()}),I3t=Ln({title:vt().optional(),readOnlyHint:lc().optional(),destructiveHint:lc().optional(),idempotentHint:lc().optional(),openWorldHint:lc().optional()}),w3t=Ln({taskSupport:vd(["required","optional","forbidden"]).optional()}),SFe=Ln({...VR.shape,...h8.shape,description:vt().optional(),inputSchema:Ln({type:ir("object"),properties:Go(vt(),wd).optional(),required:vi(vt()).optional()}).catchall(Do()),outputSchema:Ln({type:ir("object"),properties:Go(vt(),wd).optional(),required:vi(vt()).optional()}).catchall(Do()).optional(),annotations:I3t.optional(),execution:w3t.optional(),_meta:Go(vt(),Do()).optional()}),Fle=g8.extend({method:ir("tools/list")}),x3t=A8.extend({tools:vi(SFe)}),oj=Dd.extend({content:vi(Lle).default([]),structuredContent:Go(vt(),Do()).optional(),isError:lc().optional()}),d6n=oj.or(Dd.extend({toolResult:Do()})),D3t=f8.extend({name:vt(),arguments:Go(vt(),Do()).optional()}),b8=xd.extend({method:ir("tools/call"),params:D3t}),R3t=qg.extend({method:ir("notifications/tools/list_changed"),params:jg.optional()}),p6n=Ln({autoRefresh:lc().default(!0),debounceMs:Ba().int().nonnegative().default(300)}),v8=vd(["debug","info","notice","warning","error","critical","alert","emergency"]),N3t=hh.extend({level:v8}),Ule=xd.extend({method:ir("logging/setLevel"),params:N3t}),O3t=jg.extend({level:v8,logger:vt().optional(),data:Do()}),k3t=qg.extend({method:ir("notifications/message"),params:O3t}),B3t=Ln({name:vt().optional()}),M3t=Ln({hints:vi(B3t).optional(),costPriority:Ba().min(0).max(1).optional(),speedPriority:Ba().min(0).max(1).optional(),intelligencePriority:Ba().min(0).max(1).optional()}),P3t=Ln({mode:vd(["auto","required","none"]).optional()}),L3t=Ln({type:ir("tool_result"),toolUseId:vt().describe("The unique identifier for the corresponding tool call."),content:vi(Lle).default([]),structuredContent:Ln({}).loose().optional(),isError:lc().optional(),_meta:Go(vt(),Do()).optional()}),F3t=n5("type",[Ble,Mle,Ple]),q$=n5("type",[Ble,Mle,Ple,E3t,L3t]),U3t=Ln({role:E8,content:po([q$,vi(q$)]),_meta:Go(vt(),Do()).optional()}),z3t=f8.extend({messages:vi(U3t),modelPreferences:M3t.optional(),systemPrompt:vt().optional(),includeContext:vd(["none","thisServer","allServers"]).optional(),temperature:Ba().optional(),maxTokens:Ba().int(),stopSequences:vi(vt()).optional(),metadata:wd.optional(),tools:vi(SFe).optional(),toolChoice:P3t.optional()}),Q3t=xd.extend({method:ir("sampling/createMessage"),params:z3t}),zle=Dd.extend({model:vt(),stopReason:as(vd(["endTurn","stopSequence","maxTokens"]).or(vt())),role:E8,content:F3t}),Qle=Dd.extend({model:vt(),stopReason:as(vd(["endTurn","stopSequence","maxTokens","toolUse"]).or(vt())),role:E8,content:po([q$,vi(q$)])}),G3t=Ln({type:ir("boolean"),title:vt().optional(),description:vt().optional(),default:lc().optional()}),H3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),minLength:Ba().optional(),maxLength:Ba().optional(),format:vd(["email","uri","date","date-time"]).optional(),default:vt().optional()}),$3t=Ln({type:vd(["number","integer"]),title:vt().optional(),description:vt().optional(),minimum:Ba().optional(),maximum:Ba().optional(),default:Ba().optional()}),j3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),enum:vi(vt()),default:vt().optional()}),q3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),oneOf:vi(Ln({const:vt(),title:vt()})),default:vt().optional()}),V3t=Ln({type:ir("string"),title:vt().optional(),description:vt().optional(),enum:vi(vt()),enumNames:vi(vt()).optional(),default:vt().optional()}),Y3t=po([j3t,q3t]),K3t=Ln({type:ir("array"),title:vt().optional(),description:vt().optional(),minItems:Ba().optional(),maxItems:Ba().optional(),items:Ln({type:ir("string"),enum:vi(vt())}),default:vi(vt()).optional()}),W3t=Ln({type:ir("array"),title:vt().optional(),description:vt().optional(),minItems:Ba().optional(),maxItems:Ba().optional(),items:Ln({anyOf:vi(Ln({const:vt(),title:vt()}))}),default:vi(vt()).optional()}),Z3t=po([K3t,W3t]),J3t=po([V3t,Y3t,Z3t]),X3t=po([J3t,G3t,H3t,$3t]),eOt=f8.extend({mode:ir("form").optional(),message:vt(),requestedSchema:Ln({type:ir("object"),properties:Go(vt(),X3t),required:vi(vt()).optional()})}),tOt=f8.extend({mode:ir("url"),message:vt(),elicitationId:vt(),url:vt().url()}),nOt=po([eOt,tOt]),rOt=xd.extend({method:ir("elicitation/create"),params:nOt}),iOt=jg.extend({elicitationId:vt()}),aOt=qg.extend({method:ir("notifications/elicitation/complete"),params:iOt}),sj=Dd.extend({action:vd(["accept","decline","cancel"]),content:a5(t=>t===null?void 0:t,Go(vt(),po([vt(),Ba(),lc(),vi(vt())])).optional())}),oOt=Ln({type:ir("ref/resource"),uri:vt()});var sOt=Ln({type:ir("ref/prompt"),name:vt()}),lOt=hh.extend({ref:po([sOt,oOt]),argument:Ln({name:vt(),value:vt()}),context:Ln({arguments:Go(vt(),vt()).optional()}).optional()}),cOt=xd.extend({method:ir("completion/complete"),params:lOt});var uOt=Dd.extend({completion:bd({values:vi(vt()).max(100),total:as(Ba().int()),hasMore:as(lc())})}),dOt=Ln({uri:vt().startsWith("file://"),name:vt().optional(),_meta:Go(vt(),Do()).optional()}),pOt=xd.extend({method:ir("roots/list"),params:hh.optional()}),Gle=Dd.extend({roots:vi(dOt)}),fOt=qg.extend({method:ir("notifications/roots/list_changed"),params:jg.optional()}),f6n=po([J$,Z$,cOt,Ule,kle,Ole,Dle,a3t,Nle,d3t,f3t,b8,Fle,ej,nj,rj,aj]),m6n=po([W$,X$,wle,fOt,y8]),h6n=po([K$,zle,Qle,sj,Gle,tj,ij,KR]),g6n=po([J$,Q3t,rOt,pOt,ej,nj,rj,aj]),A6n=po([W$,X$,k3t,h3t,c3t,R3t,T3t,y8,aOt]),_6n=po([K$,Z9t,uOt,C3t,_3t,i3t,o3t,l3t,oj,x3t,tj,ij,KR]),gi=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===Zi.UrlElicitationRequired&&r){let i=r;if(i.elicitations)return new ble(i.elicitations,n)}return new t(e,n,r)}},ble=class extends gi{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Zi.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function k2(t){return t==="completed"||t==="failed"||t==="cancelled"}var J6n=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Hle(t){let n=j$(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=cFe(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function $le(t,e){let n=R2(t,e);if(!n.success)throw n.error;return n.data}var yOt=6e4,lj=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(W$,n=>{this._oncancel(n)}),this.setNotificationHandler(X$,n=>{this._onprogress(n)}),this.setRequestHandler(J$,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ej,async(n,r)=>{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new gi(Zi.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(nj,async(n,r)=>{let i=async()=>{let a=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,r.sessionId);){if(s.type==="response"||s.type==="error"){let l=s.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),s.type==="response")p(l);else{let f=l,h=new gi(f.error.code,f.error.message,f.error.data);p(h)}else{let f=s.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let o=await this._taskStore.getTask(a,r.sessionId);if(!o)throw new gi(Zi.InvalidParams,`Task not found: ${a}`);if(!k2(o.status))return await this._waitForTaskUpdate(a,r.signal),await i();if(k2(o.status)){let s=await this._taskStore.getTaskResult(a,r.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[N2]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(rj,async(n,r)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new gi(Zi.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(aj,async(n,r)=>{try{let i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new gi(Zi.InvalidParams,`Task not found: ${n.params.taskId}`);if(k2(i.status))throw new gi(Zi.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let a=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!a)throw new gi(Zi.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof gi?i:new gi(Zi.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),gi.fromError(Zi.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=a=>{r?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Ab(a)||YR(a)?this._onresponse(a):O2(a)?this._onrequest(a,o):gFe(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=gi.fromError(Zi.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[N2]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:Zi.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},i?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):i?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=fFe(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(o.signal.aborted)return;let f={relatedRequestId:e.id};a&&(f.relatedTask={taskId:a}),await this.notification(p,f)},sendRequest:async(p,f,h)=>{if(o.signal.aborted)throw new gi(Zi.ConnectionClosed,"Request was cancelled");let _={...h,relatedRequestId:e.id};a&&!_.relatedTask&&(_.relatedTask={taskId:a});let y=_.relatedTask?.taskId??a;return y&&l&&await l.updateTaskStatus(y,"input_required"),await this.request(p,f,_)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async p=>{if(o.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:f,timestamp:Date.now()},i?.sessionId):await i?.send(f)},async p=>{if(o.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:Zi.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:f,timestamp:Date.now()},i?.sessionId):await i?.send(f)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,i=Number(n),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(l);return}a(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Ab(e))r(e);else{let o=new gi(e.error.code,e.error.message,e.error.data);r(o)}return}let i=this._responseHandlers.get(n);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let a=!1;if(Ab(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,n))}}if(a||this._progressHandlers.delete(n),Ab(e))i(e);else{let o=gi.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:i}=r??{};if(!i){try{yield{type:"result",result:await this.request(e,n,r)}}catch(o){yield{type:"error",error:o instanceof gi?o:new gi(Zi.InternalError,String(o))}}return}let a;try{let o=await this.request(e,KR,r);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new gi(Zi.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},r);if(yield{type:"taskStatus",task:s},k2(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)}:s.status==="failed"?yield{type:"error",error:new gi(Zi.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new gi(Zi.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},n,r)};return}let l=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),r?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof gi?o:new gi(Zi.InternalError,String(o))}}}request(e,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:l}=r??{};return new Promise((u,p)=>{let f=N=>{p(N)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(N){f(N);return}r?.signal?.throwIfAborted();let h=this._requestMessageId++,_={...e,jsonrpc:"2.0",id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),_.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),s&&(_.params={..._.params,task:s}),l&&(_.params={..._.params,_meta:{..._.params?._meta||{},[N2]:l}});let y=N=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(N)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let O=N instanceof gi?N:new gi(Zi.RequestTimeout,String(N));p(O)};this._responseHandlers.set(h,N=>{if(!r?.signal?.aborted){if(N instanceof Error)return p(N);try{let O=R2(n,N.result);O.success?u(O.data):p(O.error)}catch(O){p(O)}}}),r?.signal?.addEventListener("abort",()=>{y(r?.signal?.reason)});let E=r?.timeout??yOt,S=()=>y(gi.fromError(Zi.RequestTimeout,"Request timed out",{timeout:E}));this._setupTimeout(h,E,r?.maxTotalTimeout,S,r?.resetTimeoutOnProgress??!1);let T=l?.taskId;if(T){let N=O=>{let M=this._responseHandlers.get(h);M?M(O):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,N),this._enqueueTaskMessage(T,{type:"request",message:_,timestamp:Date.now()}).catch(O=>{this._cleanupTimeout(h),p(O)})}else this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(N=>{this._cleanupTimeout(h),p(N)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},tj,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},ij,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},_Fe,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[N2]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[N2]:n.relatedTask}}}),this._transport?.send(s,n).catch(l=>this._onerror(l))});return}let o={...e,jsonrpc:"2.0"};n?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[N2]:n.relatedTask}}}),await this._transport.send(o,n)}setRequestHandler(e,n){let r=Hle(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(i,a)=>{let o=$le(e,i);return Promise.resolve(n(o,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=Hle(e);this._notificationHandlers.set(r,i=>{let a=$le(e,i);return Promise.resolve(n(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,i)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let i of r)if(i.type==="request"&&O2(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new gi(Zi.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(r=i.pollInterval)}catch{}return new Promise((i,a)=>{if(n.aborted){a(new gi(Zi.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,r);n.addEventListener("abort",()=>{clearTimeout(o),a(new gi(Zi.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await r.createTask(i,e.id,{method:e.method,params:e.params},n)},getTask:async i=>{let a=await r.getTask(i,n);if(!a)throw new gi(Zi.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await r.storeTaskResult(i,a,o,n);let s=await r.getTask(i,n);if(s){let l=y8.parse({method:"notifications/tasks/status",params:s});await this.notification(l),k2(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>r.getTaskResult(i,n),updateTaskStatus:async(i,a,o)=>{let s=await r.getTask(i,n);if(!s)throw new gi(Zi.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(k2(s.status))throw new gi(Zi.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(i,a,o,n);let l=await r.getTask(i,n);if(l){let u=y8.parse({method:"notifications/tasks/status",params:l});await this.notification(u),k2(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>r.listTasks(i,n)}}};function CFe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function TFe(t,e){let n={...t};for(let r in e){let i=r,a=e[i];if(a===void 0)continue;let o=n[i];CFe(o)&&CFe(a)?n[i]={...o,...a}:n[i]=a}return n}var dQe=Lt(Due(),1),pQe=Lt(uQe(),1);function u7t(){let t=new dQe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,pQe.default)(t),t}var $j=class{constructor(e){this._ajv=e??u7t()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var jj=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function fQe(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function mQe(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var qj=class extends lj{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v8.options.map((r,i)=>[r,i])),this.isMessageIgnored=(r,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new $j,this.setRequestHandler(Z$,r=>this._oninitialize(r)),this.setNotificationHandler(wle,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ule,async(r,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=r.params,s=v8.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jj(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=TFe(this._capabilities,e)}setRequestHandler(e,n){let i=j$(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(qR(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(l,u)=>{let p=R2(b8,l);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new gi(Zi.InvalidParams,`Invalid tools/call request: ${y}`)}let{params:f}=p.data,h=await Promise.resolve(n(l,u));if(f.task){let y=R2(KR,h);if(!y.success){let E=y.error instanceof Error?y.error.message:String(y.error);throw new gi(Zi.InvalidParams,`Invalid task creation result: ${E}`)}return y.data}let _=R2(oj,h);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new gi(Zi.InvalidParams,`Invalid tools/call result: ${y}`)}return _.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){mQe(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&fQe(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:p8.includes(n)?n:vle,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},K$)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],i=Array.isArray(r.content)?r.content:[r.content],a=i.some(u=>u.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],l=s.some(u=>u.type==="tool_use");if(a){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(s.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==p.size||![...u].every(f=>p.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Qle,n):this.request({method:"sampling/createMessage",params:e},zle,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},sj,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:i},sj,n);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new gi(Zi.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof gi?o:new gi(Zi.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Gle,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import gQe from"node:process";var Vj=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
929
929
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),d7t(n)}clear(){this._buffer=void 0}};function d7t(t){return m8.parse(JSON.parse(t))}function hQe(t){return JSON.stringify(t)+`
930
930
  `}var Yj=class{constructor(e=gQe.stdin,n=gQe.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Vj,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=hQe(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{Http2ServerRequest as p7t}from"http2";import{Http2ServerRequest as Lue}from"http2";import{Readable as AQe}from"stream";import C7t from"crypto";var _w=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},f7t=t=>t instanceof _w?t:new _w(t.message,{cause:t}),m7t=global.Request,X8=class extends m7t{constructor(t,e){typeof t=="object"&&g6 in t&&(t=t[g6]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},h7t=t=>{let e=[],n=t.rawHeaders;for(let r=0;r<n.length;r+=2){let{[r]:i,[r+1]:a}=n;i.charCodeAt(0)!==58&&e.push([i,a])}return new Headers(e)},yQe=Symbol("wrapBodyStream"),g7t=(t,e,n,r,i)=>{let a={method:t,headers:n,signal:i.signal};if(t==="TRACE"){a.method="GET";let o=new X8(e,a);return Object.defineProperty(o,"method",{get(){return"TRACE"}}),o}if(!(t==="GET"||t==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(o){o.enqueue(r.rawBody),o.close()}});else if(r[yQe]){let o;a.body=new ReadableStream({async pull(s){try{o||=AQe.toWeb(r).getReader();let{done:l,value:u}=await o.read();l?s.close():s.enqueue(u)}catch(l){s.error(l)}}})}else a.body=AQe.toWeb(r);return new X8(e,a)},g6=Symbol("getRequestCache"),A7t=Symbol("requestCache"),Kj=Symbol("incomingKey"),Wj=Symbol("urlKey"),_7t=Symbol("headersKey"),h6=Symbol("abortControllerKey"),y7t=Symbol("getAbortController"),Zj={get method(){return this[Kj].method||"GET"},get url(){return this[Wj]},get headers(){return this[_7t]||=h7t(this[Kj])},[y7t](){return this[g6](),this[h6]},[g6](){return this[h6]||=new AbortController,this[A7t]||=g7t(this.method,this[Wj],this.headers,this[Kj],this[h6])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Zj,t,{get(){return this[g6]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Zj,t,{value:function(){return this[g6]()[t]()}})});Object.setPrototypeOf(Zj,X8.prototype);var E7t=(t,e)=>{let n=Object.create(Zj);n[Kj]=t;let r=t.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(t instanceof Lue)throw new _w("Absolute URL for :path is not allowed in HTTP/2");try{let s=new URL(r);n[Wj]=s.href}catch(s){throw new _w("Invalid absolute URL",{cause:s})}return n}let i=(t instanceof Lue?t.authority:t.headers.host)||e;if(!i)throw new _w("Missing host header");let a;if(t instanceof Lue){if(a=t.scheme,!(a==="http"||a==="https"))throw new _w("Unsupported scheme")}else a=t.socket&&t.socket.encrypted?"https":"http";let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,""))throw new _w("Invalid host header");return n[Wj]=o.href,n},_Qe=Symbol("responseCache"),m6=Symbol("getResponseCache"),yw=Symbol("cache"),Uue=global.Response,eB=class EQe{#e;#t;[m6](){return delete this[yw],this[_Qe]||=new Uue(this.#e,this.#t)}constructor(e,n){let r;if(this.#e=e,n instanceof EQe){let i=n[_Qe];if(i){this.#t=i,this[m6]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(r||=n?.headers||{"content-type":"text/plain; charset=UTF-8"},this[yw]=[n?.status||200,e,r])}get headers(){let e=this[yw];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[m6]().headers}get status(){return this[yw]?.[0]??this[m6]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(eB.prototype,t,{get(){return this[m6]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(eB.prototype,t,{value:function(){return this[m6]()[t]()}})});Object.setPrototypeOf(eB,Uue);Object.setPrototypeOf(eB.prototype,Uue.prototype);async function b7t(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function bQe(t,e,n){let r=s=>{t.cancel(s).catch(()=>{})};return e.on("close",r),e.on("error",r),(n??t.read()).then(o,i),t.closed.finally(()=>{e.off("close",r),e.off("error",r)});function i(s){s&&e.destroy(s)}function a(){t.read().then(o,i)}function o({done:s,value:l}){try{if(s)e.end();else if(!e.write(l))e.once("drain",a);else return t.read().then(o,i)}catch(u){i(u)}}}function v7t(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:bQe(t.getReader(),e)}var vQe=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let n=[];for(let[r,i]of t)r==="set-cookie"?n.push(i):e[r]=i;return n.length>0&&(e["set-cookie"]=n),e["content-type"]??="text/plain; charset=UTF-8",e},S7t="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=C7t);var zue=Symbol("outgoingEnded"),T7t=()=>new Response(null,{status:400}),SQe=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Fue=(t,e)=>{let n=t instanceof Error?t:new Error("unknown error",{cause:t});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${n.message}`),e.destroy(n))},CQe=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},TQe=async(t,e)=>{let[n,r,i]=t[yw];i instanceof Headers&&(i=vQe(i)),typeof r=="string"?i["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?i["Content-Length"]=r.byteLength:r instanceof Blob&&(i["Content-Length"]=r.size),e.writeHead(n,i),typeof r=="string"||r instanceof Uint8Array?e.end(r):r instanceof Blob?e.end(new Uint8Array(await r.arrayBuffer())):(CQe(e),await v7t(r,e)?.catch(a=>Fue(a,e))),e[zue]?.()},I7t=t=>typeof t.then=="function",w7t=async(t,e,n={})=>{if(I7t(t))if(n.errorHandler)try{t=await t}catch(i){let a=await n.errorHandler(i);if(!a)return;t=a}else t=await t.catch(SQe);if(yw in t)return TQe(t,e);let r=vQe(t.headers);if(t.body){let i=t.body.getReader(),a=[],o=!1,s;if(r["transfer-encoding"]!=="chunked"){let l=2;for(let u=0;u<l;u++){s||=i.read();let p=await b7t(s).catch(f=>{console.error(f),o=!0});if(!p){if(u===1){await new Promise(f=>setTimeout(f)),l=3;continue}break}if(s=void 0,p.value&&a.push(p.value),p.done){o=!0;break}}o&&!("content-length"in r)&&(r["content-length"]=a.reduce((u,p)=>u+p.length,0))}e.writeHead(t.status,r),a.forEach(l=>{e.write(l)}),o?e.end():(a.length===0&&CQe(e),await bQe(i,e,s))}else r[S7t]||(e.writeHead(t.status,r),e.end());e[zue]?.()},Que=(t,e={})=>{let n=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==X8&&(Object.defineProperty(global,"Request",{value:X8}),Object.defineProperty(global,"Response",{value:eB})),async(r,i)=>{let a,o;try{o=E7t(r,e.hostname);let s=!n||r.method==="GET"||r.method==="HEAD";if(s||(r[yQe]=!0,r.on("end",()=>{s=!0}),r instanceof p7t&&(i[zue]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{r.destroy(),i.destroy()})})})),i.on("close",()=>{o[h6]&&(r.errored?o[h6].abort(r.errored.toString()):i.writableFinished||o[h6].abort("Client connection prematurely closed.")),s||setTimeout(()=>{s||setTimeout(()=>{r.destroy()})})}),a=t(o,{incoming:r,outgoing:i}),yw in a)return TQe(a,i)}catch(s){if(a)return Fue(s,i);if(e.errorHandler){if(a=await e.errorHandler(o?s:f7t(s)),!a)return}else o?a=SQe(s):a=T7t()}try{return await w7t(a,i,e)}catch(s){return Fue(s,i)}}};var Jj=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,n,r,i){let a={code:n,message:r};return i?.data!==void 0&&(a.data=i.data),new Response(JSON.stringify({jsonrpc:"2.0",error:a,id:null}),{status:e,headers:{"Content-Type":"application/json",...i?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let n=e.headers.get("host");if(!n||!this._allowedHosts.includes(n)){let r=`Invalid Host header: ${n}`;return this.onerror?.(new Error(r)),this.createJsonErrorResponse(403,-32e3,r)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let n=e.headers.get("origin");if(n&&!this._allowedOrigins.includes(n)){let r=`Invalid Origin header: ${n}`;return this.onerror?.(new Error(r)),this.createJsonErrorResponse(403,-32e3,r)}}}}async handleRequest(e,n){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let r=this.validateRequestHeaders(e);if(r)return r;switch(e.method){case"POST":return this.handlePostRequest(e,n);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,n,r,i){if(!this._eventStore||i<"2025-11-25")return;let a=await this._eventStore.storeEvent(r,{}),o=`id: ${a}
931
931
  data: