@visa/cli 1.3.0 → 1.4.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +49 -49
- package/dist/mcp-server/index.js +3 -3
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var An=Object.create;var dt=Object.defineProperty;var Ln=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var In=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var On=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Dn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nn(t))!Mn.call(e,s)&&s!==n&&dt(e,s,{get:()=>t[s],enumerable:!(r=Ln(t,s))||r.enumerable});return e};var m=(e,t,n)=>(n=e!=null?An(In(e)):{},Dn(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e));var Be=On((ss,Jn)=>{Jn.exports={name:"@visa/cli",version:"1.4.0-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","README.md","LICENSE"]}});var _n=require("commander"),Me=m(require("crypto")),$n=m(require("fs")),I=m(require("os")),pe=m(require("path")),Cn=m(require("readline")),xn=require("child_process"),kn=require("util");var ge=require("child_process"),pt=require("util"),q=m(require("fs")),he=m(require("os")),He=m(require("path")),O=(0,pt.promisify)(ge.execFile),Ve=He.join(he.homedir(),".visa-mcp"),fe=He.join(Ve,"session-token"),L="visa-cli",K="session-token",me="rc-access",jn=5e3;async function Un(){try{let{stdout:e}=await O("security",["find-generic-password","-s",L,"-a",K,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Hn(e){try{try{await O("security",["delete-generic-password","-s",L,"-a",K],{timeout:5e3})}catch{}return await O("security",["add-generic-password","-s",L,"-a",K,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Vn(){try{await O("security",["delete-generic-password","-s",L,"-a",K],{timeout:5e3})}catch{}}async function Fn(){if(!Fe())return null;try{let{stdout:e}=await O("secret-tool",["lookup","service",L,"account",K],{timeout:5e3});return e.trim()||null}catch{return null}}async function Bn(e){if(!Fe())return!1;try{let t=(0,ge.execFile)("secret-tool",["store","--label",`${L} ${K}`,"service",L,"account",K]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},jn))]),!0):!1}catch{return!1}}async function Kn(){if(Fe())try{await O("secret-tool",["clear","service",L,"account",K],{timeout:5e3})}catch{}}function Fe(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function qn(){try{let{stdout:e}=await O("security",["find-generic-password","-s",L,"-a",me,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Gn(e){try{try{await O("security",["delete-generic-password","-s",L,"-a",me],{timeout:5e3})}catch{}await O("security",["add-generic-password","-s",L,"-a",me,"-w",e],{timeout:5e3})}catch{}}async function Wn(){try{await O("security",["delete-generic-password","-s",L,"-a",me],{timeout:5e3})}catch{}}function je(){try{return q.readFileSync(fe,"utf-8").trim()||null}catch{return null}}function ft(e){q.mkdirSync(Ve,{recursive:!0,mode:448}),q.writeFileSync(fe,e,{mode:384}),process.platform==="win32"&&zn(fe)}function Ue(){try{q.unlinkSync(fe)}catch{}}function zn(e){try{let t=he.userInfo().username;(0,ge.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function De(){switch(process.platform){case"darwin":return{get:Un,store:Hn,delete:Vn};case"linux":return{get:Fn,store:Bn,delete:Kn};default:return{get:async()=>je(),store:async e=>{try{return ft(e),!0}catch{return!1}},delete:async()=>Ue()}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=De(),n=await t.get();if(n)return n;let r=je();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=De();if(await n.store(t)){if(await n.get()===t){Ue();return}await n.delete()}if(ft(t),je()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Ve} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":qn()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Gn(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await De().delete(),Ue()}static async clearAll(){await this.deleteSessionToken(),await Wn()}};var ye=m(require("crypto")),Se=m(require("tty")),be=m(require("fs"));var J="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function Yn(e){return/-rc\.|-beta\./.test(e)}function Ke(e){return ye.createHash("sha256").update(e.trim()).digest("hex")}function mt(e){return J==="SKIP"?!0:ye.timingSafeEqual(Buffer.from(Ke(e)),Buffer.from(J))}function Xn(e){return new Promise((t,n)=>{let r=be.openSync("/dev/tty","r+"),s=new Se.ReadStream(r),o=new Se.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{be.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
|
|
2
2
|
`?(o.write(`
|
|
3
3
|
`),i(),t(a)):c===""?(o.write(`
|
|
4
|
-
`),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),o.write("\b \b")):(a+=c,o.write("\u2022"))})})}var
|
|
4
|
+
`),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),o.write("\b \b")):(a+=c,o.write("\u2022"))})})}var Zn=`
|
|
5
5
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
6
6
|
\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
|
|
7
7
|
\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
|
|
@@ -10,31 +10,32 @@
|
|
|
10
10
|
\u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
|
|
11
11
|
|
|
12
12
|
This is a Release Candidate build. Access is restricted to Visa employees.
|
|
13
|
-
`;async function
|
|
14
|
-
`),process.exit(1)}let
|
|
13
|
+
`;async function gt(e={}){let t=e.version??Be().version;if(!Yn(t))return;let n=process.env.VISA_RC_CODE;if(n&&mt(n)){await $.saveRcAccessToken(Ke(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(J==="SKIP"||i===J))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
|
|
14
|
+
`),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(J==="SKIP"||s===J))return;console.log(Zn);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Xn(" Enter RC access code: ")}catch{process.exit(1)}if(mt(a)){await $.saveRcAccessToken(Ke(a)),console.log(`
|
|
15
15
|
Access granted. Welcome.
|
|
16
16
|
`);return}i<o&&console.log(`
|
|
17
17
|
Invalid code. ${o-i} attempt(s) remaining.
|
|
18
18
|
`)}console.log(`
|
|
19
19
|
Invalid code. Contact your team lead.
|
|
20
|
-
`),process.exit(1)}var
|
|
21
|
-
`)}function
|
|
22
|
-
`))n(` ${c}`);n("");let i=
|
|
23
|
-
`),
|
|
24
|
-
`);
|
|
25
|
-
`)
|
|
26
|
-
`)
|
|
27
|
-
|
|
20
|
+
`),process.exit(1)}var ht=require("child_process");function Qn(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function er(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
|
|
21
|
+
`)}function tr(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function yt(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,p,u)=>{(0,ht.execFile)(c,p,d=>u(d))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of er(e).split(`
|
|
22
|
+
`))n(` ${c}`);n("");let i=Qn(r,s);if(i.headless){n(` (${i.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let a=tr(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(a.cmd,a.args,p=>{p?(n(` Could not open browser automatically (${p.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var bt=m(require("crypto")),P=m(require("fs")),ve=m(require("path"));function vt(e,t){P.mkdirSync(ve.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${bt.randomBytes(8).toString("hex")}.tmp`;try{P.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
23
|
+
`),P.renameSync(n,e)}catch(r){try{P.unlinkSync(n)}catch{}throw r}}function St(e){return`'${e.replace(/'/g,"'\\''")}'`}var wt="# visa-cli-hud-v1";function nr(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?ve.resolve(r):"";return`${s?`${St(n)} ${St(s)} statusline`:"visa-cli statusline"} ${wt}`}function _t(e){return typeof e!="string"?!1:e.includes(wt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function qe(e,t=nr){let n={},r=!1;if(P.existsSync(e)){r=!0;try{n=JSON.parse(P.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli hud enable`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return _t(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},vt(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli hud enable`}}}function $t(e){if(!P.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(P.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return _t(n)?(delete t.statusLine,vt(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var H=m(require("fs")),G=m(require("path")),rr=50,sr=64*1024,Ct=10,Ge=80;function or(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var We=or(),y={reset:"\x1B[0m",visaBlue:We?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:We?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:We?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function b(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${y.reset}`}function xt(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Et(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(p)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),p=setTimeout(()=>{n.length>0?a():o(null)},rr);e.on("data",i),e.on("end",a),e.on("error",c)})}function Rt(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${b(r||"",y.visaBlueSoft)}${b(s||"",y.dim)}`}function kt(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function ir(e){let t=` ${b("\u2502",y.dim)} `,n=Y(e.model?.display_name)||"claude",r=e.cwd?Y(G.basename(e.cwd)):"",s=hr(e.workspace),o=r||s,i=s&&s!==o?` ${b(`@${s}`,y.visaBlueSoft)}`:"",a=[b(`[${n}]`,y.visaBlue)];o&&a.push(`${b(o,y.visaGold)}${i}`);let c=a.join(t),p=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,l=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(B=>typeof B=="number"&&Number.isFinite(B)),h=l.length>0?l.reduce((B,Oe)=>B+Oe,0):null,v=Number(e.context_window?.total_input_tokens??h??d?.input_tokens??0),x=u!==null?Math.max(0,Math.min(1,u/100)):p>0?Math.max(0,Math.min(1,v/p)):0,j=u!==null&&p>0?Math.round(x*p):v,U;if(p>0||u!==null){let B=`${String(Math.round(x*100)).padStart(2," ")}%`,Oe=p>0?` ${b(`(${kt(j)}/${kt(p)})`,y.dim)}`:"";U=`${b("Context",y.dim)} ${Rt(x)} ${b(B,y.green)}${Oe}`}else U=`${b("Context",y.dim)} ${b("-",y.dim)}`;let V=cr(e.rate_limits),F=[U];V&&F.push(V);let k=F.join(t);return`${c}
|
|
24
|
+
${k}`}function ar(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Pt(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Rt(r),o=n>=90?"\x1B[38;5;196m":n>=70?y.visaGold:y.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=ar(e.resets_at),c=a?` ${b(`(${a} / ${t})`,y.dim)}`:` ${b(`(${t})`,y.dim)}`;return`${s} ${b(i,o)}${c}`}function cr(e){if(!e)return null;let t=Pt(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Pt(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${b("\u2502",y.dim)} `,o=[t,r].filter(Boolean);return`${b("Usage",y.dim)} ${o.join(s)}`}function lr(e){let t;try{let n=H.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,sr),o=r-s;t=H.openSync(e,"r");let i=Buffer.alloc(s);H.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(H.readSync(t,c,0,1,o-1),c[0]!==10){let p=a.indexOf(`
|
|
25
|
+
`);p>=0&&(a=a.slice(p+1))}}return a}catch{return null}finally{if(t!==void 0)try{H.closeSync(t)}catch{}}}function ur(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=G.basename(G.dirname(s)),i=G.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function dr(e){let t=e.split(`
|
|
26
|
+
`),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Ct*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let p=c.content;if(Array.isArray(p))for(let u of p){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let l=typeof d.id=="string"?d.id:"",h=l.length>0?!r.has(l):!1;n.push({name:d.name,target:ur(d.input),running:h})}}}return n.reverse(),n.slice(Math.max(0,n.length-Ct))}function pr(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function fr(e){let t=e.running?b("\u25D0",y.visaGold):b("\u2713",y.green),n=e.running?y.visaGold:y.visaBlueSoft,r=b(Y(e.name),n),s=e.target?Y(e.target):"",o=s?`${b(":",y.dim)} ${b(s,y.dim)}`:"",i=e.count>1?` ${b(`\xD7${e.count}`,y.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function mr(e){let t=` ${b("\u2502",y.dim)} `,n=xt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(xt(c)<=Ge)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Ge-n-1?i.slice(0,Ge-n-1)+s:i;return`${b(s,y.dim)}${t}${a}`}async function gr(e){if(!e||typeof e!="string")return null;let t=lr(e);if(!t)return null;let n;try{n=dr(t)}catch{return null}if(n.length===0)return null;let s=pr(n).map(fr);return mr(s)||null}async function Tt(e,t){let n=[e];if(t){let r=ir(t);if(r&&n.push(r),t.transcript_path){let s=await gr(t.transcript_path);s&&n.push(s)}}return n.join(`
|
|
27
|
+
`)}function Y(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function hr(e){if(typeof e=="string")return Y(G.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return Y(t?G.basename(t):e.name)}async function At(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var yr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Nt(e,t){let n=Lt(e),r=Lt(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Sr(n.pre,r.pre)>0}function Lt(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(yr);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Sr(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),p=/^\d+$/.test(a);if(c&&p){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(p)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function W(){return!!(It(process.env.VISA_CLI_NO_UPDATE_CHECK)||It(process.env.CI)||process.env.NODE_ENV==="test")}function It(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var ze="1.4.0-rc.0",ee=class{constructor(t){this.getSessionToken=t;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!W()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&Nt(r,ze)&&(this.lastSignals.updateAvailable={version:r,message:s||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return ze}async request(t,n,r,s,o){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let a={Authorization:`Bearer ${i}`};o&&(t==="GET"?a["X-User-Context"]=o.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:o}),r&&(a["Content-Type"]="application/json");let c;try{c=await At(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":ze},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let p;try{p=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(p?.error||`Request failed (${c.status}). Try again.`);return p}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s)}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async catalogSearch(t,n){let r=new URLSearchParams;t&&r.set("q",t),n&&r.set("category",n);let s=r.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(t){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`)}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getTransactions(t){return this.request("GET","/v1/transactions",void 0,void 0,t)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var Qe=require("child_process"),Vt=require("util"),Ft=m(require("crypto")),C=m(require("fs")),Bt=m(require("os")),D=m(require("path"));var E=m(require("fs")),Xe=m(require("path")),Mt=m(require("os")),Ye=Xe.join(Mt.homedir(),".visa-mcp"),re=Xe.join(Ye,"mcp-server.log"),br=5*1024*1024,Je=null;function vr(){E.existsSync(Ye)||E.mkdirSync(Ye,{recursive:!0,mode:448})}function wr(){if(!Je){if(vr(),E.existsSync(re)&&E.statSync(re).size>br){let t=re+".1";E.existsSync(t)&&E.unlinkSync(t),E.renameSync(re,t)}Je=E.createWriteStream(re,{flags:"a"})}return Je}function we(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
|
|
28
|
+
`;process.stderr.write(s),wr().write(s)}var Ot={debug:(...e)=>we("DEBUG",...e),info:(...e)=>we("INFO",...e),warn:(...e)=>we("WARN",...e),error:(...e)=>we("ERROR",...e)};var te=(0,Vt.promisify)(Qe.execFile),Ce=D.join(Bt.homedir(),".visa-mcp","bin"),X=D.join(Ce,"Visa CLI"),_r=D.join(__dirname,"..","native"),Dt="5",jt=D.join(Ce,"visa-keychain.version"),Ut=D.join(Ce,"visa-keychain.sha256");function Ht(e){let t=C.readFileSync(e);return Ft.createHash("sha256").update(t).digest("hex")}async function Kt(){try{if(C.readFileSync(jt,"utf-8").trim()===Dt&&C.existsSync(X)){let r=C.readFileSync(Ut,"utf-8").trim();if(Ht(X)!==r)Ot.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),C.unlinkSync(X);else return X}}catch{}let e=D.join(_r,"visa-keychain.m");if(C.existsSync(e)||(e=D.resolve(__dirname,"..","..","native","visa-keychain.m")),C.existsSync(e)||(e=D.resolve(__dirname,"..","native","visa-keychain.m")),!C.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");C.mkdirSync(Ce,{recursive:!0,mode:448});try{await te("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",X,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ht(X);return C.writeFileSync(Ut,t,{mode:384}),C.writeFileSync(jt,Dt,{mode:384}),X}async function qt(e){let t=await Kt(),n;try{n=(await te(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Ze=null;function se(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ze!==null?Ze:(Ze=!0,!0)}var _e="visa-cli",$e="attestation-key";async function $r(e){try{await te("security",["delete-generic-password","-s",_e,"-a",$e],{timeout:5e3})}catch{}await te("security",["add-generic-password","-s",_e,"-a",$e,"-w",e],{timeout:5e3})}async function Cr(){try{let{stdout:e}=await te("security",["find-generic-password","-s",_e,"-a",$e,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Gt(){let e=await qt(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await $r(n),r}async function Wt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Cr();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Kt(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Qe.execFile)(r,s,{timeout:6e4},(c,p)=>{let u=(p||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function zt(){try{await te("security",["delete-generic-password","-s",_e,"-a",$e],{timeout:5e3})}catch{}try{await qt(["delete-key"])}catch{}}function Jt(e,t=process.stderr){if(W()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
|
|
28
29
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
29
|
-
`),!0):!1}function
|
|
30
|
+
`),!0):!1}function Xt(e,t,n,r){let o=Lr(e.spendingControls).dailyLimit,i=Math.max(0,oe(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,oe(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(Er),d=u.slice(0,3),l=Rr(u,3),h=(e.cards??[]).slice(0,3),v=r.latestVersion?et(r.latestVersion):"",x=r.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",j=Math.round(c*100),U=z(e.status,e.enrolled?"approved":"not enrolled"),F=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${U} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${x}`,`Spend meter: ${Yt(c)} ${String(j).padStart(3," ")}% | remaining ${ne(a)}/day | daily cap ${ne(o)}`,"","Spend",` Remaining ${ne(a)} / ${ne(o)}`,` Usage ${Yt(c)} ${j}%`,` Spent today ${ne(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...h.length>0?h.map(k=>` ${Ar(k)}`):[" No cards enrolled"],"","Last 3 services",...l.length>0?l.map((k,B)=>` ${B+1}. ${k}`):[" No paid services yet"],"","Recent receipts",...d.length>0?d.map(k=>` ${Tr(k)}`):[" No receipts yet"]];return r.updateMessage&&F.push("",`Update: ${et(r.updateMessage)}`),`${F.join(`
|
|
30
31
|
`)}
|
|
31
|
-
`}function
|
|
32
|
+
`}function kr(e){return e.tool_name!=null}function Pr(e){return oe(e.amount)===0&&e.status==="failed"}function Er(e){return kr(e)&&!Pr(e)}function Rr(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=z(s.merchant_name,"Unknown merchant"),i=z(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Tr(e){let t=z(e.merchant_name,"Unknown merchant"),n=z(e.tool_name,"unknown_tool"),r=ne(oe(e.amount)),s=z(e.status,"unknown"),o=Nr(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ar(e){let t=z(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Lr(e){return{dailyLimit:oe(e?.daily_limit??e?.dailyLimit??0)}}function oe(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function ne(e){return`$${e.toFixed(2)}`}function Yt(e,t=20){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function z(e,t){let n=et(e??"").trim();return n.length>0?n:t}function Nr(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?z(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function et(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var g=m(require("fs")),Re=m(require("os")),w=m(require("path")),Qt=require("child_process"),Ir=2,xe="# >>> visa-cli shell hud v2 >>>",ke="# <<< visa-cli shell hud v2 <<<",Mr="# >>> visa-cli shell hud >>>",Or="# <<< visa-cli shell hud <<<",en=3e4,Dr=3e4;function st(){try{return w.join(cn(),".visa-cli")}catch{return w.join(Re.tmpdir(),".visa-cli")}}function ae(){return w.join(st(),"shell-hud.json")}function Te(){return w.join(st(),"shell-hud.line")}function tn(){return w.join(st(),"shell-hud.lock")}function Ae(e){let t=e??process.env.SHELL;if(!t)return null;let n=w.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Le(e){let t=cn();if(e==="zsh")return w.join(t,".zshrc");if(e==="bash")return w.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return w.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function jr(e){let t="$HOME/.visa-cli/shell-hud.line",n=Kr(e),r=qr(e);if(e==="zsh")return`${xe}
|
|
32
33
|
_visa_cli_shell_hud_precmd() {
|
|
33
34
|
setopt localoptions no_bg_nice
|
|
34
35
|
if [[ -f "${t}" ]]; then
|
|
35
36
|
print -r -- "$(cat "${t}")"
|
|
36
37
|
fi
|
|
37
|
-
if ${
|
|
38
|
+
if ${r}; then
|
|
38
39
|
${n} &>/dev/null &!
|
|
39
40
|
fi
|
|
40
41
|
}
|
|
@@ -42,15 +43,15 @@ autoload -Uz add-zsh-hook
|
|
|
42
43
|
if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
|
|
43
44
|
add-zsh-hook precmd _visa_cli_shell_hud_precmd
|
|
44
45
|
fi
|
|
45
|
-
${
|
|
46
|
+
${ke}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${xe}
|
|
46
47
|
if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
|
|
47
48
|
$function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
|
|
48
49
|
}
|
|
49
50
|
function global:prompt {
|
|
50
|
-
if (Test-Path ${
|
|
51
|
-
Write-Host (Get-Content ${
|
|
51
|
+
if (Test-Path ${s}) {
|
|
52
|
+
Write-Host (Get-Content ${s} -Raw)
|
|
52
53
|
}
|
|
53
|
-
if (${
|
|
54
|
+
if (${r}) {
|
|
54
55
|
# Reap any completed visa-hud jobs before starting a new one so the session
|
|
55
56
|
# doesn't accumulate job records over time.
|
|
56
57
|
Get-Job -Name __visa_hud_refresh -ErrorAction SilentlyContinue | Where-Object { $_.State -in 'Completed','Failed','Stopped' } | Remove-Job -Force -ErrorAction SilentlyContinue
|
|
@@ -58,12 +59,12 @@ function global:prompt {
|
|
|
58
59
|
}
|
|
59
60
|
& $function:global:__visa_cli_original_prompt
|
|
60
61
|
}
|
|
61
|
-
${
|
|
62
|
+
${ke}`}return`${xe}
|
|
62
63
|
__visa_cli_shell_hud_precmd() {
|
|
63
64
|
if [ -f "${t}" ]; then
|
|
64
65
|
cat "${t}"
|
|
65
66
|
fi
|
|
66
|
-
if ${
|
|
67
|
+
if ${r}; then
|
|
67
68
|
${n} &>/dev/null &
|
|
68
69
|
fi
|
|
69
70
|
}
|
|
@@ -71,21 +72,20 @@ case ";$PROMPT_COMMAND;" in
|
|
|
71
72
|
*";__visa_cli_shell_hud_precmd;"*) ;;
|
|
72
73
|
*) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
|
|
73
74
|
esac
|
|
74
|
-
${
|
|
75
|
+
${ke}`}function nn(e){let t=e;for(let[n,r]of[[xe,ke],[Mr,Or]])t=t.replace(new RegExp(`\\n?${Zt(n)}[\\s\\S]*?${Zt(r)}\\n?`,"g"),"");return t.trimEnd()}function Ur(e,t){let n=nn(e).trimEnd(),r=jr(t);return n.length>0?`${n}
|
|
75
76
|
|
|
76
|
-
${
|
|
77
|
-
`:`${
|
|
78
|
-
`}function
|
|
79
|
-
`:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${
|
|
80
|
-
|
|
81
|
-
`),Ee(ce(),n+`
|
|
82
|
-
`)
|
|
83
|
-
`),{
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
Step
|
|
87
|
-
Step
|
|
88
|
-
Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info below the Claude Code input, so"),console.log(" you can see your spend, card, and session usage in real time.");let l;if(e.yes?(l=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?l=await Xs(" Enable Visa HUD? [Y/n] ",!0):(l=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),l){let g=Ke(a),b=g.installed==="new"||g.installed==="already-visa"||g.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${b}${g.message}`);try{let R=z(),D=await R.getStatus(),K={currentVersion:R.getClientVersion(),latestVersion:R.lastSignals?.updateAvailable?.version,updateMessage:R.lastSignals?.updateAvailable?.message,updateCheckDisabled:F()},q=rt(D,K);Le(q),console.log(` Preview: ${q.split(`
|
|
77
|
+
${r}
|
|
78
|
+
`:`${r}
|
|
79
|
+
`}function rn(e=Ae()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=Le(e);let n=g.existsSync(t)?g.readFileSync(t,"utf-8"):"",r=Ur(n,e),s=r!==n;return s&&Ee(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${ln(n)}`}}}function sn(e=Ae()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Le(e),!g.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=g.readFileSync(t,"utf-8"),r=nn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Ee(t,r.length>0?`${r}
|
|
80
|
+
`:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${ln(n)}`}}}function ot(e,t){let n=Pe(t.currentVersion),r=` ${N("\u2502",A.dim)} `;if(!e.enrolled)return`${N("VISA CLI",A.visaBlue)} ${N(`v${n}`,A.visaBlueSoft)}${r}${N("setup needed",A.visaGold)}`;let s=tt(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),o=Math.max(0,tt(e.dailySpent)),i=s>0?Math.min(s,Math.max(0,tt(e.dailyRemaining??s-o))):0,a=s>0?Math.max(0,Math.min(1,o/s)):0,c=Fr(e),p=s>0?`${Vr(a)} ${N(`${nt(i)} left today`,A.green)} ${N(`(${nt(o)}/${nt(s)}/day)`,A.dim)}`:N("no spend limit",A.dim);return`${N("VISA CLI",A.visaBlue)} ${N(`v${n}`,A.visaBlueSoft)}${r}${N(c,A.visaGold)}${r}${p}`}function on(){let e=an();return!!e&&Date.now()-e.renderedAt<=en}function it(){let e=an();if(e&&Date.now()-e.renderedAt<=en||(Hr(),e?.line))return e.line;try{let t=Te();if(g.existsSync(t))return g.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function at(e){try{let t=w.dirname(ae());g.mkdirSync(t,{recursive:!0});let n=Pe(e),r={hudVersion:Ir,renderedAt:Date.now(),line:n};Ee(ae(),JSON.stringify(r)+`
|
|
81
|
+
`),Ee(Te(),n+`
|
|
82
|
+
`)}catch{}}function ie(){try{g.unlinkSync(tn())}catch{}}function an(){let e=ae();if(!g.existsSync(e))return null;try{return JSON.parse(g.readFileSync(e,"utf-8"))}catch{return null}}function Hr(){let e=tn();try{if(g.mkdirSync(w.dirname(e),{recursive:!0}),!Gr(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){ie();return}let n=(0,Qt.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",ie),n.unref()}catch{ie()}}function tt(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Pe(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Vr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${N(r||"",A.green)}${N(s||"",A.dim)}`}function nt(e){return`$${e.toFixed(2)}`}function Fr(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Pe(n.toUpperCase()),o=Pe(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Br(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var rt=Br(),A={reset:"\x1B[0m",visaBlue:rt?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:rt?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:rt?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function N(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${A.reset}`}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cn(){let e=Re.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function Kr(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function qr(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Gr(e){for(let t=0;t<2;t+=1){let n;try{return n=g.openSync(e,"wx"),g.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=g.statSync(e);if(Date.now()-s.mtimeMs<=Dr)return!1;g.unlinkSync(e)}catch{}}finally{n!==void 0&&g.closeSync(n)}}return!1}function ln(e){return e instanceof Error?e.message:"unknown file system error"}function Ee(e,t){g.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;g.writeFileSync(n,t),g.renameSync(n,e)}var R=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},un=["GET","POST"];function dn(e){let t;try{t=new URL(e)}catch{throw new R(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new R(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function pn(e){let t=(e??"GET").toUpperCase();if(!un.includes(t))throw new R(`Unsupported HTTP method "${e}". Supported: ${un.join(", ")}.`);return t}function fn(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new R(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function mn(e){if(!e||typeof e!="object")throw new R("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new R("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new R("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new R(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new R("Merchant returned an empty currency.");if(t.currency.length>10)throw new R(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var S=m(require("fs")),f=m(require("path")),gn=m(require("os")),_=gn.homedir(),Wr=["Claude_","Anthropic.ClaudeDesktop_"];function hn(){return process.env.APPDATA||f.join(_,"AppData","Roaming")}function zr(){return process.env.LOCALAPPDATA||f.join(_,"AppData","Local")}function yn(){if(process.platform!=="win32")return;let e=f.join(zr(),"Packages");if(S.existsSync(e))try{let t=S.readdirSync(e,"utf-8");for(let n of Wr){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return f.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Sn(){if(process.platform==="win32"){let e=yn();return e?f.join(e,"claude_desktop_config.json"):f.join(hn(),"Claude","claude_desktop_config.json")}return f.join(_,"Library","Application Support","Claude","claude_desktop_config.json")}function bn(){if(process.platform!=="win32")return[f.join(_,"Library","Application Support","Claude")];let e=[f.join(hn(),"Claude")],t=yn();return t&&e.push(t),e}function Ne(e){return e.id==="claude-desktop"?Sn():e.globalConfigPath}function Jr(e){return e.id==="claude-desktop"?bn():e.detectPaths}var M=[{id:"claude",displayName:"Claude Code",globalConfigPath:f.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[f.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Sn(),configKey:"mcpServers",detectPaths:bn(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:f.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[f.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:f.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[f.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:f.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[f.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:f.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[f.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:f.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[f.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:f.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[f.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})}];function ct(e){return M.find(t=>t.id===e)}function ce(e){return Jr(e).some(t=>{if(t.includes("*")){let n=f.dirname(t),r=f.basename(t).replaceAll("*","");if(!S.existsSync(n))return!1;try{return S.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return S.existsSync(t)})}function vn(){return{command:"node",args:[f.resolve(__dirname,"mcp-server/index.js")]}}function le(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):Ne(e),r=f.dirname(n);S.existsSync(r)||S.mkdirSync(r,{recursive:!0});let s={};if(S.existsSync(n))try{s=JSON.parse(S.readFileSync(n,"utf-8"))}catch{s={}}s[e.configKey]=s[e.configKey]||{};let o=vn();return s[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,S.writeFileSync(n,JSON.stringify(s,null,2)+`
|
|
83
|
+
`),{installed:!0,configPath:n,message:e.postInstallHint}}function lt(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):Ne(e);if(!S.existsSync(n))return{removed:!1,configPath:n};let r;try{r=JSON.parse(S.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=r[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],S.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
84
|
+
`),{removed:!0,configPath:n})}function wn(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):Ne(e);if(!S.existsSync(n))return!1;try{return!!JSON.parse(S.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Yr(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function Xr(e,t){if(e===t)return!0;let n=f.resolve(e),r=f.resolve(t);if(n===r)return!0;try{let s=S.realpathSync(n),o=S.realpathSync(r);return s===o}catch{return!1}}function ue(){let e=vn(),t=e.args[e.args.length-1],n=[];for(let r of M){let s=Ne(r);if(!S.existsSync(s))continue;let o;try{o=JSON.parse(S.readFileSync(s,"utf-8"))}catch{continue}let i=o?.[r.configKey]?.["visa-cli"];if(!i)continue;let a=Yr(i);if(!a||Xr(a,t))continue;let c=S.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function ut(e){return{configPath:le(e.client,"global").configPath}}var Zr=(0,kn.promisify)(xn.execFile);function Qr(e,t){return process.stdin.isTTY?new Promise(n=>{let r=Cn.createInterface({input:process.stdin,output:process.stdout});r.question(e,s=>{r.close();let o=s.trim().toLowerCase();if(o===""){n(t);return}n(o==="y"||o==="yes")})}):Promise.resolve(t)}function es(e){let t=I.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
|
|
85
|
+
${r}: ${n(e.currentPath)}`}function Pn(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(es(n))}var T=new _n.Command,Ie=null,de=!1;function Z(){return Ie=new ee(()=>$.getSessionToken()),Ie}T.name("visa-cli").description("Visa CLI - AI payment orchestration").version(Be().version);T.hook("preAction",async()=>{await gt()});T.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept all prompts (enable HUD etc) without asking \u2014 for CI/agent use").option("--no-hud","Skip the HUD install prompt (default: ask)").action(async e=>{try{if(e.check){let l=ue();Pn(l,"MCP config check:"),l.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=ue(),n=new Map(t.map(l=>[l.client.id,l])),r=new Set;for(let l of M)if(ce(l)){let h=le(l),v=n.get(l.id),x=v?` \u2014 repaired stale ${v.staleReason} entry`:"";console.log(` \u2713 ${l.displayName} (${h.configPath.replace(I.homedir(),"~")})${x}`),v&&r.add(l.id)}let s=t.filter(l=>!r.has(l.client.id));for(let l of s)ut(l),console.log(` \u2713 ${l.client.displayName} (${l.configPath.replace(I.homedir(),"~")}) \u2014 repaired stale ${l.staleReason} entry`);let o=r.size+s.length;console.log(o===0?" \u2713 MCP config verified \u2014 nothing to repair.":` \u2713 Repaired ${o} stale MCP config ${o===1?"entry":"entries"}.`),console.log(`
|
|
86
|
+
Step 2: Checking authentication...`);let i=await $.getSessionToken();if(i)try{await new ee(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(l){let h=l instanceof Error?l.message:"";h.includes("session has expired")||h.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await $.clearAll(),i=null):console.log(` Couldn't verify session (${h||"unknown error"}) \u2014 continuing with existing token.`)}if(i||(console.log(" No session found. Opening browser for GitHub login..."),i=await new Promise(async(l,h)=>{let v=Me.randomBytes(16).toString("hex"),x=`https://auth.visacli.sh/login?state=${v}`;await yt(x);let j=3e4,U=300*1e3,V=Date.now()+U;for(;Date.now()<V;)try{let F=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:v,timeout:j}),signal:AbortSignal.timeout(j+5e3)});if(!F.ok)continue;let k=await F.json();if(k.status==="pending")continue;if(k.status==="expired"){h(new Error("Session expired. Please run setup again."));return}if(k.status==="complete"&&k.sessionToken){console.log(` Signed in as ${k.user}.`),l(k.sessionToken);return}}catch{}h(new Error("Login timed out after 5 minutes. Please run setup again."))}),await $.saveSessionToken(i),console.log(" Session token saved.")),console.log(`
|
|
87
|
+
Step 3: Setting up authentication...`),!se())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Zr("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}try{let l=await Gt();console.log(" Attestation key generated."),await Z().registerAttestationKey(l),console.log(" Attestation key registered with server.")}catch(l){console.log(` Skipped: ${l.message}`)}}let a=pe.join(I.homedir(),".claude","settings.json"),c=$n.existsSync(pe.join(I.homedir(),".claude.json")),p=e.hud===!1;if(c&&!p){console.log(`
|
|
88
|
+
Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info below the Claude Code input, so"),console.log(" you can see your spend, card, and session usage in real time.");let l;if(e.yes?(l=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?l=await Qr(" Enable Visa HUD? [Y/n] ",!0):(l=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),l){let h=qe(a),v=h.installed==="new"||h.installed==="already-visa"||h.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${v}${h.message}`);try{let x=Z(),j=await x.getStatus(),U={currentVersion:x.getClientVersion(),latestVersion:x.lastSignals?.updateAvailable?.version,updateMessage:x.lastSignals?.updateAvailable?.message,updateCheckDisabled:W()},V=ot(j,U);at(V),console.log(` Preview: ${V.split(`
|
|
89
89
|
`)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let u="\x1B[1m",d="\x1B[0m";console.log(`
|
|
90
90
|
\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
91
91
|
\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
|
|
@@ -104,20 +104,20 @@ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info
|
|
|
104
104
|
${u}Verify:${d} visa-cli status
|
|
105
105
|
${u}HUD:${d} Restart Claude Code to see your spend pinned below the input
|
|
106
106
|
${u}Docs:${d} https://visacli.sh
|
|
107
|
-
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});
|
|
107
|
+
`)}catch(t){console.error("Error:",t.message),process.exit(1)}});T.command("install [client]").description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=ue();Pn(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=ue();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)ut(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(I.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
|
|
108
108
|
Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
|
|
109
109
|
\x1B[1mSupported MCP Clients\x1B[0m
|
|
110
|
-
`),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of M){let c=
|
|
111
|
-
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let
|
|
112
|
-
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let
|
|
113
|
-
`);let i;if(se())try{let{nonce:c}=await
|
|
114
|
-
Result URLs:`);for(let c of a.receipt.urls)console.log(` ${c}`)}}else console.error(`Payment failed: ${a.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof
|
|
115
|
-
`)}return{transactions:[]}});process.stdout.write(
|
|
116
|
-
`);try{await
|
|
117
|
-
Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});
|
|
118
|
-
`)});
|
|
119
|
-
`);let
|
|
110
|
+
`),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of M){let c=ce(a),p=wn(a),u=c?"Yes":"No",d=p?"Yes":"No",l=a.globalConfigPath.replace(I.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${l}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of M){if(!ce(a)){i.push(a.displayName);continue}le(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
|
|
111
|
+
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ct(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!ce(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=le(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});T.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of M)lt(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
|
|
112
|
+
Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ct(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let s=lt(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});T.command("pay <url>").description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{dn(e);let n=pn(t.method),r=fn(t.body),s=new ee(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=mn(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
|
|
113
|
+
`);let i;if(se())try{let{nonce:c}=await s.getAttestationChallenge(),p=Buffer.from(JSON.stringify({nonce:c,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");i={signature:await Wt(p,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:c,amount:o.amount,merchant:o.merchantName}}catch(c){console.error(`Touch ID confirmation failed: ${c?.message||"user cancelled or biometric error"}`),process.exit(1)}else console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let a=await s.pay({url:e,method:n,body:r,attestation:i,idempotencyKey:Me.randomUUID()});if(a.success){if(console.log(`Payment complete: $${(a.amount??o.amount).toFixed(2)} \u2192 ${a.merchantName??o.merchantName}`),a.receipt?.urls?.length){console.log(`
|
|
114
|
+
Result URLs:`);for(let c of a.receipt.urls)console.log(` ${c}`)}}else console.error(`Payment failed: ${a.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof R?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});T.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{de=!1;try{let e=Z(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:W()},r=await e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
|
|
115
|
+
`)}return{transactions:[]}});process.stdout.write(Xt(t,Array.isArray(r?.transactions)?r.transactions:[],se(),n)),de=!0}catch(e){de=!1,console.error("Error:",e.message),process.exit(1)}});T.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
|
|
116
|
+
`);try{await Z().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await $.clearAll(),console.log(" Keychain credentials cleared."),se())try{await zt(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
|
|
117
|
+
Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});T.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(async e=>{(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await Z().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var Q=T.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function En(){let e=rn();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Rn(){let e=sn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Q.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(En);Q.command("enable").description("Enable the persistent shell HUD").action(En);Q.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Rn);Q.command("disable").description("Disable the persistent shell HUD").action(Rn);Q.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${it()}
|
|
118
|
+
`)});Q.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,l,h)=>{console.log(` ${l?"\u2713":"\u2717"} ${d}: ${h}`),l||(n=!1)};console.log(`Shell HUD Doctor
|
|
119
|
+
`);let s=Ae();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Le(s),l=e(d);if(r("RC file exists",l,d.replace(I.homedir(),"~")),l){let v=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",v,v?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let o=ae(),i=e(o);if(r("Cache file",i,i?o.replace(I.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),l=Date.now()-(d.renderedAt??0),h=Math.round(l/1e3),v=h<=30;console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${h}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Te(),c=e(a),p="missing";if(c)try{p=t(a,"utf-8").trim().slice(0,80)}catch{p="unreadable"}r("Line file",c,p);let u=!1;try{u=!!await $.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await Z().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let l=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,l)}console.log(n?`
|
|
120
120
|
All checks passed.`:`
|
|
121
|
-
Some checks failed \u2014 see above.`),n||process.exit(1)});
|
|
122
|
-
`)[0],
|
|
123
|
-
`)});var
|
|
121
|
+
Some checks failed \u2014 see above.`),n||process.exit(1)});Q.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(async e=>{if(!(!e.force&&on()))try{let t=Z(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:W()},s=ot(n,r);at(s)}catch{}finally{ie()}});T.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await Et(),n=it().split(`
|
|
122
|
+
`)[0],r=await Tt(n,e);process.stdout.write(`${r}
|
|
123
|
+
`)});var Tn=T.command("hud").description("Manage the Visa HUD pinned below Claude Code input");Tn.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=pe.join(I.homedir(),".claude","settings.json"),t=qe(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Tn.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=pe.join(I.homedir(),".claude","settings.json"),t=$t(e);console.log(t.message),t.removed||process.exit(1)});T.hook("postAction",()=>{if(de){de=!1;return}Ie&&Jt(Ie.lastSignals)});T.parse();
|
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var _n=Object.create;var Lt=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(r,e)=>()=>(r&&(e=r(r=0)),e);var kn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ur=(r,e)=>{for(var t in e)Lt(r,t,{get:e[t],enumerable:!0})},Tn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wn(e))!xn.call(r,s)&&s!==t&&Lt(r,s,{get:()=>e[s],enumerable:!(n=vn(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?_n(bn(r)):{},Tn(e||!r||!r.__esModule?Lt(t,"default",{value:r,enumerable:!0}):t,r));var lr={};ur(lr,{fetchWithTimeout:()=>jt});async function jt(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Mt=Sn(()=>{"use strict"});var on=kn((To,ci)=>{ci.exports={name:"@visa/cli",version:"1.
|
|
2
|
+
"use strict";var _n=Object.create;var Lt=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Sn=(r,e)=>()=>(r&&(e=r(r=0)),e);var kn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ur=(r,e)=>{for(var t in e)Lt(r,t,{get:e[t],enumerable:!0})},Tn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wn(e))!xn.call(r,s)&&s!==t&&Lt(r,s,{get:()=>e[s],enumerable:!(n=vn(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?_n(bn(r)):{},Tn(e||!r||!r.__esModule?Lt(t,"default",{value:r,enumerable:!0}):t,r));var lr={};ur(lr,{fetchWithTimeout:()=>jt});async function jt(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Mt=Sn(()=>{"use strict"});var on=kn((To,ci)=>{ci.exports={name:"@visa/cli",version:"1.4.0-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","README.md","LICENSE"]}});var mn=require("@modelcontextprotocol/sdk/server/index.js"),pn=require("@modelcontextprotocol/sdk/server/stdio.js"),te=require("@modelcontextprotocol/sdk/types.js");Mt();var In=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function dt(r,e){let t=dr(r),n=dr(e);if(!t||!n)return!1;for(let s=0;s<3;s++)if(t.main[s]!==n.main[s])return t.main[s]>n.main[s];return t.pre&&!n.pre?!1:!t.pre&&n.pre?!0:!t.pre&&!n.pre?!1:Rn(t.pre,n.pre)>0}function dr(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(In);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function Rn(r,e){let t=r.split("."),n=e.split("."),s=Math.max(t.length,n.length);for(let a=0;a<s;a++){if(a>=t.length)return-1;if(a>=n.length)return 1;let i=t[a],o=n[a],c=/^\d+$/.test(i),l=/^\d+$/.test(o);if(c&&l){let u=Number(i)-Number(o);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function mt(){return!!(mr(process.env.VISA_CLI_NO_UPDATE_CHECK)||mr(process.env.CI)||process.env.NODE_ENV==="test")}function mr(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var Ut="1.4.0-rc.0",pt=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!mt()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&dt(n,Ut)&&(this.lastSignals.updateAvailable={version:n,message:s||`Update available: v${n}. Run: npm install -g @visa/cli && visa-cli setup`})}let t=e.headers.get("X-Feedback-Prompt");if(t)try{this.lastSignals.feedbackPrompt=JSON.parse(t)}catch{}}getClientVersion(){return Ut}async request(e,t,n,s,a){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let o={Authorization:`Bearer ${i}`};a&&(e==="GET"?o["X-User-Context"]=a.replace(/[\r\n\0]/g," ").slice(0,1e3):n={...n||{},user_context:a}),n&&(o["Content-Type"]="application/json");let c;try{c=await jt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":Ut},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${t}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(e,t){return this.request("POST","/v1/pay",e,void 0,t)}async shortcut(e,t,n,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,t,n,s)}async batch(e,t,n){return this.request("POST","/v1/batch",e,t,n)}async catalogSearch(e,t){let n=new URLSearchParams;e&&n.set("q",e),t&&n.set("category",t);let s=n.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,t){return this.request("POST","/v1/payment-preview",e,void 0,t)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,t){return this.request("POST","/v1/spending-controls",e,void 0,t)}async removeCard(e,t,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,t,void 0,n)}async setDefaultCard(e,t,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,t,void 0,n)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,t){return this.request("POST","/v1/logout",e,void 0,t)}async feedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let t=new URLSearchParams;e?.tab&&t.set("tab",e.tab),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let n=t.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(e,t){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:t})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async getFeedback(e,t){let n=new URLSearchParams;e&&n.set("limit",String(e));let s=n.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,t)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var Ft=require("child_process"),_r=require("util"),vr=I(require("crypto")),P=I(require("fs")),wr=I(require("os")),G=I(require("path"));var M=I(require("fs")),Vt=I(require("path")),pr=I(require("os")),Dt=Vt.join(pr.homedir(),".visa-mcp"),Ye=Vt.join(Dt,"mcp-server.log"),En=5*1024*1024,qt=null;function An(){M.existsSync(Dt)||M.mkdirSync(Dt,{recursive:!0,mode:448})}function On(){if(!qt){if(An(),M.existsSync(Ye)&&M.statSync(Ye).size>En){let e=Ye+".1";M.existsSync(e)&&M.unlinkSync(e),M.renameSync(Ye,e)}qt=M.createWriteStream(Ye,{flags:"a"})}return qt}function ft(r,...e){let t=new Date().toISOString(),n=e.map(a=>typeof a=="string"?a:JSON.stringify(a,null,2)).join(" "),s=`[${t}] [${r}] ${n}
|
|
3
3
|
`;process.stderr.write(s),On().write(s)}var m={debug:(...r)=>ft("DEBUG",...r),info:(...r)=>ft("INFO",...r),warn:(...r)=>ft("WARN",...r),error:(...r)=>ft("ERROR",...r)};var ht=(0,_r.promisify)(Ft.execFile),gt=G.join(wr.homedir(),".visa-mcp","bin"),ye=G.join(gt,"Visa CLI"),Cn=G.join(__dirname,"..","native"),fr="5",hr=G.join(gt,"visa-keychain.version"),gr=G.join(gt,"visa-keychain.sha256");function yr(r){let e=P.readFileSync(r);return vr.createHash("sha256").update(e).digest("hex")}async function br(){try{if(P.readFileSync(hr,"utf-8").trim()===fr&&P.existsSync(ye)){let n=P.readFileSync(gr,"utf-8").trim();if(yr(ye)!==n)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),P.unlinkSync(ye);else return ye}}catch{}let r=G.join(Cn,"visa-keychain.m");if(P.existsSync(r)||(r=G.resolve(__dirname,"..","..","native","visa-keychain.m")),P.existsSync(r)||(r=G.resolve(__dirname,"..","native","visa-keychain.m")),!P.existsSync(r))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");P.mkdirSync(gt,{recursive:!0,mode:448});try{await ht("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",ye,r],{timeout:3e4})}catch(t){throw t.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):t}let e=yr(ye);return P.writeFileSync(gr,e,{mode:384}),P.writeFileSync(hr,fr,{mode:384}),ye}async function Nn(r){let e=await br(),t;try{t=(await ht(e,r,{timeout:6e4})).stdout}catch(a){t=a.stdout||"";let i=t.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(a.stderr?.trim()||a.message||"Unknown error")}let n=t.trim();if(n.startsWith("OK:"))return n.slice(3);if(n==="OK")return;let s=n.startsWith("ERROR:")?n.slice(6):"Unknown error";throw new Error(s)}var Ht=null;function Bt(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ht!==null?Ht:(Ht=!0,!0)}var xr="visa-cli",Sr="attestation-key";async function Pn(){try{let{stdout:r}=await ht("security",["find-generic-password","-s",xr,"-a",Sr,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function kr(r,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let t=await Pn();if(!t)throw new Error("Attestation key not found. Run setup to generate a new key.");let n=await br(),s=["sign",r];return e&&s.push(e),new Promise((a,i)=>{let o=(0,Ft.execFile)(n,s,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?a(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});o.stdin.write(t),o.stdin.end()})}async function Tr(){try{await ht("security",["delete-generic-password","-s",xr,"-a",Sr],{timeout:5e3})}catch{}try{await Nn(["delete-key"])}catch{}}var vt=require("child_process"),Ir=require("util"),ue=I(require("fs")),wt=I(require("os")),Gt=I(require("path")),K=(0,Ir.promisify)(vt.execFile),Kt=Gt.join(wt.homedir(),".visa-mcp"),yt=Gt.join(Kt,"session-token"),H="visa-cli",ce="session-token",_t="rc-access",Ln=5e3;async function jn(){try{let{stdout:r}=await K("security",["find-generic-password","-s",H,"-a",ce,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Mn(r){try{try{await K("security",["delete-generic-password","-s",H,"-a",ce],{timeout:5e3})}catch{}return await K("security",["add-generic-password","-s",H,"-a",ce,"-w",r],{timeout:5e3}),!0}catch{return!1}}async function Un(){try{await K("security",["delete-generic-password","-s",H,"-a",ce],{timeout:5e3})}catch{}}async function qn(){if(!Yt())return null;try{let{stdout:r}=await K("secret-tool",["lookup","service",H,"account",ce],{timeout:5e3});return r.trim()||null}catch{return null}}async function Dn(r){if(!Yt())return!1;try{let e=(0,vt.execFile)("secret-tool",["store","--label",`${H} ${ce}`,"service",H,"account",ce]);return e.stdin?(e.stdin.write(r),e.stdin.end(),await Promise.race([new Promise((t,n)=>{e.on("exit",s=>s===0?t():n(new Error(`secret-tool exited ${s}`))),e.on("error",n)}),new Promise((t,n)=>setTimeout(()=>{e.kill(),n(new Error("secret-tool timed out"))},Ln))]),!0):!1}catch{return!1}}async function Vn(){if(Yt())try{await K("secret-tool",["clear","service",H,"account",ce],{timeout:5e3})}catch{}}function Yt(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Hn(){try{let{stdout:r}=await K("security",["find-generic-password","-s",H,"-a",_t,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Fn(r){try{try{await K("security",["delete-generic-password","-s",H,"-a",_t],{timeout:5e3})}catch{}await K("security",["add-generic-password","-s",H,"-a",_t,"-w",r],{timeout:5e3})}catch{}}async function Bn(){try{await K("security",["delete-generic-password","-s",H,"-a",_t],{timeout:5e3})}catch{}}function zt(){try{return ue.readFileSync(yt,"utf-8").trim()||null}catch{return null}}function Rr(r){ue.mkdirSync(Kt,{recursive:!0,mode:448}),ue.writeFileSync(yt,r,{mode:384}),process.platform==="win32"&&Wn(yt)}function Zt(){try{ue.unlinkSync(yt)}catch{}}function Wn(r){try{let e=wt.userInfo().username;(0,vt.execFile)("icacls",[r,"/inheritance:r","/grant:r",`${e}:F`],{timeout:5e3},t=>{t&&console.error(`[visa-cli] icacls ACL restriction failed: ${t.message}`)})}catch(e){console.error(`[visa-cli] Failed to invoke icacls: ${e instanceof Error?e.message:String(e)}`)}}function Wt(){switch(process.platform){case"darwin":return{get:jn,store:Mn,delete:Un};case"linux":return{get:qn,store:Dn,delete:Vn};default:return{get:async()=>zt(),store:async r=>{try{return Rr(r),!0}catch{return!1}},delete:async()=>Zt()}}}var L=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=Wt(),t=await e.get();if(t)return t;let n=zt();return n?(await e.store(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let t=Wt();if(await t.store(e)){if(await t.get()===e){Zt();return}await t.delete()}if(Rr(e),zt()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Kt} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Hn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Fn(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Wt().delete(),Zt()}static async clearAll(){await this.deleteSessionToken(),await Bn()}};var bt={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",priceCents:4,notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",priceCents:1,notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",priceCents:6,notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",priceCents:8,notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",priceCents:5,notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",priceCents:15,notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",priceCents:10,notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",priceCents:20,notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",priceCents:10,notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech or sound effects.",tiers:{tts:{toolId:"fal-metavoice",priceCents:3,notes:"MetaVoice \u2014 high-quality TTS from text"},sfx:{toolId:"fal-stable-audio",priceCents:4,notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:'Pick "tts" for spoken words, "sfx" for music-beds/effects/ambient.',inputProperties:{prompt:{type:"string",description:"Text to speak (tts) or description of sound (sfx)."}},required:["prompt"]},generate_3d:{intro:"Generate a 3D model from a text description.",tiers:{trellis:{toolId:"fal-trellis-3d",priceCents:8,notes:"Trellis \u2014 fast text-to-3D, returns a GLB mesh URL"}},guidance:"Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{prompt:{type:"string",description:"Description of the 3D object."}},required:["prompt"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",priceCents:3,notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",priceCents:2,notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered \u2014 prices below are per 1M input/output tokens. Typical 500-in/500-out prompts cost 1\u20139\xA2 depending on model.",tiers:{fast:{toolId:"or-gpt-4o-mini",priceCents:1,notes:"GPT-4o Mini \u2014 $0.15/M in \xB7 $0.60/M out. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",priceCents:9,notes:"Claude 3.5 Sonnet \u2014 $3.00/M in \xB7 $15.00/M out. Strong reasoning, long-context. ~20x pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",priceCents:2,notes:"DeepSeek R1 \u2014 $0.55/M in \xB7 $2.19/M out. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",priceCents:1,notes:"Perplexity Sonar \u2014 $1.00/M in \xB7 $1.00/M out. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",priceCents:1,notes:"Llama 3.3 70B \u2014 $0.30/M in \xB7 $0.40/M out. Open-source large model."},coding:{toolId:"or-deepseek-chat",priceCents:1,notes:"DeepSeek Chat V3 \u2014 $0.30/M in \xB7 $0.88/M out. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis \u2014 WARN user it's ~$0.09/call), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Je(){return process.env.VISA_SPECIFIC_TOOLS!=="false"}function Xe(){return process.env.VISA_META_TOOLS!=="false"}function Qe(){return process.env.VISA_DISCOVER_TOOLS!=="false"}function Er(r){let e=bt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=[e.intro,"","Tiers:"];for(let[n,s]of Object.entries(e.tiers)){let a=`$${(s.priceCents/100).toFixed(2)}`;t.push(` - ${n.padEnd(15)} ${a.padStart(6)} ${s.notes}`)}return t.push("",e.guidance),t.join(`
|
|
4
4
|
`)}function Ar(r){let e=bt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=Object.keys(e.tiers);return{type:"object",properties:{tier:{type:"string",enum:t,default:t[0],description:`Quality/style tier. Default: ${t[0]}.`},...e.inputProperties},required:e.required??[]}}function xt(r,e){if(!_e.includes(r))return r;let t=bt[r];if(!t)return r;let n=Object.keys(t.tiers),s=e||n[0],a=t.tiers[s];if(!a)throw new Error(`Unknown tier '${s}' for ${r}. Valid tiers: ${n.join(", ")}`);return a.toolId}async function Or(r,e,t){let n=xt(r,e.tier),{tier:s,...a}=e;return O.executeTool({tool_id:n,...a},t)}var _e=Object.keys(bt);function Cr(r=process.env,e=process.platform){return r.VISA_CLI_NO_BROWSER==="1"||r.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:r.CI==="true"||r.CI==="1"?{headless:!0,reason:"CI environment detected"}:r.SSH_CONNECTION||r.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!r.DISPLAY&&!r.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function Nr(r,e=process.platform){return e==="darwin"?{cmd:"open",args:[r]}:e==="win32"?{cmd:"cmd",args:["/c","start","",r]}:e==="linux"?{cmd:"xdg-open",args:[r]}:null}var tt=I(require("crypto")),Lr=require("child_process"),V=I(require("fs")),rt=I(require("os")),nt=I(require("path"));var zn="# visa-cli-hud-v1";function St(r){return typeof r!="string"?!1:r.includes(zn)?!0:r.includes("visa-cli")&&r.includes("statusline")}var kt=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",S=new pt(()=>L.getSessionToken()),Zn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Pr=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my recent transactions" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Pay https://example.com/checkout" \u2192 pay','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Fast shortcuts:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image_card (~$0.06)','\u2022 "Make a fast thumbnail: minimalist cat logo" \u2192 generate_image_fast_card (~$0.04)','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video_tempo_card (~$0.30)','\u2022 "Make a song about coding late at night" \u2192 generate_music_tempo_card (~$0.10)','\u2022 "Check the status of my music job" \u2192 check_music_status_tempo_card','\u2022 "What is ETH on Base trading at?" \u2192 query_onchain_prices_card (~$0.02)','\u2022 "Explore stablecoin inflows on Base" \u2192 allium_explorer_card','\u2022 "Open the latest Allium result set" \u2192 allium_explorer_results_card','\u2022 "Show pxlwall campaign insights" \u2192 pxlwall_card',"","Category tools:",...Zn.map(r=>`\u2022 "${r.replace(/_/g," ")}" \u2192 ${r}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
5
5
|
`);function D(r){if(!r||typeof r!="string"||process.env.VISA_SUPPRESS_BROWSER==="true")return;let e;try{e=new URL(r)}catch{return}if(e.protocol!=="https:"&&e.protocol!=="http:")return;let t=e.toString(),n=Cr();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let s=Nr(t);if(!s){m.info(`No browser command for platform "${rt.platform()}". URL: ${t}`);return}(0,Lr.execFile)(s.cmd,s.args,a=>{a&&m.warn(`Browser open failed: ${a.message}. URL: ${t}`)})}async function C(r,e,t,n){if(!Bt()){m.warn("attestation:unavailable",{context:r});return}m.info("attestation:attempt",{context:r,amount:e,merchant:t});try{let{nonce:s}=await S.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:s,amount:e,merchant:t,context:r})).toString("base64");m.info("touchid:prompt",{context:r,amount:e,merchant:t});let i=await kr(a,n);return m.info("attestation:success",{context:r,amount:e,merchant:t}),{signature:i,nonce:s,amount:e,merchant:t}}catch(s){throw m.error("attestation:failure",{context:r,amount:e,merchant:t,error:s.message}),s}}async function z(r,e,t){let n=await S.paymentPreview({tool:r,url:e},t);if(!n||!n.merchantName||!n.amount||n.amount<=0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(n.amount)||n.amount<0||n.amount>999999)throw new Error(`Invalid payment amount: ${n.amount}. Payment rejected for safety.`);return n}function Y(r){if(r.pricingMode==="max-cap"){let e=typeof r.estimatedAmount=="number"&&r.estimatedAmount>0?` (estimated $${r.estimatedAmount.toFixed(2)})`:"";return`pay up to $${r.amount.toFixed(2)} to ${r.merchantName}${e}`}return`pay $${r.amount.toFixed(2)} to ${r.merchantName}`}function jr(){return nt.join(rt.homedir(),".visa-mcp","allium-results")}var Gn=16*1024,Kn=50*1024*1024,Yn=10;function Jn(r){return r.replace(/[^A-Za-z0-9_\-]/g,"_").slice(0,128)}function Xn(r,e){let t=jr();V.mkdirSync(t,{recursive:!0});let n=Jn(r),s=nt.join(t,`${n}.csv`);V.writeFileSync(s,e);let a=Buffer.byteLength(e),i=e.split(`
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
${n}
|
|
15
15
|
|
|
16
16
|
Use execute_tool with the tool id and required params to run any of these.`}],_tools:t}}catch(e){throw m.error("catalog:discover:error",{error:e.message}),new Error(`Failed to search tool catalog: ${e.message}`)}}async function Ns(r,e){let{tool_id:t,params:n,...s}=r,a=n||s;if(!t)throw new Error("tool_id is required. Use discover_tools first to find available tools.");m.info("catalog:execute",{tool:t});let i=await z(t,void 0,e);m.info("payment:attempt",{tool:t,amount:i.amount,merchant:i.merchantName});try{let o=await C(t,i.amount,i.merchantName,Y(i)),c=await S.shortcut(t,{...a,attestation:o},12e4,e);if(m.info("payment:success",{tool:t,amount:i.amount,merchant:i.merchantName}),c.urls?.length){c.urls.forEach(u=>D(u));let l=c.mediaType||(c.urls[0]?.match(/\.(mp4|webm|mov)/)?"video":"image");st({prompt:a.prompt||`${t} execution`,tool:t,mediaUrl:c.urls[0],mediaType:l,cost:c.amount??i.amount,transactionId:c.transactionId,userContext:e})}return c}catch(o){throw m.error("payment:failure",{tool:t,amount:i.amount,merchant:i.merchantName,error:o.message}),o}}var O=class{static async getStatus(e){return vs(e)}static async pay(e,t){return es(e,t)}static async getCards(e){return ws(e)}static async transactionHistory(e){return bs(e)}static async feedback(e,t){return xs(e,t)}static async updateSpendingControls(e,t){return Ss(e,t)}static async reset(e,t){return As(e,t)}static async login(e){return Rs(e)}static async addCard(e){return Es(e)}static async removeCard(e,t){return Ts(e,t)}static async setDefaultCard(e,t){return Is(e,t)}static async batch(e,t){return ys(e,t)}static async discoverTools(e){return Cs(e)}static async executeTool(e,t){return Ns(e,t)}static async shortcut(e,t,n){switch(e){case"generate_image_card":return ts(t,n);case"generate_image_fast_card":return rs(t,n);case"generate_video_tempo_card":return ns(t,n);case"generate_music_tempo_card":return ss(t,n);case"check_music_status_tempo_card":return as(t,n);case"query_onchain_prices_card":return is(t,n);case"allium_explorer_card":return os(t,n);case"allium_explorer_results_card":return cs(t,n);case"pxlwall_card":return ls(t,n);default:{m.info("payment:attempt",{tool:e});try{let s=await C(e,0,""),a=await S.shortcut(e,{...t,attestation:s},void 0,n);return m.info("payment:success",{tool:e}),a.urls?.length&&a.urls.forEach(i=>D(i)),a}catch(s){throw m.error("payment:failure",{tool:e,error:s.message}),s}}}}static async submitFeedback(e,t,n){m.info("feedback:submit",{length:e.length});try{let s=await S.submitFeedback(e,t,n);return m.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw m.error("feedback:error",{error:a}),s}}static async getFeedback(e,t){m.info("feedback:list",{limit:e||20});try{let n=await S.getFeedback(e,t);return m.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let s=n instanceof Error?n.message:"Unknown error";throw m.error("feedback:error",{error:s}),n}}};var Jt=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card","pxlwall_card"]),Xt=new Set(["discover_tools","execute_tool"]),Ps=new Set(_e);function Ur(r){return Jt.has(r)&&!Je()?"VISA_SPECIFIC_TOOLS":Xt.has(r)&&!Qe()?"VISA_DISCOVER_TOOLS":Ps.has(r)&&!Xe()?"VISA_META_TOOLS":null}var Tt=I(require("fs")),qr=I(require("path")),Dr=I(require("os"));var Qt=qr.join(Dr.homedir(),".visa-mcp"),le=class{static ensureConfigDir(){Tt.existsSync(Qt)||Tt.mkdirSync(Qt,{recursive:!0,mode:448})}static getConfigDir(){return Qt}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let e=new Set;for(let[t,n]of Object.entries(this.TOOL_STATES))n||e.add(t);return e}static isToolDisabled(e){return this.TOOL_STATES[e]===!1}};var er=["pay","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card"],$s={generate_image_card:"image generation",generate_image_fast_card:"fast image generation",generate_music_tempo_card:"music generation",generate_video_tempo_card:"video generation",query_onchain_prices_card:"onchain price queries",allium_explorer_card:"blockchain data exploration",allium_explorer_results_card:"blockchain data results",pay:"payments"};function Ls(r){return $s[r]||r}var ve=null;async function It(r){if(ve!==null)return ve;try{let{transactions:e}=await r.getTransactions();ve={};for(let t of e)t.status==="completed"&&(ve[t.tool_name]=(ve[t.tool_name]||0)+1)}catch{m.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),ve={}}return ve}function Vr(r,e,t){return er.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${Ls(r)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:t}}:e%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:t}}:{}:{}}var at=I(require("fs")),Hr=I(require("path"));var js=5,Ms={shownCodes:[]},we=null;function Fr(){return process.env.VISA_CLI_REFERRAL_NUDGE_FILE||Hr.join(le.getConfigDir(),"referral-nudges.json")}function Us(){if(we)return we;try{let r=at.readFileSync(Fr(),"utf8"),e=JSON.parse(r);return we={shownCodes:Array.isArray(e.shownCodes)?e.shownCodes.filter(t=>typeof t=="string"):[]},we}catch{return we={...Ms},we}}function qs(r){we=r;try{le.ensureConfigDir(),at.writeFileSync(Fr(),JSON.stringify(r,null,2)+`
|
|
17
|
-
`,{mode:384})}catch{}}function Ds(r){return r.trim().toLowerCase()}function Br(r,e){if(e<js)return{};if(!r.referralCode||!r.referralLink)return{};let t=Ds(r.referralCode);if(!t)return{};let n=Us();return n.shownCodes.includes(t)?{}:(qs({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var k={};ur(k,{BRAND:()=>ma,DIRTY:()=>be,EMPTY_PATH:()=>Bs,INVALID:()=>g,NEVER:()=>Ya,OK:()=>$,ParseStatus:()=>N,Schema:()=>b,ZodAny:()=>pe,ZodArray:()=>ie,ZodBigInt:()=>Se,ZodBoolean:()=>ke,ZodBranded:()=>ot,ZodCatch:()=>Le,ZodDate:()=>Te,ZodDefault:()=>$e,ZodDiscriminatedUnion:()=>At,ZodEffects:()=>W,ZodEnum:()=>Ne,ZodError:()=>U,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Ct,ZodIntersection:()=>Ae,ZodIssueCode:()=>d,ZodLazy:()=>Oe,ZodLiteral:()=>Ce,ZodMap:()=>Be,ZodNaN:()=>ze,ZodNativeEnum:()=>Pe,ZodNever:()=>Z,ZodNull:()=>Re,ZodNullable:()=>Q,ZodNumber:()=>xe,ZodObject:()=>q,ZodOptional:()=>F,ZodParsedType:()=>f,ZodPipeline:()=>ct,ZodPromise:()=>fe,ZodReadonly:()=>je,ZodRecord:()=>Ot,ZodSchema:()=>b,ZodSet:()=>We,ZodString:()=>me,ZodSymbol:()=>He,ZodTransformer:()=>W,ZodTuple:()=>X,ZodType:()=>b,ZodUndefined:()=>Ie,ZodUnion:()=>Ee,ZodUnknown:()=>ae,ZodVoid:()=>Fe,addIssueToContext:()=>p,any:()=>ba,array:()=>Ta,bigint:()=>ga,boolean:()=>tn,coerce:()=>Ka,custom:()=>Xr,date:()=>ya,datetimeRegex:()=>Yr,defaultErrorMap:()=>ne,discriminatedUnion:()=>Aa,effect:()=>Va,enum:()=>Ua,function:()=>La,getErrorMap:()=>qe,getParsedType:()=>J,instanceof:()=>fa,intersection:()=>Oa,isAborted:()=>Rt,isAsync:()=>De,isDirty:()=>Et,isValid:()=>de,late:()=>pa,lazy:()=>ja,literal:()=>Ma,makeIssue:()=>it,map:()=>Pa,nan:()=>ha,nativeEnum:()=>qa,never:()=>Sa,null:()=>wa,nullable:()=>Fa,number:()=>en,object:()=>Ia,objectUtil:()=>tr,oboolean:()=>Ga,onumber:()=>Za,optional:()=>Ha,ostring:()=>za,pipeline:()=>Wa,preprocess:()=>Ba,promise:()=>Da,quotelessJson:()=>Vs,record:()=>Na,set:()=>$a,setErrorMap:()=>Fs,strictObject:()=>Ra,string:()=>Qr,symbol:()=>_a,transformer:()=>Va,tuple:()=>Ca,undefined:()=>va,union:()=>Ea,unknown:()=>xa,util:()=>x,void:()=>ka});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var tr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(tr||(tr={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var d=x.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"]),Vs=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),U=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};U.create=r=>new U(r);var Hs=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},ne=Hs;var Wr=ne;function Fs(r){Wr=r}function qe(){return Wr}var it=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Bs=[];function p(r,e){let t=qe(),n=it({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ne?void 0:ne].filter(s=>!!s)});r.common.issues.push(n)}var N=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),be=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),Rt=r=>r.status==="aborted",Et=r=>r.status==="dirty",de=r=>r.status==="valid",De=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var B=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},zr=(r,e)=>{if(de(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new U(r.common.issues);return this._error=t,this._error}}};function w(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return J(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(De(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parseSync({data:e,path:n.path,parent:n});return zr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return de(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>de(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(De(s)?s:Promise.resolve(s));return zr(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new W({schema:this,typeName:_.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:t=>this["~validate"](t)}}optional(){return F.create(this,this._def)}nullable(){return Q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ie.create(this)}promise(){return fe.create(this,this._def)}or(e){return Ee.create([this,e],this._def)}and(e){return Ae.create(this,e,this._def)}transform(e){return new W({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new $e({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new ot({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Le({...w(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ct.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ws=/^c[^\s-]{8,}$/i,zs=/^[0-9a-z]+$/,Zs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Gs=/^[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,Ks=/^[a-z0-9_-]{21}$/i,Ys=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Js=/^[-+]?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)?)??$/,Xs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rr,ea=/^(?:(?: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])$/,ta=/^(?:(?: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])$/,ra=/^(([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]))$/,na=/^(([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])$/,sa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gr="((\\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])))",ia=new RegExp(`^${Gr}$`);function Kr(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function oa(r){return new RegExp(`^${Kr(r)}$`)}function Yr(r){let e=`${Gr}T${Kr(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function ca(r,e){return!!((e==="v4"||!e)&&ea.test(r)||(e==="v6"||!e)&&ra.test(r))}function ua(r,e){if(!Ys.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function la(r,e){return!!((e==="v4"||!e)&&ta.test(r)||(e==="v6"||!e)&&na.test(r))}var me=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new N,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Xs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")rr||(rr=new RegExp(Qs,"u")),rr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Gs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Ks.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Ws.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")zs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Zs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:d.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:d.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.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)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?Yr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?ia.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?oa(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?ca(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?ua(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?la(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?sa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?aa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.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,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};me.create=r=>new me({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...w(r)});function da(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var xe=class r extends b{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)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new N;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?da(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};xe.create=r=>new xe({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});var Se=class r extends b{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)!==f.bigint)return this._getInvalidInput(e);let n,s=new N;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Se.create=r=>new Se({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});var ke=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.boolean,received:n.parsedType}),g}return $(e.data)}};ke.create=r=>new ke({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});var Te=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),g}let n=new N,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):x.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Te.create=r=>new Te({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});var He=class extends b{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.symbol,received:n.parsedType}),g}return $(e.data)}};He.create=r=>new He({typeName:_.ZodSymbol,...w(r)});var Ie=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.undefined,received:n.parsedType}),g}return $(e.data)}};Ie.create=r=>new Ie({typeName:_.ZodUndefined,...w(r)});var Re=class extends b{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.null,received:n.parsedType}),g}return $(e.data)}};Re.create=r=>new Re({typeName:_.ZodNull,...w(r)});var pe=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};pe.create=r=>new pe({typeName:_.ZodAny,...w(r)});var ae=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};ae.create=r=>new ae({typeName:_.ZodUnknown,...w(r)});var Z=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};Z.create=r=>new Z({typeName:_.ZodNever,...w(r)});var Fe=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.void,received:n.parsedType}),g}return $(e.data)}};Fe.create=r=>new Fe({typeName:_.ZodVoid,...w(r)});var ie=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new B(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new B(t,i,t.path,o)));return N.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};ie.create=(r,e)=>new ie({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(e)});function Ve(r){if(r instanceof q){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=F.create(Ve(n))}return new q({...r._def,shape:()=>e})}else return r instanceof ie?new ie({...r._def,type:Ve(r.element)}):r instanceof F?F.create(Ve(r.unwrap())):r instanceof Q?Q.create(Ve(r.unwrap())):r instanceof X?X.create(r.items.map(e=>Ve(e))):r}var q=class r extends b{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(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Z&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let u=a[l],y=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new B(s,y,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Z){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let y=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new B(s,y,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let y=await u.key,E=await u.value;l.push({key:y,value:E,alwaysSet:u.alwaysSet})}return l}).then(l=>N.mergeObjectSync(n,l)):N.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof F;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Jr(x.objectKeys(this.shape))}};q.create=(r,e)=>new q({shape:()=>r,unknownKeys:"strip",catchall:Z.create(),typeName:_.ZodObject,...w(e)});q.strictCreate=(r,e)=>new q({shape:()=>r,unknownKeys:"strict",catchall:Z.create(),typeName:_.ZodObject,...w(e)});q.lazycreate=(r,e)=>new q({shape:r,unknownKeys:"strip",catchall:Z.create(),typeName:_.ZodObject,...w(e)});var Ee=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new U(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new U(c));return p(t,{code:d.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};Ee.create=(r,e)=>new Ee({options:r,typeName:_.ZodUnion,...w(e)});var se=r=>r instanceof Oe?se(r.schema):r instanceof W?se(r.innerType()):r instanceof Ce?[r.value]:r instanceof Ne?r.options:r instanceof Pe?x.objectValues(r.enum):r instanceof $e?se(r._def.innerType):r instanceof Ie?[void 0]:r instanceof Re?[null]:r instanceof F?[void 0,...se(r.unwrap())]:r instanceof Q?[null,...se(r.unwrap())]:r instanceof ot||r instanceof je?se(r.unwrap()):r instanceof Le?se(r._def.innerType):[],At=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=se(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...w(n)})}};function nr(r,e){let t=J(r),n=J(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=x.objectKeys(e),a=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=nr(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=nr(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Ae=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Rt(a)||Rt(i))return g;let o=nr(a.value,i.value);return o.valid?((Et(a)||Et(i))&&t.dirty(),{status:t.value,value:o.data}):(p(n,{code:d.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ae.create=(r,e,t)=>new Ae({left:r,right:e,typeName:_.ZodIntersection,...w(t)});var X=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:d.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return p(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new B(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>N.mergeArray(t,i)):N.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};X.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:r,typeName:_.ZodTuple,rest:null,...w(e)})};var Ot=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:d.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new B(n,o,n.path,o)),value:i._parse(new B(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?N.mergeObjectAsync(t,s):N.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...w(n)}):new r({keyType:me.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}},Be=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:d.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],l)=>({key:s._parse(new B(n,o,n.path,[l,"key"])),value:a._parse(new B(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}}}};Be.create=(r,e,t)=>new Be({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});var We=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:d.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return g;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let o=[...n.data.values()].map((c,l)=>a._parse(new B(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};We.create=(r,e)=>new We({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});var Ct=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return it({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),ne].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return it({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),ne].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof fe){let o=this;return $(async function(...c){let l=new U([]),u=await o._def.args.parseAsync(c,a).catch(v=>{throw l.addIssue(n(c,v)),l}),y=await Reflect.apply(i,this,u);return await o._def.returns._def.type.parseAsync(y,a).catch(v=>{throw l.addIssue(s(y,v)),l})})}else{let o=this;return $(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new U([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),y=o._def.returns.safeParse(u,a);if(!y.success)throw new U([s(u,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:X.create(e).rest(ae.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||X.create([]).rest(ae.create()),returns:t||ae.create(),typeName:_.ZodFunction,...w(n)})}},Oe=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Oe.create=(r,e)=>new Oe({getter:r,typeName:_.ZodLazy,...w(e)});var Ce=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ce.create=(r,e)=>new Ce({value:r,typeName:_.ZodLiteral,...w(e)});function Jr(r,e){return new Ne({values:r,typeName:_.ZodEnum,...w(e)})}var Ne=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:x.joinValues(n),received:t.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),g}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ne.create=Jr;var Pe=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=x.objectValues(t);return p(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return $(e.data)}get enum(){return this._def.values}};Pe.create=(r,e)=>new Pe({values:r,typeName:_.ZodNativeEnum,...w(e)});var fe=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};fe.create=(r,e)=>new fe({type:r,typeName:_.ZodPromise,...w(e)});var W=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?be(c.value):t.value==="dirty"?be(c.value):c});{if(t.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?be(o.value):t.value==="dirty"?be(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!de(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>de(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);x.assertNever(s)}};W.create=(r,e,t)=>new W({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});W.createWithPreprocess=(r,e,t)=>new W({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});var F=class extends b{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};F.create=(r,e)=>new F({innerType:r,typeName:_.ZodOptional,...w(e)});var Q=class extends b{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:_.ZodNullable,...w(e)});var $e=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};$e.create=(r,e)=>new $e({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});var Le=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return De(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new U(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new U(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});var ze=class extends b{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};ze.create=r=>new ze({typeName:_.ZodNaN,...w(r)});var ma=Symbol("zod_brand"),ot=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ct=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),be(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},je=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(de(s)&&(s.value=Object.freeze(s.value)),s);return De(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};je.create=(r,e)=>new je({innerType:r,typeName:_.ZodReadonly,...w(e)});function Zr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xr(r,e={},t){return r?pe.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Zr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Zr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):pe.create()}var pa={object:q.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var fa=(r,e={message:`Input not instance of ${r.name}`})=>Xr(t=>t instanceof r,e),Qr=me.create,en=xe.create,ha=ze.create,ga=Se.create,tn=ke.create,ya=Te.create,_a=He.create,va=Ie.create,wa=Re.create,ba=pe.create,xa=ae.create,Sa=Z.create,ka=Fe.create,Ta=ie.create,Ia=q.create,Ra=q.strictCreate,Ea=Ee.create,Aa=At.create,Oa=Ae.create,Ca=X.create,Na=Ot.create,Pa=Be.create,$a=We.create,La=Ct.create,ja=Oe.create,Ma=Ce.create,Ua=Ne.create,qa=Pe.create,Da=fe.create,Va=W.create,Ha=F.create,Fa=Q.create,Ba=W.createWithPreprocess,Wa=ct.create,za=()=>Qr().optional(),Za=()=>en().optional(),Ga=()=>tn().optional(),Ka={string:(r=>me.create({...r,coerce:!0})),number:(r=>xe.create({...r,coerce:!0})),boolean:(r=>ke.create({...r,coerce:!0})),bigint:(r=>Se.create({...r,coerce:!0})),date:(r=>Te.create({...r,coerce:!0}))};var Ya=g;var rn="1.3.0",nn=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),sn=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),an=k.object({daily_remaining:k.number(),daily_limit:k.number()}),Ja=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),Xa=k.object({proactive:Ja,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),Qa=k.object({user:nn,usage:sn,budget:an,suggestions:Xa}),ei=k.object({user:nn,usage:sn,budget:an});function ti(r){let e=Qa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=ei.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Me(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var ri=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
17
|
+
`,{mode:384})}catch{}}function Ds(r){return r.trim().toLowerCase()}function Br(r,e){if(e<js)return{};if(!r.referralCode||!r.referralLink)return{};let t=Ds(r.referralCode);if(!t)return{};let n=Us();return n.shownCodes.includes(t)?{}:(qs({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var k={};ur(k,{BRAND:()=>ma,DIRTY:()=>be,EMPTY_PATH:()=>Bs,INVALID:()=>g,NEVER:()=>Ya,OK:()=>$,ParseStatus:()=>N,Schema:()=>b,ZodAny:()=>pe,ZodArray:()=>ie,ZodBigInt:()=>Se,ZodBoolean:()=>ke,ZodBranded:()=>ot,ZodCatch:()=>Le,ZodDate:()=>Te,ZodDefault:()=>$e,ZodDiscriminatedUnion:()=>At,ZodEffects:()=>W,ZodEnum:()=>Ne,ZodError:()=>U,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>Ct,ZodIntersection:()=>Ae,ZodIssueCode:()=>d,ZodLazy:()=>Oe,ZodLiteral:()=>Ce,ZodMap:()=>Be,ZodNaN:()=>ze,ZodNativeEnum:()=>Pe,ZodNever:()=>Z,ZodNull:()=>Re,ZodNullable:()=>Q,ZodNumber:()=>xe,ZodObject:()=>q,ZodOptional:()=>F,ZodParsedType:()=>f,ZodPipeline:()=>ct,ZodPromise:()=>fe,ZodReadonly:()=>je,ZodRecord:()=>Ot,ZodSchema:()=>b,ZodSet:()=>We,ZodString:()=>me,ZodSymbol:()=>He,ZodTransformer:()=>W,ZodTuple:()=>X,ZodType:()=>b,ZodUndefined:()=>Ie,ZodUnion:()=>Ee,ZodUnknown:()=>ae,ZodVoid:()=>Fe,addIssueToContext:()=>p,any:()=>ba,array:()=>Ta,bigint:()=>ga,boolean:()=>tn,coerce:()=>Ka,custom:()=>Xr,date:()=>ya,datetimeRegex:()=>Yr,defaultErrorMap:()=>ne,discriminatedUnion:()=>Aa,effect:()=>Va,enum:()=>Ua,function:()=>La,getErrorMap:()=>qe,getParsedType:()=>J,instanceof:()=>fa,intersection:()=>Oa,isAborted:()=>Rt,isAsync:()=>De,isDirty:()=>Et,isValid:()=>de,late:()=>pa,lazy:()=>ja,literal:()=>Ma,makeIssue:()=>it,map:()=>Pa,nan:()=>ha,nativeEnum:()=>qa,never:()=>Sa,null:()=>wa,nullable:()=>Fa,number:()=>en,object:()=>Ia,objectUtil:()=>tr,oboolean:()=>Ga,onumber:()=>Za,optional:()=>Ha,ostring:()=>za,pipeline:()=>Wa,preprocess:()=>Ba,promise:()=>Da,quotelessJson:()=>Vs,record:()=>Na,set:()=>$a,setErrorMap:()=>Fs,strictObject:()=>Ra,string:()=>Qr,symbol:()=>_a,transformer:()=>Va,tuple:()=>Ca,undefined:()=>va,union:()=>Ea,unknown:()=>xa,util:()=>x,void:()=>ka});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var tr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(tr||(tr={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var d=x.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"]),Vs=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),U=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};U.create=r=>new U(r);var Hs=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},ne=Hs;var Wr=ne;function Fs(r){Wr=r}function qe(){return Wr}var it=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Bs=[];function p(r,e){let t=qe(),n=it({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ne?void 0:ne].filter(s=>!!s)});r.common.issues.push(n)}var N=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),be=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),Rt=r=>r.status==="aborted",Et=r=>r.status==="dirty",de=r=>r.status==="valid",De=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var B=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},zr=(r,e)=>{if(de(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new U(r.common.issues);return this._error=t,this._error}}};function w(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return J(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(De(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parseSync({data:e,path:n.path,parent:n});return zr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return de(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>de(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(De(s)?s:Promise.resolve(s));return zr(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new W({schema:this,typeName:_.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:t=>this["~validate"](t)}}optional(){return F.create(this,this._def)}nullable(){return Q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ie.create(this)}promise(){return fe.create(this,this._def)}or(e){return Ee.create([this,e],this._def)}and(e){return Ae.create(this,e,this._def)}transform(e){return new W({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new $e({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new ot({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Le({...w(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ct.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ws=/^c[^\s-]{8,}$/i,zs=/^[0-9a-z]+$/,Zs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Gs=/^[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,Ks=/^[a-z0-9_-]{21}$/i,Ys=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Js=/^[-+]?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)?)??$/,Xs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rr,ea=/^(?:(?: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])$/,ta=/^(?:(?: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])$/,ra=/^(([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]))$/,na=/^(([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])$/,sa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gr="((\\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])))",ia=new RegExp(`^${Gr}$`);function Kr(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function oa(r){return new RegExp(`^${Kr(r)}$`)}function Yr(r){let e=`${Gr}T${Kr(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function ca(r,e){return!!((e==="v4"||!e)&&ea.test(r)||(e==="v6"||!e)&&ra.test(r))}function ua(r,e){if(!Ys.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function la(r,e){return!!((e==="v4"||!e)&&ta.test(r)||(e==="v6"||!e)&&na.test(r))}var me=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new N,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Xs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")rr||(rr=new RegExp(Qs,"u")),rr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Gs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Ks.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Ws.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")zs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Zs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:d.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:d.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.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)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?Yr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?ia.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?oa(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?ca(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?ua(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?la(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?sa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?aa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.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,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};me.create=r=>new me({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...w(r)});function da(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var xe=class r extends b{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)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new N;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?da(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};xe.create=r=>new xe({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});var Se=class r extends b{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)!==f.bigint)return this._getInvalidInput(e);let n,s=new N;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Se.create=r=>new Se({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});var ke=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.boolean,received:n.parsedType}),g}return $(e.data)}};ke.create=r=>new ke({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});var Te=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),g}let n=new N,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):x.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Te.create=r=>new Te({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});var He=class extends b{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.symbol,received:n.parsedType}),g}return $(e.data)}};He.create=r=>new He({typeName:_.ZodSymbol,...w(r)});var Ie=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.undefined,received:n.parsedType}),g}return $(e.data)}};Ie.create=r=>new Ie({typeName:_.ZodUndefined,...w(r)});var Re=class extends b{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.null,received:n.parsedType}),g}return $(e.data)}};Re.create=r=>new Re({typeName:_.ZodNull,...w(r)});var pe=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};pe.create=r=>new pe({typeName:_.ZodAny,...w(r)});var ae=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};ae.create=r=>new ae({typeName:_.ZodUnknown,...w(r)});var Z=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};Z.create=r=>new Z({typeName:_.ZodNever,...w(r)});var Fe=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.void,received:n.parsedType}),g}return $(e.data)}};Fe.create=r=>new Fe({typeName:_.ZodVoid,...w(r)});var ie=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new B(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new B(t,i,t.path,o)));return N.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};ie.create=(r,e)=>new ie({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(e)});function Ve(r){if(r instanceof q){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=F.create(Ve(n))}return new q({...r._def,shape:()=>e})}else return r instanceof ie?new ie({...r._def,type:Ve(r.element)}):r instanceof F?F.create(Ve(r.unwrap())):r instanceof Q?Q.create(Ve(r.unwrap())):r instanceof X?X.create(r.items.map(e=>Ve(e))):r}var q=class r extends b{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(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Z&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let u=a[l],y=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new B(s,y,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Z){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let y=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new B(s,y,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let y=await u.key,E=await u.value;l.push({key:y,value:E,alwaysSet:u.alwaysSet})}return l}).then(l=>N.mergeObjectSync(n,l)):N.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof F;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Jr(x.objectKeys(this.shape))}};q.create=(r,e)=>new q({shape:()=>r,unknownKeys:"strip",catchall:Z.create(),typeName:_.ZodObject,...w(e)});q.strictCreate=(r,e)=>new q({shape:()=>r,unknownKeys:"strict",catchall:Z.create(),typeName:_.ZodObject,...w(e)});q.lazycreate=(r,e)=>new q({shape:r,unknownKeys:"strip",catchall:Z.create(),typeName:_.ZodObject,...w(e)});var Ee=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new U(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new U(c));return p(t,{code:d.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};Ee.create=(r,e)=>new Ee({options:r,typeName:_.ZodUnion,...w(e)});var se=r=>r instanceof Oe?se(r.schema):r instanceof W?se(r.innerType()):r instanceof Ce?[r.value]:r instanceof Ne?r.options:r instanceof Pe?x.objectValues(r.enum):r instanceof $e?se(r._def.innerType):r instanceof Ie?[void 0]:r instanceof Re?[null]:r instanceof F?[void 0,...se(r.unwrap())]:r instanceof Q?[null,...se(r.unwrap())]:r instanceof ot||r instanceof je?se(r.unwrap()):r instanceof Le?se(r._def.innerType):[],At=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=se(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...w(n)})}};function nr(r,e){let t=J(r),n=J(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=x.objectKeys(e),a=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=nr(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=nr(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Ae=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Rt(a)||Rt(i))return g;let o=nr(a.value,i.value);return o.valid?((Et(a)||Et(i))&&t.dirty(),{status:t.value,value:o.data}):(p(n,{code:d.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ae.create=(r,e,t)=>new Ae({left:r,right:e,typeName:_.ZodIntersection,...w(t)});var X=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:d.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return p(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new B(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>N.mergeArray(t,i)):N.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};X.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:r,typeName:_.ZodTuple,rest:null,...w(e)})};var Ot=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:d.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new B(n,o,n.path,o)),value:i._parse(new B(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?N.mergeObjectAsync(t,s):N.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...w(n)}):new r({keyType:me.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}},Be=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:d.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],l)=>({key:s._parse(new B(n,o,n.path,[l,"key"])),value:a._parse(new B(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}}}};Be.create=(r,e,t)=>new Be({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});var We=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:d.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return g;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let o=[...n.data.values()].map((c,l)=>a._parse(new B(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};We.create=(r,e)=>new We({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});var Ct=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return it({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),ne].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return it({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),ne].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof fe){let o=this;return $(async function(...c){let l=new U([]),u=await o._def.args.parseAsync(c,a).catch(v=>{throw l.addIssue(n(c,v)),l}),y=await Reflect.apply(i,this,u);return await o._def.returns._def.type.parseAsync(y,a).catch(v=>{throw l.addIssue(s(y,v)),l})})}else{let o=this;return $(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new U([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),y=o._def.returns.safeParse(u,a);if(!y.success)throw new U([s(u,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:X.create(e).rest(ae.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||X.create([]).rest(ae.create()),returns:t||ae.create(),typeName:_.ZodFunction,...w(n)})}},Oe=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Oe.create=(r,e)=>new Oe({getter:r,typeName:_.ZodLazy,...w(e)});var Ce=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ce.create=(r,e)=>new Ce({value:r,typeName:_.ZodLiteral,...w(e)});function Jr(r,e){return new Ne({values:r,typeName:_.ZodEnum,...w(e)})}var Ne=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:x.joinValues(n),received:t.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),g}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ne.create=Jr;var Pe=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=x.objectValues(t);return p(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return $(e.data)}get enum(){return this._def.values}};Pe.create=(r,e)=>new Pe({values:r,typeName:_.ZodNativeEnum,...w(e)});var fe=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};fe.create=(r,e)=>new fe({type:r,typeName:_.ZodPromise,...w(e)});var W=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?be(c.value):t.value==="dirty"?be(c.value):c});{if(t.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?be(o.value):t.value==="dirty"?be(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!de(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>de(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);x.assertNever(s)}};W.create=(r,e,t)=>new W({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});W.createWithPreprocess=(r,e,t)=>new W({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});var F=class extends b{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};F.create=(r,e)=>new F({innerType:r,typeName:_.ZodOptional,...w(e)});var Q=class extends b{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:_.ZodNullable,...w(e)});var $e=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};$e.create=(r,e)=>new $e({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});var Le=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return De(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new U(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new U(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});var ze=class extends b{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};ze.create=r=>new ze({typeName:_.ZodNaN,...w(r)});var ma=Symbol("zod_brand"),ot=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ct=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),be(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},je=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(de(s)&&(s.value=Object.freeze(s.value)),s);return De(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};je.create=(r,e)=>new je({innerType:r,typeName:_.ZodReadonly,...w(e)});function Zr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xr(r,e={},t){return r?pe.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Zr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Zr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):pe.create()}var pa={object:q.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var fa=(r,e={message:`Input not instance of ${r.name}`})=>Xr(t=>t instanceof r,e),Qr=me.create,en=xe.create,ha=ze.create,ga=Se.create,tn=ke.create,ya=Te.create,_a=He.create,va=Ie.create,wa=Re.create,ba=pe.create,xa=ae.create,Sa=Z.create,ka=Fe.create,Ta=ie.create,Ia=q.create,Ra=q.strictCreate,Ea=Ee.create,Aa=At.create,Oa=Ae.create,Ca=X.create,Na=Ot.create,Pa=Be.create,$a=We.create,La=Ct.create,ja=Oe.create,Ma=Ce.create,Ua=Ne.create,qa=Pe.create,Da=fe.create,Va=W.create,Ha=F.create,Fa=Q.create,Ba=W.createWithPreprocess,Wa=ct.create,za=()=>Qr().optional(),Za=()=>en().optional(),Ga=()=>tn().optional(),Ka={string:(r=>me.create({...r,coerce:!0})),number:(r=>xe.create({...r,coerce:!0})),boolean:(r=>ke.create({...r,coerce:!0})),bigint:(r=>Se.create({...r,coerce:!0})),date:(r=>Te.create({...r,coerce:!0}))};var Ya=g;var rn="1.4.0-rc.0",nn=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),sn=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),an=k.object({daily_remaining:k.number(),daily_limit:k.number()}),Ja=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),Xa=k.object({proactive:Ja,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),Qa=k.object({user:nn,usage:sn,budget:an,suggestions:Xa}),ei=k.object({user:nn,usage:sn,budget:an});function ti(r){let e=Qa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=ei.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Me(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var ri=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
18
18
|
|
|
19
19
|
Rules:
|
|
20
20
|
- If the user asks a question that one of your tools can answer \u2014 including historical data, analytics, comparisons, or trends \u2014 offer to use the tool. Don't just answer from your training data when live data is available.
|
|
@@ -59,7 +59,7 @@ Your first response in this session MUST end with this line in bold italic:
|
|
|
59
59
|
`+y.map(E=>`- "${E}"`).join(`
|
|
60
60
|
`))}}return e.join(`
|
|
61
61
|
|
|
62
|
-
`)}},ar=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),ir=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!ar.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!ar.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Me(n)),t}},oi=3e3;async function or(r,e,t){let n={instructions:new ut(null,t).build(),manager:null};try{let s=await r();if(!s)return m.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Mt(),lr)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":rn},timeoutMs:oi});if(!i.ok)return m.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!mt()){let u=i.headers.get("X-Latest-Version"),y=i.headers.get("X-Update-Message");u&&dt(u,rn)&&(o=y||`Update available: v${u}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),l=ti(c);if(l.full)return m.info(`suggestions: loaded for ${l.full.user.name??"unknown"} (proactive: ${l.full.suggestions.proactive?"yes":"none"})`),{instructions:new ut(l.full,t,o).build(),manager:new ir(l.full.suggestions.reactive)};if(l.partial){m.warn("suggestions: suggestions block malformed, using partial payload");let u={...l.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new ut(u,t,o).build(),manager:null}}return m.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return m.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var Nt=I(require("crypto")),Pt=I(require("tty")),$t=I(require("fs"));var Ue="
|
|
62
|
+
`)}},ar=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),ir=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!ar.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!ar.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Me(n)),t}},oi=3e3;async function or(r,e,t){let n={instructions:new ut(null,t).build(),manager:null};try{let s=await r();if(!s)return m.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Mt(),lr)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":rn},timeoutMs:oi});if(!i.ok)return m.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!mt()){let u=i.headers.get("X-Latest-Version"),y=i.headers.get("X-Update-Message");u&&dt(u,rn)&&(o=y||`Update available: v${u}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),l=ti(c);if(l.full)return m.info(`suggestions: loaded for ${l.full.user.name??"unknown"} (proactive: ${l.full.suggestions.proactive?"yes":"none"})`),{instructions:new ut(l.full,t,o).build(),manager:new ir(l.full.suggestions.reactive)};if(l.partial){m.warn("suggestions: suggestions block malformed, using partial payload");let u={...l.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new ut(u,t,o).build(),manager:null}}return m.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return m.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var Nt=I(require("crypto")),Pt=I(require("tty")),$t=I(require("fs"));var Ue="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function ui(r){return/-rc\.|-beta\./.test(r)}function cr(r){return Nt.createHash("sha256").update(r.trim()).digest("hex")}function cn(r){return Ue==="SKIP"?!0:Nt.timingSafeEqual(Buffer.from(cr(r)),Buffer.from(Ue))}function li(r){return new Promise((e,t)=>{let n=$t.openSync("/dev/tty","r+"),s=new Pt.ReadStream(n),a=new Pt.WriteStream(n),i=()=>{try{s.destroy()}catch{}try{a.destroy()}catch{}try{$t.closeSync(n)}catch{}};a.write(r),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let o="";s.on("data",c=>{c==="\r"||c===`
|
|
63
63
|
`?(a.write(`
|
|
64
64
|
`),i(),e(o)):c===""?(a.write(`
|
|
65
65
|
`),i(),t(new Error("Cancelled"))):c==="\x7F"||c==="\b"?o.length>0&&(o=o.slice(0,-1),a.write("\b \b")):(o+=c,a.write("\u2022"))})})}var di=`
|