@visa/cli 1.6.0-rc.4 → 1.7.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 CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var On=Object.create;var bt=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Un=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Vn=Object.prototype.hasOwnProperty;var Fn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Bn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Un(t))!Vn.call(e,s)&&s!==n&&bt(e,s,{get:()=>t[s],enumerable:!(r=jn(t,s))||r.enumerable});return e};var g=(e,t,n)=>(n=e!=null?On(Hn(e)):{},Bn(t||!e||!e.__esModule?bt(n,"default",{value:e,enumerable:!0}):n,e));var qe=Fn((fs,tr)=>{tr.exports={name:"@visa/cli",version:"1.6.0-rc.4",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"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var En=require("commander"),Oe=g(require("crypto")),Tn=g(require("fs")),N=g(require("os")),pe=g(require("path")),Rn=g(require("readline")),An=require("child_process"),In=require("util");var he=require("child_process"),vt=require("util"),W=g(require("fs")),ye=g(require("os")),Fe=g(require("path")),O=(0,vt.promisify)(he.execFile),Be=Fe.join(ye.homedir(),".visa-mcp"),me=Fe.join(Be,"session-token"),I="visa-cli",G="session-token",ge="rc-access",Kn=5e3;async function qn(){try{let{stdout:e}=await O("security",["find-generic-password","-s",I,"-a",G,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Gn(e){try{try{await O("security",["delete-generic-password","-s",I,"-a",G],{timeout:5e3})}catch{}return await O("security",["add-generic-password","-s",I,"-a",G,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Wn(){try{await O("security",["delete-generic-password","-s",I,"-a",G],{timeout:5e3})}catch{}}async function Jn(){if(!Ke())return null;try{let{stdout:e}=await O("secret-tool",["lookup","service",I,"account",G],{timeout:5e3});return e.trim()||null}catch{return null}}async function zn(e){if(!Ke())return!1;try{let t=(0,he.execFile)("secret-tool",["store","--label",`${I} ${G}`,"service",I,"account",G]);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"))},Kn))]),!0):!1}catch{return!1}}async function Yn(){if(Ke())try{await O("secret-tool",["clear","service",I,"account",G],{timeout:5e3})}catch{}}function Ke(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Xn(){try{let{stdout:e}=await O("security",["find-generic-password","-s",I,"-a",ge,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Zn(e){try{try{await O("security",["delete-generic-password","-s",I,"-a",ge],{timeout:5e3})}catch{}await O("security",["add-generic-password","-s",I,"-a",ge,"-w",e],{timeout:5e3})}catch{}}async function Qn(){try{await O("security",["delete-generic-password","-s",I,"-a",ge],{timeout:5e3})}catch{}}function He(){try{return W.readFileSync(me,"utf-8").trim()||null}catch{return null}}function wt(e){W.mkdirSync(Be,{recursive:!0,mode:448}),W.writeFileSync(me,e,{mode:384}),process.platform==="win32"&&er(me)}function Ve(){try{W.unlinkSync(me)}catch{}}function er(e){try{let t=ye.userInfo().username;(0,he.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 Ue(){switch(process.platform){case"darwin":return{get:qn,store:Gn,delete:Wn};case"linux":return{get:Jn,store:zn,delete:Yn};default:return{get:async()=>He(),store:async e=>{try{return wt(e),!0}catch{return!1}},delete:async()=>Ve()}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Ue(),n=await t.get();if(n)return n;let r=He();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Ue();if(await n.store(t)){if(await n.get()===t){Ve();return}await n.delete()}if(wt(t),He()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Be} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Xn()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Zn(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Ue().delete(),Ve()}static async clearAll(){await this.deleteSessionToken(),await Qn()}};var Se=g(require("crypto")),be=g(require("tty")),ve=g(require("fs"));var X="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function nr(e){return/-rc\.|-beta\./.test(e)}function Ge(e){return Se.createHash("sha256").update(e.trim()).digest("hex")}function _t(e){return X==="SKIP"?!0:Se.timingSafeEqual(Buffer.from(Ge(e)),Buffer.from(X))}function rr(e){return new Promise((t,n)=>{let r=ve.openSync("/dev/tty","r+"),s=new be.ReadStream(r),o=new be.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{ve.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
1
+ "use strict";var Kn=Object.create;var Ct=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty;var zn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gn(t))!Jn.call(e,s)&&s!==n&&Ct(e,s,{get:()=>t[s],enumerable:!(r=qn(t,s))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Kn(Wn(e)):{},Yn(t||!e||!e.__esModule?Ct(n,"default",{value:e,enumerable:!0}):n,e));var Je=zn((ws,cr)=>{cr.exports={name:"@visa/cli",version:"1.7.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"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Nn=require("commander"),He=h(require("crypto")),Dn=h(require("fs")),H=h(require("os")),ge=h(require("path")),Mn=h(require("readline")),Un=require("child_process"),jn=require("util");var Se=require("child_process"),kt=require("util"),Y=h(require("fs")),ve=h(require("os")),qe=h(require("path")),B=(0,kt.promisify)(Se.execFile),Ge=qe.join(ve.homedir(),".visa-mcp"),he=qe.join(Ge,"session-token"),U="visa-cli",z="session-token",ye="rc-access",Xn=5e3;async function Zn(){try{let{stdout:e}=await B("security",["find-generic-password","-s",U,"-a",z,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Qn(e){try{try{await B("security",["delete-generic-password","-s",U,"-a",z],{timeout:5e3})}catch{}return await B("security",["add-generic-password","-s",U,"-a",z,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function er(){try{await B("security",["delete-generic-password","-s",U,"-a",z],{timeout:5e3})}catch{}}async function tr(){if(!We())return null;try{let{stdout:e}=await B("secret-tool",["lookup","service",U,"account",z],{timeout:5e3});return e.trim()||null}catch{return null}}async function nr(e){if(!We())return!1;try{let t=(0,Se.execFile)("secret-tool",["store","--label",`${U} ${z}`,"service",U,"account",z]);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"))},Xn))]),!0):!1}catch{return!1}}async function rr(){if(We())try{await B("secret-tool",["clear","service",U,"account",z],{timeout:5e3})}catch{}}function We(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function sr(){try{let{stdout:e}=await B("security",["find-generic-password","-s",U,"-a",ye,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function or(e){try{try{await B("security",["delete-generic-password","-s",U,"-a",ye],{timeout:5e3})}catch{}await B("security",["add-generic-password","-s",U,"-a",ye,"-w",e],{timeout:5e3})}catch{}}async function ir(){try{await B("security",["delete-generic-password","-s",U,"-a",ye],{timeout:5e3})}catch{}}function Be(){try{return Y.readFileSync(he,"utf-8").trim()||null}catch{return null}}function $t(e){Y.mkdirSync(Ge,{recursive:!0,mode:448}),Y.writeFileSync(he,e,{mode:384}),process.platform==="win32"&&ar(he)}function Ke(){try{Y.unlinkSync(he)}catch{}}function ar(e){try{let t=ve.userInfo().username;(0,Se.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 Fe(){switch(process.platform){case"darwin":return{get:Zn,store:Qn,delete:er};case"linux":return{get:tr,store:nr,delete:rr};default:return{get:async()=>Be(),store:async e=>{try{return $t(e),!0}catch{return!1}},delete:async()=>Ke()}}}var C=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Fe(),n=await t.get();if(n)return n;let r=Be();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Fe();if(await n.store(t)){if(await n.get()===t){Ke();return}await n.delete()}if($t(t),Be()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Ge} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":sr()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await or(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Fe().delete(),Ke()}static async clearAll(){await this.deleteSessionToken(),await ir()}};var be=h(require("crypto")),we=h(require("tty")),_e=h(require("fs"));var Q="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function lr(e){return/-rc\.|-beta\./.test(e)}function ze(e){return be.createHash("sha256").update(e.trim()).digest("hex")}function Et(e){return Q==="SKIP"?!0:be.timingSafeEqual(Buffer.from(ze(e)),Buffer.from(Q))}function ur(e){return new Promise((t,n)=>{let r=_e.openSync("/dev/tty","r+"),s=new we.ReadStream(r),o=new we.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{_e.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 sr=`
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 dr=`
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,26 +10,26 @@
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 $t(e={}){let t=e.version??qe().version;if(!nr(t))return;let n=process.env.VISA_RC_CODE;if(n&&_t(n)){await $.saveRcAccessToken(Ge(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(X==="SKIP"||i===X))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
14
- `),process.exit(1)}let s=await $.getRcAccessToken();if(s&&(X==="SKIP"||s===X))return;console.log(sr);let o=3;for(let i=1;i<=o;i++){let a;try{a=await rr(" Enter RC access code: ")}catch{process.exit(1)}if(_t(a)){await $.saveRcAccessToken(Ge(a)),console.log(`
13
+ `;async function xt(e={}){let t=e.version??Je().version;if(!lr(t))return;let n=process.env.VISA_RC_CODE;if(n&&Et(n)){await C.saveRcAccessToken(ze(n));return}if(e.isMcp??!1){let i=await C.getRcAccessToken();if(i&&(Q==="SKIP"||i===Q))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
14
+ `),process.exit(1)}let s=await C.getRcAccessToken();if(s&&(Q==="SKIP"||s===Q))return;console.log(dr);let o=3;for(let i=1;i<=o;i++){let a;try{a=await ur(" Enter RC access code: ")}catch{process.exit(1)}if(Et(a)){await C.saveRcAccessToken(ze(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 Ct=require("child_process");function or(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 ir(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 ar(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 xt(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,d,u)=>{(0,Ct.execFile)(c,d,f=>u(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of ir(e).split(`
22
- `))n(` ${c}`);n("");let i=or(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=ar(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,d=>{d?(n(` Could not open browser automatically (${d.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var Pt=g(require("crypto")),E=g(require("fs")),we=g(require("path"));function Et(e,t){E.mkdirSync(we.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Pt.randomBytes(8).toString("hex")}.tmp`;try{E.writeFileSync(n,JSON.stringify(t,null,2)+`
23
- `),E.renameSync(n,e)}catch(r){try{E.unlinkSync(n)}catch{}throw r}}function kt(e){return`'${e.replace(/'/g,"'\\''")}'`}var Tt="# visa-cli-hud-v1";function cr(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?we.resolve(r):"";return`${s?`${kt(n)} ${kt(s)} statusline`:"visa-cli statusline"} ${Tt}`}function Rt(e){return typeof e!="string"?!1:e.includes(Tt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function We(e,t=cr){let n={},r=!1;if(E.existsSync(e)){r=!0;try{n=JSON.parse(E.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 Rt(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()},Et(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 At(e){if(!E.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(E.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 Rt(n)?(delete t.statusLine,Et(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 F=g(require("fs")),J=g(require("path")),lr=50,ur=64*1024,It=10,Je=80;function dr(){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 ze=dr(),S={reset:"\x1B[0m",visaBlue:ze?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ze?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ze?"\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}${S.reset}`}function Lt(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Mt(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(d)},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 f=JSON.parse(u);o(f&&typeof f=="object"?f:null)}catch{o(null)}},c=()=>o(null),d=setTimeout(()=>{n.length>0?a():o(null)},lr);e.on("data",i),e.on("end",a),e.on("error",c)})}function Ot(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||"",S.visaBlueSoft)}${b(s||"",S.dim)}`}function Nt(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 fr(e){let t=` ${b("\u2502",S.dim)} `,n=Z(e.model?.display_name)||"claude",r=e.cwd?Z(J.basename(e.cwd)):"",s=_r(e.workspace),o=r||s,i=s&&s!==o?` ${b(`@${s}`,S.visaBlueSoft)}`:"",a=[b(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${b(o,S.visaGold)}${i}`);let c=a.join(t),d=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,f=e.context_window?.current_usage,l=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(q=>typeof q=="number"&&Number.isFinite(q)),h=l.length>0?l.reduce((q,je)=>q+je,0):null,v=Number(e.context_window?.total_input_tokens??h??f?.input_tokens??0),k=u!==null?Math.max(0,Math.min(1,u/100)):d>0?Math.max(0,Math.min(1,v/d)):0,H=u!==null&&d>0?Math.round(k*d):v,V;if(d>0||u!==null){let q=`${String(Math.round(k*100)).padStart(2," ")}%`,je=d>0?` ${b(`(${Nt(H)}/${Nt(d)})`,S.dim)}`:"";V=`${b("Context",S.dim)} ${Ot(k)} ${b(q,S.green)}${je}`}else V=`${b("Context",S.dim)} ${b("-",S.dim)}`;let B=mr(e.rate_limits),K=[V];B&&K.push(B);let P=K.join(t);return`${c}
24
- ${P}`}function pr(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 Dt(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=Ot(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=pr(e.resets_at),c=a?` ${b(`(${a} / ${t})`,S.dim)}`:` ${b(`(${t})`,S.dim)}`;return`${s} ${b(i,o)}${c}`}function mr(e){if(!e)return null;let t=Dt(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Dt(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${b("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${b("Usage",S.dim)} ${o.join(s)}`}function gr(e){let t;try{let n=F.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,ur),o=r-s;t=F.openSync(e,"r");let i=Buffer.alloc(s);F.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(F.readSync(t,c,0,1,o-1),c[0]!==10){let d=a.indexOf(`
25
- `);d>=0&&(a=a.slice(d+1))}}return a}catch{return null}finally{if(t!==void 0)try{F.closeSync(t)}catch{}}}function hr(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=J.basename(J.dirname(s)),i=J.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function yr(e){let t=e.split(`
26
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<It*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 d=c.content;if(Array.isArray(d))for(let u of d){if(!u||typeof u!="object")continue;let f=u;if(f.type==="tool_result"&&typeof f.tool_use_id=="string")r.add(f.tool_use_id);else if(f.type==="tool_use"&&typeof f.name=="string"){let l=typeof f.id=="string"?f.id:"",h=l.length>0?!r.has(l):!1;n.push({name:f.name,target:hr(f.input),running:h})}}}return n.reverse(),n.slice(Math.max(0,n.length-It))}function Sr(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 br(e){let t=e.running?b("\u25D0",S.visaGold):b("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=b(Z(e.name),n),s=e.target?Z(e.target):"",o=s?`${b(":",S.dim)} ${b(s,S.dim)}`:"",i=e.count>1?` ${b(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function vr(e){let t=` ${b("\u2502",S.dim)} `,n=Lt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Lt(c)<=Je)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>Je-n-1?i.slice(0,Je-n-1)+s:i;return`${b(s,S.dim)}${t}${a}`}async function wr(e){if(!e||typeof e!="string")return null;let t=gr(e);if(!t)return null;let n;try{n=yr(t)}catch{return null}if(n.length===0)return null;let s=Sr(n).map(br);return vr(s)||null}async function jt(e,t){let n=[e];if(t){let r=fr(t);if(r&&n.push(r),t.transcript_path){let s=await wr(t.transcript_path);s&&n.push(s)}}return n.join(`
27
- `)}function Z(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 _r(e){if(typeof e=="string")return Z(J.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 Z(t?J.basename(t):e.name)}async function Ut(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 $r=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Vt(e,t){let n=Ht(e),r=Ht(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:Cr(n.pre,r.pre)>0}function Ht(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match($r);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Cr(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),d=/^\d+$/.test(a);if(c&&d){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(d)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function z(){return!!(Ft(process.env.VISA_CLI_NO_UPDATE_CHECK)||Ft(process.env.CI)||process.env.NODE_ENV==="test")}function Ft(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ye="1.6.0-rc.4",te=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={},!z()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&Vt(r,Ye)&&(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 Ye}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 Ut(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Ye},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 d;try{d=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(d?.error||`Request failed (${c.status}). Try again.`);return d}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 setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}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 tt=require("child_process"),Jt=require("util"),zt=g(require("crypto")),C=g(require("fs")),Yt=g(require("os")),j=g(require("path"));var T=g(require("fs")),Qe=g(require("path")),Bt=g(require("os")),Ze=Qe.join(Bt.homedir(),".visa-mcp"),oe=Qe.join(Ze,"mcp-server.log"),xr=5*1024*1024,Xe=null;function kr(){T.existsSync(Ze)||T.mkdirSync(Ze,{recursive:!0,mode:448})}function Pr(){if(!Xe){if(kr(),T.existsSync(oe)&&T.statSync(oe).size>xr){let t=oe+".1";T.existsSync(t)&&T.unlinkSync(t),T.renameSync(oe,t)}Xe=T.createWriteStream(oe,{flags:"a"})}return Xe}function _e(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),Pr().write(s)}var ne={debug:(...e)=>_e("DEBUG",...e),info:(...e)=>_e("INFO",...e),warn:(...e)=>_e("WARN",...e),error:(...e)=>_e("ERROR",...e)};var re=(0,Jt.promisify)(tt.execFile),xe=j.join(Yt.homedir(),".visa-mcp","bin"),Q=j.join(xe,"Visa CLI"),Er=j.join(__dirname,"..","native"),Kt="5",qt=j.join(xe,"visa-keychain.version"),Gt=j.join(xe,"visa-keychain.sha256");function Wt(e){let t=C.readFileSync(e);return zt.createHash("sha256").update(t).digest("hex")}async function Xt(){try{if(C.readFileSync(qt,"utf-8").trim()===Kt&&C.existsSync(Q)){let r=C.readFileSync(Gt,"utf-8").trim();if(Wt(Q)!==r)ne.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),C.unlinkSync(Q);else return Q}}catch{}let e=j.join(Er,"visa-keychain.m");if(C.existsSync(e)||(e=j.resolve(__dirname,"..","..","native","visa-keychain.m")),C.existsSync(e)||(e=j.resolve(__dirname,"..","native","visa-keychain.m")),!C.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");C.mkdirSync(xe,{recursive:!0,mode:448});try{await re("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Q,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Wt(Q);return C.writeFileSync(Gt,t,{mode:384}),C.writeFileSync(qt,Kt,{mode:384}),Q}async function Zt(e){let t=await Xt(),n;try{n=(await re(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 et=null;function D(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:et!==null?et:(et=!0,!0)}var $e="visa-cli",Ce="attestation-key";async function Tr(e){try{await re("security",["delete-generic-password","-s",$e,"-a",Ce],{timeout:5e3})}catch{}await re("security",["add-generic-password","-s",$e,"-a",Ce,"-w",e],{timeout:5e3})}async function Rr(){try{let{stdout:e}=await re("security",["find-generic-password","-s",$e,"-a",Ce,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function ke(){let e=await Zt(["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 Tr(n),r}async function nt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Rr();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Xt(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,tt.execFile)(r,s,{timeout:6e4},(c,d)=>{let u=(d||"").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 Qt(){try{await re("security",["delete-generic-password","-s",$e,"-a",Ce],{timeout:5e3})}catch{}try{await Zt(["delete-key"])}catch{}}function tn(e,t=process.stderr){if(z()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
20
+ `),process.exit(1)}var Pt=require("child_process");function fr(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 pr(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 mr(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 Rt(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((c,l,u)=>{(0,Pt.execFile)(c,l,f=>u(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of pr(e).split(`
22
+ `))n(` ${c}`);n("");let i=fr(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=mr(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,l=>{l?(n(` Could not open browser automatically (${l.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var At=h(require("crypto")),R=h(require("fs")),Ce=h(require("path"));function It(e,t){R.mkdirSync(Ce.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${At.randomBytes(8).toString("hex")}.tmp`;try{R.writeFileSync(n,JSON.stringify(t,null,2)+`
23
+ `),R.renameSync(n,e)}catch(r){try{R.unlinkSync(n)}catch{}throw r}}function Tt(e){return`'${e.replace(/'/g,"'\\''")}'`}var Lt="# visa-cli-hud-v1";function gr(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Ce.resolve(r):"";return`${s?`${Tt(n)} ${Tt(s)} statusline`:"visa-cli statusline"} ${Lt}`}function Ot(e){return typeof e!="string"?!1:e.includes(Lt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Ye(e,t=gr){let n={},r=!1;if(R.existsSync(e)){r=!0;try{n=JSON.parse(R.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 Ot(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()},It(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 Nt(e){if(!R.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(R.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 Ot(n)?(delete t.statusLine,It(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 G=h(require("fs")),X=h(require("path")),hr=50,yr=64*1024,Dt=10,Xe=80;function Sr(){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 Ze=Sr(),S={reset:"\x1B[0m",visaBlue:Ze?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Ze?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Ze?"\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}${S.reset}`}function Mt(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Ht(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(l)},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 f=JSON.parse(u);o(f&&typeof f=="object"?f:null)}catch{o(null)}},c=()=>o(null),l=setTimeout(()=>{n.length>0?a():o(null)},hr);e.on("data",i),e.on("end",a),e.on("error",c)})}function Vt(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||"",S.visaBlueSoft)}${b(s||"",S.dim)}`}function Ut(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 vr(e){let t=` ${b("\u2502",S.dim)} `,n=ee(e.model?.display_name)||"claude",r=e.cwd?ee(X.basename(e.cwd)):"",s=Rr(e.workspace),o=r||s,i=s&&s!==o?` ${b(`@${s}`,S.visaBlueSoft)}`:"",a=[b(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${b(o,S.visaGold)}${i}`);let c=a.join(t),l=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,f=e.context_window?.current_usage,d=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(J=>typeof J=="number"&&Number.isFinite(J)),m=d.length>0?d.reduce((J,Ve)=>J+Ve,0):null,v=Number(e.context_window?.total_input_tokens??m??f?.input_tokens??0),k=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,v/l)):0,L=u!==null&&l>0?Math.round(k*l):v,$;if(l>0||u!==null){let J=`${String(Math.round(k*100)).padStart(2," ")}%`,Ve=l>0?` ${b(`(${Ut(L)}/${Ut(l)})`,S.dim)}`:"";$=`${b("Context",S.dim)} ${Vt(k)} ${b(J,S.green)}${Ve}`}else $=`${b("Context",S.dim)} ${b("-",S.dim)}`;let D=wr(e.rate_limits),M=[$];D&&M.push(D);let P=M.join(t);return`${c}
24
+ ${P}`}function br(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 jt(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=Vt(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=br(e.resets_at),c=a?` ${b(`(${a} / ${t})`,S.dim)}`:` ${b(`(${t})`,S.dim)}`;return`${s} ${b(i,o)}${c}`}function wr(e){if(!e)return null;let t=jt(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?jt(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${b("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${b("Usage",S.dim)} ${o.join(s)}`}function _r(e){let t;try{let n=G.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,yr),o=r-s;t=G.openSync(e,"r");let i=Buffer.alloc(s);G.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(G.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
25
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{G.closeSync(t)}catch{}}}function Cr(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=X.basename(X.dirname(s)),i=X.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function kr(e){let t=e.split(`
26
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Dt*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 l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let f=u;if(f.type==="tool_result"&&typeof f.tool_use_id=="string")r.add(f.tool_use_id);else if(f.type==="tool_use"&&typeof f.name=="string"){let d=typeof f.id=="string"?f.id:"",m=d.length>0?!r.has(d):!1;n.push({name:f.name,target:Cr(f.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Dt))}function $r(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 Er(e){let t=e.running?b("\u25D0",S.visaGold):b("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=b(ee(e.name),n),s=e.target?ee(e.target):"",o=s?`${b(":",S.dim)} ${b(s,S.dim)}`:"",i=e.count>1?` ${b(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function xr(e){let t=` ${b("\u2502",S.dim)} `,n=Mt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Mt(c)<=Xe)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>Xe-n-1?i.slice(0,Xe-n-1)+s:i;return`${b(s,S.dim)}${t}${a}`}async function Pr(e){if(!e||typeof e!="string")return null;let t=_r(e);if(!t)return null;let n;try{n=kr(t)}catch{return null}if(n.length===0)return null;let s=$r(n).map(Er);return xr(s)||null}async function Ft(e,t){let n=[e];if(t){let r=vr(t);if(r&&n.push(r),t.transcript_path){let s=await Pr(t.transcript_path);s&&n.push(s)}}return n.join(`
27
+ `)}function ee(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 Rr(e){if(typeof e=="string")return ee(X.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 ee(t?X.basename(t):e.name)}async function Bt(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 Tr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function qt(e,t){let n=Kt(e),r=Kt(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:Ar(n.pre,r.pre)>0}function Kt(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Tr);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Ar(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),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function K(){return!!(Gt(process.env.VISA_CLI_NO_UPDATE_CHECK)||Gt(process.env.CI)||process.env.NODE_ENV==="test")}function Gt(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Qe="1.7.0-rc.0",re=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={},!K()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&qt(r,Qe)&&(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 Qe}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 Bt(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Qe},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 l;try{l=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(l?.error||`Request failed (${c.status}). Try again.`);return l}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 setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}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 st=require("child_process"),Zt=require("util"),Qt=h(require("crypto")),E=h(require("fs")),en=h(require("os")),q=h(require("path"));var T=h(require("fs")),nt=h(require("path")),Wt=h(require("os")),tt=nt.join(Wt.homedir(),".visa-mcp"),ae=nt.join(tt,"mcp-server.log"),Ir=5*1024*1024,et=null;function Lr(){T.existsSync(tt)||T.mkdirSync(tt,{recursive:!0,mode:448})}function Or(){if(!et){if(Lr(),T.existsSync(ae)&&T.statSync(ae).size>Ir){let t=ae+".1";T.existsSync(t)&&T.unlinkSync(t),T.renameSync(ae,t)}et=T.createWriteStream(ae,{flags:"a"})}return et}function ke(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),Or().write(s)}var se={debug:(...e)=>ke("DEBUG",...e),info:(...e)=>ke("INFO",...e),warn:(...e)=>ke("WARN",...e),error:(...e)=>ke("ERROR",...e)};var oe=(0,Zt.promisify)(st.execFile),xe=q.join(en.homedir(),".visa-mcp","bin"),te=q.join(xe,"Visa CLI"),Nr=q.join(__dirname,"..","native"),Jt="5",zt=q.join(xe,"visa-keychain.version"),Yt=q.join(xe,"visa-keychain.sha256");function Xt(e){let t=E.readFileSync(e);return Qt.createHash("sha256").update(t).digest("hex")}async function tn(){try{if(E.readFileSync(zt,"utf-8").trim()===Jt&&E.existsSync(te)){let r=E.readFileSync(Yt,"utf-8").trim();if(Xt(te)!==r)se.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),E.unlinkSync(te);else return te}}catch{}let e=q.join(Nr,"visa-keychain.m");if(E.existsSync(e)||(e=q.resolve(__dirname,"..","..","native","visa-keychain.m")),E.existsSync(e)||(e=q.resolve(__dirname,"..","native","visa-keychain.m")),!E.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");E.mkdirSync(xe,{recursive:!0,mode:448});try{await oe("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",te,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Xt(te);return E.writeFileSync(Yt,t,{mode:384}),E.writeFileSync(zt,Jt,{mode:384}),te}async function nn(e){let t=await tn(),n;try{n=(await oe(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 rt=null;function A(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:rt!==null?rt:(rt=!0,!0)}var $e="visa-cli",Ee="attestation-key";async function Dr(e){try{await oe("security",["delete-generic-password","-s",$e,"-a",Ee],{timeout:5e3})}catch{}await oe("security",["add-generic-password","-s",$e,"-a",Ee,"-w",e],{timeout:5e3})}async function Mr(){try{let{stdout:e}=await oe("security",["find-generic-password","-s",$e,"-a",Ee,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Pe(){let e=await nn(["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 Dr(n),r}async function ot(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Mr();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await tn(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,st.execFile)(r,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:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function rn(){try{await oe("security",["delete-generic-password","-s",$e,"-a",Ee],{timeout:5e3})}catch{}try{await nn(["delete-key"])}catch{}}function sn(e,t=process.stderr){if(K()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
29
29
  \x1B[33m\u2191 ${n}\x1B[0m
30
- `),!0):!1}function rn(e,t,n,r){let o=Or(e.spendingControls).dailyLimit,i=Math.max(0,ie(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,ie(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(Lr),f=u.slice(0,3),l=Nr(u,3),h=(e.cards??[]).slice(0,3),v=r.latestVersion?rt(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",H=Math.round(c*100),V=Y(e.status,e.enrolled?"approved":"not enrolled"),K=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${V} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${k}`,`Spend meter: ${nn(c)} ${String(H).padStart(3," ")}% | remaining ${se(a)}/day | daily cap ${se(o)}`,"","Spend",` Remaining ${se(a)} / ${se(o)}`,` Usage ${nn(c)} ${H}%`,` Spent today ${se(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...h.length>0?h.map(P=>` ${Mr(P)}`):[" No cards enrolled"],"","Last 3 services",...l.length>0?l.map((P,q)=>` ${q+1}. ${P}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(P=>` ${Dr(P)}`):[" No receipts yet"]];return r.updateMessage&&K.push("",`Update: ${rt(r.updateMessage)}`),`${K.join(`
30
+ `),!0):!1}function an(e,t,n,r){let o=Kr(e.spendingControls).dailyLimit,i=Math.max(0,ce(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,ce(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(Hr),f=u.slice(0,3),d=Vr(u,3),m=(e.cards??[]).slice(0,3),v=r.latestVersion?at(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",L=Math.round(c*100),$=Z(e.status,e.enrolled?"approved":"not enrolled"),M=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${$} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${k}`,`Spend meter: ${on(c)} ${String(L).padStart(3," ")}% | remaining ${ie(a)}/day | daily cap ${ie(o)}`,"","Spend",` Remaining ${ie(a)} / ${ie(o)}`,` Usage ${on(c)} ${L}%`,` Spent today ${ie(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...m.length>0?m.map(P=>` ${Br(P)}`):[" No cards enrolled"],"","Last 3 services",...d.length>0?d.map((P,J)=>` ${J+1}. ${P}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(P=>` ${Fr(P)}`):[" No receipts yet"]];return r.updateMessage&&M.push("",`Update: ${at(r.updateMessage)}`),`${M.join(`
31
31
  `)}
32
- `}function Ar(e){return e.tool_name!=null}function Ir(e){return ie(e.amount)===0&&e.status==="failed"}function Lr(e){return Ar(e)&&!Ir(e)}function Nr(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Y(s.merchant_name,"Unknown merchant"),i=Y(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Dr(e){let t=Y(e.merchant_name,"Unknown merchant"),n=Y(e.tool_name,"unknown_tool"),r=se(ie(e.amount)),s=Y(e.status,"unknown"),o=jr(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Mr(e){let t=Y(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Or(e){return{dailyLimit:ie(e?.daily_limit??e?.dailyLimit??0)}}function ie(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function se(e){return`$${e.toFixed(2)}`}function nn(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 Y(e,t){let n=rt(e??"").trim();return n.length>0?n:t}function jr(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Y(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function rt(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 y=g(require("fs")),Ae=g(require("os")),w=g(require("path")),on=require("child_process"),Ur=2,Pe="# >>> visa-cli shell hud v2 >>>",Ee="# <<< visa-cli shell hud v2 <<<",Hr="# >>> visa-cli shell hud >>>",Vr="# <<< visa-cli shell hud <<<",an=3e4,Fr=3e4;function at(){try{return w.join(mn(),".visa-cli")}catch{return w.join(Ae.tmpdir(),".visa-cli")}}function ce(){return w.join(at(),"shell-hud.json")}function Ie(){return w.join(at(),"shell-hud.line")}function cn(){return w.join(at(),"shell-hud.lock")}function Le(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 Ne(e){let t=mn();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 Br(e){let t="$HOME/.visa-cli/shell-hud.line",n=zr(e),r=Yr(e);if(e==="zsh")return`${Pe}
32
+ `}function Ur(e){return e.tool_name!=null}function jr(e){return ce(e.amount)===0&&e.status==="failed"}function Hr(e){return Ur(e)&&!jr(e)}function Vr(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 Fr(e){let t=Z(e.merchant_name,"Unknown merchant"),n=Z(e.tool_name,"unknown_tool"),r=ie(ce(e.amount)),s=Z(e.status,"unknown"),o=qr(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Br(e){let t=Z(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function Kr(e){return{dailyLimit:ce(e?.daily_limit??e?.dailyLimit??0)}}function ce(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function ie(e){return`$${e.toFixed(2)}`}function on(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=at(e??"").trim();return n.length>0?n:t}function qr(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 at(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 y=h(require("fs")),Le=h(require("os")),w=h(require("path")),ln=require("child_process"),Gr=2,Re="# >>> visa-cli shell hud v2 >>>",Te="# <<< visa-cli shell hud v2 <<<",Wr="# >>> visa-cli shell hud >>>",Jr="# <<< visa-cli shell hud <<<",un=3e4,zr=3e4;function dt(){try{return w.join(yn(),".visa-cli")}catch{return w.join(Le.tmpdir(),".visa-cli")}}function ue(){return w.join(dt(),"shell-hud.json")}function Oe(){return w.join(dt(),"shell-hud.line")}function dn(){return w.join(dt(),"shell-hud.lock")}function Ne(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 De(e){let t=yn();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 Yr(e){let t="$HOME/.visa-cli/shell-hud.line",n=ns(e),r=rs(e);if(e==="zsh")return`${Re}
33
33
  _visa_cli_shell_hud_precmd() {
34
34
  setopt localoptions no_bg_nice
35
35
  if [[ -f "${t}" ]]; then
@@ -46,7 +46,7 @@ autoload -Uz add-zsh-hook
46
46
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
47
47
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
48
48
  fi
49
- ${Ee}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Pe}
49
+ ${Te}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Re}
50
50
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
51
51
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
52
52
  }
@@ -65,7 +65,7 @@ function global:prompt {
65
65
  }
66
66
  & $function:global:__visa_cli_original_prompt
67
67
  }
68
- ${Ee}`}return`${Pe}
68
+ ${Te}`}return`${Re}
69
69
  __visa_cli_shell_hud_precmd() {
70
70
  if [ -f "${t}" ]; then
71
71
  cat "${t}"
@@ -82,33 +82,34 @@ case ";$PROMPT_COMMAND;" in
82
82
  *";__visa_cli_shell_hud_precmd;"*) ;;
83
83
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
84
84
  esac
85
- ${Ee}`}function ln(e){let t=e;for(let[n,r]of[[Pe,Ee],[Hr,Vr]])t=t.replace(new RegExp(`\\n?${sn(n)}[\\s\\S]*?${sn(r)}\\n?`,"g"),"");return t.trimEnd()}function Kr(e,t){let n=ln(e).trimEnd(),r=Br(t);return n.length>0?`${n}
85
+ ${Te}`}function fn(e){let t=e;for(let[n,r]of[[Re,Te],[Wr,Jr]])t=t.replace(new RegExp(`\\n?${cn(n)}[\\s\\S]*?${cn(r)}\\n?`,"g"),"");return t.trimEnd()}function Xr(e,t){let n=fn(e).trimEnd(),r=Yr(t);return n.length>0?`${n}
86
86
 
87
87
  ${r}
88
88
  `:`${r}
89
- `}function un(e=Le()){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=Ne(e);let n=y.existsSync(t)?y.readFileSync(t,"utf-8"):"",r=Kr(n,e),s=r!==n;return s&&Re(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}: ${gn(n)}`}}}function dn(e=Le()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Ne(e),!y.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=y.readFileSync(t,"utf-8"),r=ln(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Re(t,r.length>0?`${r}
90
- `:""),{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}: ${gn(n)}`}}}function ct(e,t){let n=Te(t.currentVersion),r=` ${L("\u2502",A.dim)} `;if(!e.enrolled)return`${L("VISA CLI",A.visaBlue)} ${L(`v${n}`,A.visaBlueSoft)}${r}${L("setup needed",A.visaGold)}`;let s=st(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),o=Math.max(0,st(e.dailySpent)),i=s>0?Math.min(s,Math.max(0,st(e.dailyRemaining??s-o))):0,a=s>0?Math.max(0,Math.min(1,o/s)):0,c=Wr(e),d=s>0?`${Gr(a)} ${L(`${ot(i)} left today`,A.green)} ${L(`(${ot(o)}/${ot(s)}/day)`,A.dim)}`:L("no spend limit",A.dim);return`${L("VISA CLI",A.visaBlue)} ${L(`v${n}`,A.visaBlueSoft)}${r}${L(c,A.visaGold)}${r}${d}`}function fn(){let e=pn();return!!e&&Date.now()-e.renderedAt<=an}function lt(){let e=pn();if(e&&Date.now()-e.renderedAt<=an||(qr(),e?.line))return e.line;try{let t=Ie();if(y.existsSync(t))return y.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function ut(e){try{let t=w.dirname(ce());y.mkdirSync(t,{recursive:!0});let n=Te(e),r={hudVersion:Ur,renderedAt:Date.now(),line:n};Re(ce(),JSON.stringify(r)+`
91
- `),Re(Ie(),n+`
92
- `)}catch{}}function ae(){try{y.unlinkSync(cn())}catch{}}function pn(){let e=ce();if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf-8"))}catch{return null}}function qr(){let e=cn();try{if(y.mkdirSync(w.dirname(e),{recursive:!0}),!Xr(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){ae();return}let n=(0,on.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",ae),n.unref()}catch{ae()}}function st(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Te(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 Gr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",A.green)}${L(s||"",A.dim)}`}function ot(e){return`$${e.toFixed(2)}`}function Wr(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=Te(n.toUpperCase()),o=Te(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Jr(){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 it=Jr(),A={reset:"\x1B[0m",visaBlue:it?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:it?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:it?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function L(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${A.reset}`}function sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mn(){let e=Ae.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function zr(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function Yr(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Xr(e){for(let t=0;t<2;t+=1){let n;try{return n=y.openSync(e,"wx"),y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=y.statSync(e);if(Date.now()-s.mtimeMs<=Fr)return!1;y.unlinkSync(e)}catch{}}finally{n!==void 0&&y.closeSync(n)}}return!1}function gn(e){return e instanceof Error?e.message:"unknown file system error"}function Re(e,t){y.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,t),y.renameSync(n,e)}async function dt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&D()){ne.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await ke();await e.registerAttestationKey(r),ne.info("attestation:key-reregistered")}catch(r){throw ne.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var R=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},hn=["GET","POST"];function yn(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 Sn(e){let t=(e??"GET").toUpperCase();if(!hn.includes(t))throw new R(`Unsupported HTTP method "${e}". Supported: ${hn.join(", ")}.`);return t}function bn(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 vn(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 m=g(require("fs")),p=g(require("path")),wn=g(require("os")),_=wn.homedir(),Zr=["Claude_","Anthropic.ClaudeDesktop_"];function _n(){return process.env.APPDATA||p.join(_,"AppData","Roaming")}function Qr(){return process.env.LOCALAPPDATA||p.join(_,"AppData","Local")}function $n(){if(process.platform!=="win32")return;let e=p.join(Qr(),"Packages");if(m.existsSync(e))try{let t=m.readdirSync(e,"utf-8");for(let n of Zr){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return p.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Cn(){if(process.platform==="win32"){let e=$n();return e?p.join(e,"claude_desktop_config.json"):p.join(_n(),"Claude","claude_desktop_config.json")}return p.join(_,"Library","Application Support","Claude","claude_desktop_config.json")}function xn(){if(process.platform!=="win32")return[p.join(_,"Library","Application Support","Claude")];let e=[p.join(_n(),"Claude")],t=$n();return t&&e.push(t),e}function De(e){return e.id==="claude-desktop"?Cn():e.globalConfigPath}function es(e){return e.id==="claude-desktop"?xn():e.detectPaths}var M=[{id:"claude",displayName:"Claude Code",globalConfigPath:p.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[p.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Cn(),configKey:"mcpServers",detectPaths:xn(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:p.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:p.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[p.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[p.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[p.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:p.join(_,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[p.join(_,".codex")],postInstallHint:"Restart Codex to connect."}];function ft(e){return M.find(t=>t.id===e)}function le(e){return es(e).some(t=>{if(t.includes("*")){let n=p.dirname(t),r=p.basename(t).replaceAll("*","");if(!m.existsSync(n))return!1;try{return m.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return m.existsSync(t)})}function kn(){return{command:"node",args:[p.resolve(__dirname,"mcp-server/index.js")]}}function pt(e,t){return t==="project"?"json":e.configFormat??"json"}function ts(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function mt(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function gt(e,t){let n=e.split(`
93
- `),r=mt(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=ts(i[2]))}return Object.keys(s).length>0?s:void 0}function ns(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
94
- `),i=mt(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
89
+ `}function pn(e=Ne()){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=De(e);let n=y.existsSync(t)?y.readFileSync(t,"utf-8"):"",r=Xr(n,e),s=r!==n;return s&&Ie(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}: ${Sn(n)}`}}}function mn(e=Ne()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=De(e),!y.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=y.readFileSync(t,"utf-8"),r=fn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Ie(t,r.length>0?`${r}
90
+ `:""),{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}: ${Sn(n)}`}}}function ft(e,t){let n=Ae(t.currentVersion),r=` ${j("\u2502",O.dim)} `;if(!e.enrolled)return`${j("VISA CLI",O.visaBlue)} ${j(`v${n}`,O.visaBlueSoft)}${r}${j("setup needed",O.visaGold)}`;let s=ct(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),o=Math.max(0,ct(e.dailySpent)),i=s>0?Math.min(s,Math.max(0,ct(e.dailyRemaining??s-o))):0,a=s>0?Math.max(0,Math.min(1,o/s)):0,c=es(e),l=s>0?`${Qr(a)} ${j(`${lt(i)} left today`,O.green)} ${j(`(${lt(o)}/${lt(s)}/day)`,O.dim)}`:j("no spend limit",O.dim);return`${j("VISA CLI",O.visaBlue)} ${j(`v${n}`,O.visaBlueSoft)}${r}${j(c,O.visaGold)}${r}${l}`}function gn(){let e=hn();return!!e&&Date.now()-e.renderedAt<=un}function pt(){let e=hn();if(e&&Date.now()-e.renderedAt<=un||(Zr(),e?.line))return e.line;try{let t=Oe();if(y.existsSync(t))return y.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function mt(e){try{let t=w.dirname(ue());y.mkdirSync(t,{recursive:!0});let n=Ae(e),r={hudVersion:Gr,renderedAt:Date.now(),line:n};Ie(ue(),JSON.stringify(r)+`
91
+ `),Ie(Oe(),n+`
92
+ `)}catch{}}function le(){try{y.unlinkSync(dn())}catch{}}function hn(){let e=ue();if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf-8"))}catch{return null}}function Zr(){let e=dn();try{if(y.mkdirSync(w.dirname(e),{recursive:!0}),!ss(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){le();return}let n=(0,ln.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",le),n.unref()}catch{le()}}function ct(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Ae(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 Qr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${j(r||"",O.green)}${j(s||"",O.dim)}`}function lt(e){return`$${e.toFixed(2)}`}function es(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=Ae(n.toUpperCase()),o=Ae(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function ts(){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 ut=ts(),O={reset:"\x1B[0m",visaBlue:ut?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ut?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ut?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function j(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${O.reset}`}function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(){let e=Le.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function ns(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function rs(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function ss(e){for(let t=0;t<2;t+=1){let n;try{return n=y.openSync(e,"wx"),y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=y.statSync(e);if(Date.now()-s.mtimeMs<=zr)return!1;y.unlinkSync(e)}catch{}}finally{n!==void 0&&y.closeSync(n)}}return!1}function Sn(e){return e instanceof Error?e.message:"unknown file system error"}function Ie(e,t){y.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,t),y.renameSync(n,e)}async function gt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&A()){se.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await Pe();await e.registerAttestationKey(r),se.info("attestation:key-reregistered")}catch(r){throw se.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var vn="1.7.0-rc.0";function W(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function N(e){return e==null?"\u2014":e?"yes":"no"}function Me(e){return e==null?"\u2014":`$${e.toFixed(2)}`}async function bn(e){let t=null,n=null;try{t=await e.api.getStatus()}catch($){n=$?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL;r.push({key:"auth.serverUrl",value:s||"https://auth.visacli.sh",formatted:s||"https://auth.visacli.sh",source:W("VISA_AUTH_URL",!!s),hint:s?void 0:"Set VISA_AUTH_URL to point at a staging or self-hosted auth server."}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:N(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let o=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:o,formatted:N(o),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:o===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:N(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:A(),formatted:N(A()),source:{kind:"device"}});let i=t?.spendingControls,a=i?i.max_transaction_amount??i.maxTransactionAmount??null:null,c=i?i.daily_limit??i.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:a,formatted:Me(a),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:c,formatted:Me(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Me(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Me(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let l=t?.cards?.find($=>$.isDefault)??t?.cards?.[0];l&&r.push({key:"cards.default",value:{brand:l.brand??null,last4:l.last4},formatted:`${l.brand||"card"} \u2022\u2022\u2022\u2022 ${l.last4}`,source:{kind:"server"}});let u=process.env.VISA_SUPPRESS_BROWSER;r.push({key:"ui.suppressBrowser",value:u==="true",formatted:N(u==="true"),source:W("VISA_SUPPRESS_BROWSER",!!u),hint:"Set to `true` to stop the CLI from opening payment URLs in your browser."});let f=process.env.VISA_SUPPRESS_FEED;r.push({key:"ui.suppressFeed",value:f==="true",formatted:N(f==="true"),source:W("VISA_SUPPRESS_FEED",!!f)});let d=K(),m;process.env.VISA_CLI_NO_UPDATE_CHECK?m={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?m={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?m={kind:"env",var:"NODE_ENV"}:m={kind:"default"},r.push({key:"ui.updateCheck",value:!d,formatted:N(!d),source:m});let v=process.env.VISA_META_TOOLS;r.push({key:"tools.meta",value:v!=="false",formatted:N(v!=="false"),source:W("VISA_META_TOOLS",v!==void 0)});let k=process.env.VISA_SPECIFIC_TOOLS;r.push({key:"tools.specific",value:k!=="false",formatted:N(k!=="false"),source:W("VISA_SPECIFIC_TOOLS",k!==void 0)});let L=process.env.VISA_DISCOVER_TOOLS;if(r.push({key:"tools.discover",value:L!=="false",formatted:N(L!=="false"),source:W("VISA_DISCOVER_TOOLS",L!==void 0)}),r.push({key:"client.version",value:vn,formatted:vn,source:{kind:"default"}}),e.includeDev){let $=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:$==="true",formatted:N($==="true"),source:W("VISA_MOCK_KEYCHAIN",!!$)});let D=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:D==="true",formatted:N(D==="true"),source:W("VISA_MOCK_TOUCHID",!!D)});let M=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!M,formatted:N(!!M),source:W("VISA_CLI_DEBUG",!!M)})}return{entries:r,statusError:n}}function os(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function wn(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${os(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
93
+ `)}function _n(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var I=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},Cn=["GET","POST"];function kn(e){let t;try{t=new URL(e)}catch{throw new I(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new I(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function $n(e){let t=(e??"GET").toUpperCase();if(!Cn.includes(t))throw new I(`Unsupported HTTP method "${e}". Supported: ${Cn.join(", ")}.`);return t}function En(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new I(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function xn(e){if(!e||typeof e!="object")throw new I("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new I("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new I("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new I(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new I("Merchant returned an empty currency.");if(t.currency.length>10)throw new I(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var g=h(require("fs")),p=h(require("path")),Pn=h(require("os")),_=Pn.homedir(),is=["Claude_","Anthropic.ClaudeDesktop_"];function Rn(){return process.env.APPDATA||p.join(_,"AppData","Roaming")}function as(){return process.env.LOCALAPPDATA||p.join(_,"AppData","Local")}function Tn(){if(process.platform!=="win32")return;let e=p.join(as(),"Packages");if(g.existsSync(e))try{let t=g.readdirSync(e,"utf-8");for(let n of is){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return p.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function An(){if(process.platform==="win32"){let e=Tn();return e?p.join(e,"claude_desktop_config.json"):p.join(Rn(),"Claude","claude_desktop_config.json")}return p.join(_,"Library","Application Support","Claude","claude_desktop_config.json")}function In(){if(process.platform!=="win32")return[p.join(_,"Library","Application Support","Claude")];let e=[p.join(Rn(),"Claude")],t=Tn();return t&&e.push(t),e}function Ue(e){return e.id==="claude-desktop"?An():e.globalConfigPath}function cs(e){return e.id==="claude-desktop"?In():e.detectPaths}var V=[{id:"claude",displayName:"Claude Code",globalConfigPath:p.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[p.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:An(),configKey:"mcpServers",detectPaths:In(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:p.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:p.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[p.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[p.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[p.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:p.join(_,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[p.join(_,".codex")],postInstallHint:"Restart Codex to connect."}];function ht(e){return V.find(t=>t.id===e)}function de(e){return cs(e).some(t=>{if(t.includes("*")){let n=p.dirname(t),r=p.basename(t).replaceAll("*","");if(!g.existsSync(n))return!1;try{return g.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return g.existsSync(t)})}function Ln(){return{command:"node",args:[p.resolve(__dirname,"mcp-server/index.js")]}}function yt(e,t){return t==="project"?"json":e.configFormat??"json"}function ls(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function St(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function vt(e,t){let n=e.split(`
94
+ `),r=St(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=ls(i[2]))}return Object.keys(s).length>0?s:void 0}function us(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
95
+ `),i=St(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
95
96
  `);return c.endsWith(`
96
97
  `)?c:c+`
97
98
  `}let a=e.trimEnd();return a+(a.length>0?`
98
99
 
99
100
  `:"")+s.join(`
100
101
  `)+`
101
- `}function rs(e,t){let n=e.split(`
102
- `),r=mt(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
102
+ `}function ds(e,t){let n=e.split(`
103
+ `),r=St(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
103
104
  `).replace(/\n{3,}/g,`
104
105
 
105
- `)):e}function ue(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e),r=p.dirname(n);m.existsSync(r)||m.mkdirSync(r,{recursive:!0});let s=pt(e,t),o=kn();if(s==="toml"){let i=m.existsSync(n)?m.readFileSync(n,"utf-8"):"",a=ns(i,"visa-cli",o);m.writeFileSync(n,a)}else{let i={};if(m.existsSync(n))try{i=JSON.parse(m.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,m.writeFileSync(n,JSON.stringify(i,null,2)+`
106
- `)}return{installed:!0,configPath:n,message:e.postInstallHint}}function ht(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e);if(!m.existsSync(n))return{removed:!1,configPath:n};if(pt(e,t)==="toml"){let i=m.readFileSync(n,"utf-8");return gt(i,"visa-cli")?(m.writeFileSync(n,rs(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(m.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],m.writeFileSync(n,JSON.stringify(s,null,2)+`
107
- `),{removed:!0,configPath:n})}function Pn(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):De(e);if(!m.existsSync(n))return!1;if(pt(e,t)==="toml")try{let s=m.readFileSync(n,"utf-8");return!!gt(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(m.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function ss(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 os(e,t){if(e===t)return!0;let n=p.resolve(e),r=p.resolve(t);if(n===r)return!0;try{let s=m.realpathSync(n),o=m.realpathSync(r);return s===o}catch{return!1}}function de(){let e=kn(),t=e.args[e.args.length-1],n=[];for(let r of M){let s=De(r);if(!m.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let d=m.readFileSync(s,"utf-8");i=gt(d,"visa-cli")}catch{continue}else{let d;try{d=JSON.parse(m.readFileSync(s,"utf-8"))}catch{continue}i=d?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=ss(i);if(!a||os(a,t))continue;let c=m.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function yt(e){return{configPath:ue(e.client,"global").configPath}}var is=(0,In.promisify)(An.execFile);function as(e,t){return process.stdin.isTTY?new Promise(n=>{let r=Rn.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 cs(e){let t=N.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
108
- ${r}: ${n(e.currentPath)}`}function Ln(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(cs(n))}var x=new En.Command,Me=null,fe=!1;function U(){return Me=new te(()=>$.getSessionToken()),Me}x.name("visa-cli").description("Visa CLI - AI payment orchestration").version(qe().version);x.hook("preAction",async()=>{await $t()});x.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=de();Ln(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=de(),n=new Map(t.map(l=>[l.client.id,l])),r=new Set;for(let l of M)if(le(l)){let h=ue(l),v=n.get(l.id),k=v?` \u2014 repaired stale ${v.staleReason} entry`:"";console.log(` \u2713 ${l.displayName} (${h.configPath.replace(N.homedir(),"~")})${k}`),v&&r.add(l.id)}let s=t.filter(l=>!r.has(l.client.id));for(let l of s)yt(l),console.log(` \u2713 ${l.client.displayName} (${l.configPath.replace(N.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(`
109
- Step 2: Checking authentication...`);let i=await $.getSessionToken();if(i)try{await new te(()=>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=Oe.randomBytes(16).toString("hex"),k=`https://auth.visacli.sh/login?state=${v}`;await xt(k);let H=3e4,V=300*1e3,B=Date.now()+V;for(;Date.now()<B;)try{let K=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:v,timeout:H}),signal:AbortSignal.timeout(H+5e3)});if(!K.ok)continue;let P=await K.json();if(P.status==="pending")continue;if(P.status==="expired"){h(new Error("Session expired. Please run setup again."));return}if(P.status==="complete"&&P.sessionToken){console.log(` Signed in as ${P.user}.`),l(P.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(`
110
- Step 3: Setting up authentication...`),!D())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await is("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 ke();console.log(" Attestation key generated."),await U().registerAttestationKey(l),console.log(" Attestation key registered with server.")}catch(l){console.log(` Skipped: ${l.message}`)}}let a=pe.join(N.homedir(),".claude","settings.json"),c=Tn.existsSync(pe.join(N.homedir(),".claude.json")),d=e.hud===!1;if(c&&!d){console.log(`
111
- 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 as(" 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=We(a),v=h.installed==="new"||h.installed==="already-visa"||h.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${v}${h.message}`);try{let k=U(),H=await k.getStatus(),V={currentVersion:k.getClientVersion(),latestVersion:k.lastSignals?.updateAvailable?.version,updateMessage:k.lastSignals?.updateAvailable?.message,updateCheckDisabled:z()},B=ct(H,V);ut(B),console.log(` Preview: ${B.split(`
106
+ `)):e}function fe(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):Ue(e),r=p.dirname(n);g.existsSync(r)||g.mkdirSync(r,{recursive:!0});let s=yt(e,t),o=Ln();if(s==="toml"){let i=g.existsSync(n)?g.readFileSync(n,"utf-8"):"",a=us(i,"visa-cli",o);g.writeFileSync(n,a)}else{let i={};if(g.existsSync(n))try{i=JSON.parse(g.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,g.writeFileSync(n,JSON.stringify(i,null,2)+`
107
+ `)}return{installed:!0,configPath:n,message:e.postInstallHint}}function bt(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):Ue(e);if(!g.existsSync(n))return{removed:!1,configPath:n};if(yt(e,t)==="toml"){let i=g.readFileSync(n,"utf-8");return vt(i,"visa-cli")?(g.writeFileSync(n,ds(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(g.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],g.writeFileSync(n,JSON.stringify(s,null,2)+`
108
+ `),{removed:!0,configPath:n})}function On(e,t="global"){let n=t==="project"?p.join(process.cwd(),".mcp.json"):Ue(e);if(!g.existsSync(n))return!1;if(yt(e,t)==="toml")try{let s=g.readFileSync(n,"utf-8");return!!vt(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(g.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function fs(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 ps(e,t){if(e===t)return!0;let n=p.resolve(e),r=p.resolve(t);if(n===r)return!0;try{let s=g.realpathSync(n),o=g.realpathSync(r);return s===o}catch{return!1}}function pe(){let e=Ln(),t=e.args[e.args.length-1],n=[];for(let r of V){let s=Ue(r);if(!g.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=g.readFileSync(s,"utf-8");i=vt(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(g.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=fs(i);if(!a||ps(a,t))continue;let c=g.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function wt(e){return{configPath:fe(e.client,"global").configPath}}var ms=(0,jn.promisify)(Un.execFile);function gs(e,t){return process.stdin.isTTY?new Promise(n=>{let r=Mn.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 hs(e){let t=H.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
109
+ ${r}: ${n(e.currentPath)}`}function Hn(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(hs(n))}var x=new Nn.Command,je=null,me=!1;function F(){return je=new re(()=>C.getSessionToken()),je}x.name("visa-cli").description("Visa CLI - AI payment orchestration").version(Je().version);x.hook("preAction",async()=>{await xt()});x.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 d=pe();Hn(d,"MCP config check:"),d.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=pe(),n=new Map(t.map(d=>[d.client.id,d])),r=new Set;for(let d of V)if(de(d)){let m=fe(d),v=n.get(d.id),k=v?` \u2014 repaired stale ${v.staleReason} entry`:"";console.log(` \u2713 ${d.displayName} (${m.configPath.replace(H.homedir(),"~")})${k}`),v&&r.add(d.id)}let s=t.filter(d=>!r.has(d.client.id));for(let d of s)wt(d),console.log(` \u2713 ${d.client.displayName} (${d.configPath.replace(H.homedir(),"~")}) \u2014 repaired stale ${d.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(`
110
+ Step 2: Checking authentication...`);let i=await C.getSessionToken();if(i)try{await new re(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(d){let m=d instanceof Error?d.message:"";m.includes("session has expired")||m.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await C.clearAll(),i=null):console.log(` Couldn't verify session (${m||"unknown error"}) \u2014 continuing with existing token.`)}if(i||(console.log(" No session found. Opening browser for GitHub login..."),i=await new Promise(async(d,m)=>{let v=He.randomBytes(16).toString("hex"),k=`https://auth.visacli.sh/login?state=${v}`;await Rt(k);let L=3e4,$=300*1e3,D=Date.now()+$;for(;Date.now()<D;)try{let M=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:v,timeout:L}),signal:AbortSignal.timeout(L+5e3)});if(!M.ok)continue;let P=await M.json();if(P.status==="pending")continue;if(P.status==="expired"){m(new Error("Session expired. Please run setup again."));return}if(P.status==="complete"&&P.sessionToken){console.log(` Signed in as ${P.user}.`),d(P.sessionToken);return}}catch{}m(new Error("Login timed out after 5 minutes. Please run setup again."))}),await C.saveSessionToken(i),console.log(" Session token saved.")),console.log(`
111
+ Step 3: Setting up authentication...`),!A())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await ms("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 d=await Pe();console.log(" Attestation key generated."),await F().registerAttestationKey(d),console.log(" Attestation key registered with server.")}catch(d){console.log(` Skipped: ${d.message}`)}}let a=ge.join(H.homedir(),".claude","settings.json"),c=Dn.existsSync(ge.join(H.homedir(),".claude.json")),l=e.hud===!1;if(c&&!l){console.log(`
112
+ 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 d;if(e.yes?(d=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?d=await gs(" Enable Visa HUD? [Y/n] ",!0):(d=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),d){let m=Ye(a),v=m.installed==="new"||m.installed==="already-visa"||m.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${v}${m.message}`);try{let k=F(),L=await k.getStatus(),$={currentVersion:k.getClientVersion(),latestVersion:k.lastSignals?.updateAvailable?.version,updateMessage:k.lastSignals?.updateAvailable?.message,updateCheckDisabled:K()},D=ft(L,$);mt(D),console.log(` Preview: ${D.split(`
112
113
  `)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let u="\x1B[1m",f="\x1B[0m";console.log(`
113
114
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
114
115
  \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
@@ -127,20 +128,20 @@ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info
127
128
  ${u}Verify:${f} visa-cli status
128
129
  ${u}HUD:${f} Restart Claude Code to see your spend pinned below the input
129
130
  ${u}Docs:${f} https://visacli.sh
130
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});x.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=de();Ln(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=de();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)yt(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(N.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
131
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});x.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=pe();Hn(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=pe();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)wt(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(H.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
131
132
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
132
133
  \x1B[1mSupported MCP Clients\x1B[0m
133
- `),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=le(a),d=Pn(a),u=c?"Yes":"No",f=d?"Yes":"No",l=a.globalConfigPath.replace(N.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${f.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(!le(a)){i.push(a.displayName);continue}ue(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(`
134
- Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ft(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!le(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=ue(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)}});x.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)ht(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(`
135
- Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=ft(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let s=ht(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)}});x.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{yn(e);let n=Sn(t.method),r=bn(t.body),s=new te(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=vn(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
136
- `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!D()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let c=Oe.randomUUID(),d=await dt(s,async()=>{let u;if(a&&D())try{let{nonce:f}=await s.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:f,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await nt(l,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:f,amount:o.amount,merchant:o.merchantName}}catch(f){throw new Error(`Touch ID confirmation failed: ${f?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:c})});if(d.success){if(console.log(`Payment complete: $${(d.amount??o.amount).toFixed(2)} \u2192 ${d.merchantName??o.merchantName}`),d.receipt?.urls?.length){console.log(`
137
- Result URLs:`);for(let u of d.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${d.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof R?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});x.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{fe=!1;try{let e=U(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:z()},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}
138
- `)}return{transactions:[]}});process.stdout.write(rn(t,Array.isArray(r?.transactions)?r.transactions:[],D(),n)),fe=!0}catch(e){fe=!1,console.error("Error:",e.message),process.exit(1)}});x.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
139
- `);try{await U().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await $.clearAll(),console.log(" Keychain credentials cleared."),D())try{await Qt(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
140
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});x.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 U().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var St=x.command("biometric").description("Manage Touch ID / biometric attestation enforcement");St.command("status").description("Show current biometric enforcement state").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await U().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=D();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});St.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=U(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});St.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await $.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=U(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!D()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await dt(t,async()=>{let s;if(n.hasAttestationKey&&D())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await nt(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var ee=x.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function Nn(){let e=un();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Dn(){let e=dn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}ee.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Nn);ee.command("enable").description("Enable the persistent shell HUD").action(Nn);ee.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Dn);ee.command("disable").description("Disable the persistent shell HUD").action(Dn);ee.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${lt()}
141
- `)});ee.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(f,l,h)=>{console.log(` ${l?"\u2713":"\u2717"} ${f}: ${h}`),l||(n=!1)};console.log(`Shell HUD Doctor
142
- `);let s=Le();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let f=Ne(s),l=e(f);if(r("RC file exists",l,f.replace(N.homedir(),"~")),l){let v=t(f,"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=ce(),i=e(o);if(r("Cache file",i,i?o.replace(N.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let f=JSON.parse(t(o,"utf-8")),l=Date.now()-(f.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=Ie(),c=e(a),d="missing";if(c)try{d=t(a,"utf-8").trim().slice(0,80)}catch{d="unreadable"}r("Line file",c,d);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 U().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(f){let l=f instanceof Error?f.message:"unknown error";r("API connectivity",!1,l)}console.log(n?`
134
+ `),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 V){let c=de(a),l=On(a),u=c?"Yes":"No",f=l?"Yes":"No",d=a.globalConfigPath.replace(H.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${f.padEnd(11)} ${d}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of V){if(!de(a)){i.push(a.displayName);continue}fe(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(`
135
+ Supported clients: ${V.map(o=>o.id).join(", ")}`),process.exit(1));let r=ht(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${V.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!de(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=fe(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)}});x.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 V)bt(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(`
136
+ Supported clients: ${V.map(o=>o.id).join(", ")}`),process.exit(1));let r=ht(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${V.map(o=>o.id).join(", ")}`),process.exit(1));let s=bt(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)}});x.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{kn(e);let n=$n(t.method),r=En(t.body),s=new re(()=>C.getSessionToken());console.log(`Checking payment for ${e}...`);let o=xn(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
137
+ `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!A()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let c=He.randomUUID(),l=await gt(s,async()=>{let u;if(a&&A())try{let{nonce:f}=await s.getAttestationChallenge(),d=Buffer.from(JSON.stringify({nonce:f,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await ot(d,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:f,amount:o.amount,merchant:o.merchantName}}catch(f){throw new Error(`Touch ID confirmation failed: ${f?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:c})});if(l.success){if(console.log(`Payment complete: $${(l.amount??o.amount).toFixed(2)} \u2192 ${l.merchantName??o.merchantName}`),l.receipt?.urls?.length){console.log(`
138
+ Result URLs:`);for(let u of l.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${l.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof I?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});x.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{me=!1;try{let e=F(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:K()},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}
139
+ `)}return{transactions:[]}});process.stdout.write(an(t,Array.isArray(r?.transactions)?r.transactions:[],A(),n)),me=!0}catch(e){me=!1,console.error("Error:",e.message),process.exit(1)}});x.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
140
+ `);try{await F().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await C.clearAll(),console.log(" Keychain credentials cleared."),A())try{await rn(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
141
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});x.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 C.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await F().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var ys=x.command("config").description("Inspect the CLI configuration");ys.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=F(),n=await bn({api:t,includeDev:!!e.dev});if(e.json){console.log(_n(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(wn(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});var _t=x.command("biometric").description("Manage Touch ID / biometric attestation enforcement");_t.command("status").description("Show current biometric enforcement state").action(async()=>{try{await C.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await F().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=A();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});_t.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await C.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=F(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});_t.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await C.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=F(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!A()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await gt(t,async()=>{let s;if(n.hasAttestationKey&&A())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await ot(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var ne=x.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function Vn(){let e=pn();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Fn(){let e=mn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}ne.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Vn);ne.command("enable").description("Enable the persistent shell HUD").action(Vn);ne.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Fn);ne.command("disable").description("Disable the persistent shell HUD").action(Fn);ne.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${pt()}
142
+ `)});ne.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(f,d,m)=>{console.log(` ${d?"\u2713":"\u2717"} ${f}: ${m}`),d||(n=!1)};console.log(`Shell HUD Doctor
143
+ `);let s=Ne();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let f=De(s),d=e(f);if(r("RC file exists",d,f.replace(H.homedir(),"~")),d){let v=t(f,"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=ue(),i=e(o);if(r("Cache file",i,i?o.replace(H.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let f=JSON.parse(t(o,"utf-8")),d=Date.now()-(f.renderedAt??0),m=Math.round(d/1e3),v=m<=30;console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${m}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Oe(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await C.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await F().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(f){let d=f instanceof Error?f.message:"unknown error";r("API connectivity",!1,d)}console.log(n?`
143
144
  All checks passed.`:`
144
- Some checks failed \u2014 see above.`),n||process.exit(1)});ee.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&&fn()))try{let t=U(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:z()},s=ct(n,r);ut(s)}catch{}finally{ae()}});x.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await Mt(),n=lt().split(`
145
- `)[0],r=await jt(n,e);process.stdout.write(`${r}
146
- `)});var Mn=x.command("hud").description("Manage the Visa HUD pinned below Claude Code input");Mn.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=pe.join(N.homedir(),".claude","settings.json"),t=We(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Mn.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=pe.join(N.homedir(),".claude","settings.json"),t=At(e);console.log(t.message),t.removed||process.exit(1)});x.hook("postAction",()=>{if(fe){fe=!1;return}Me&&tn(Me.lastSignals)});x.parse();
145
+ Some checks failed \u2014 see above.`),n||process.exit(1)});ne.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&&gn()))try{let t=F(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:K()},s=ft(n,r);mt(s)}catch{}finally{le()}});x.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await Ht(),n=pt().split(`
146
+ `)[0],r=await Ft(n,e);process.stdout.write(`${r}
147
+ `)});var Bn=x.command("hud").description("Manage the Visa HUD pinned below Claude Code input");Bn.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=ge.join(H.homedir(),".claude","settings.json"),t=Ye(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Bn.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=ge.join(H.homedir(),".claude","settings.json"),t=Nt(e);console.log(t.message),t.removed||process.exit(1)});x.hook("postAction",()=>{if(me){me=!1;return}je&&sn(je.lastSignals)});x.parse();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Tn=Object.create;var Ut=Object.defineProperty;var In=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var On=(r,e)=>()=>(r&&(e=r(r=0)),e);var Cn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pr=(r,e)=>{for(var t in e)Ut(r,t,{get:e[t],enumerable:!0})},Pn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rn(e))!En.call(r,s)&&s!==t&&Ut(r,s,{get:()=>e[s],enumerable:!(n=In(e,s))||n.enumerable});return r};var R=(r,e,t)=>(t=r!=null?Tn(An(r)):{},Pn(e||!r||!r.__esModule?Ut(t,"default",{value:r,enumerable:!0}):t,r));var fr={};pr(fr,{fetchWithTimeout:()=>Vt});async function Vt(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 Ht=On(()=>{"use strict"});var fn=Cn((Do,vi)=>{vi.exports={name:"@visa/cli",version:"1.6.0-rc.4",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"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var vn=require("@modelcontextprotocol/sdk/server/index.js"),bn=require("@modelcontextprotocol/sdk/server/stdio.js"),se=require("@modelcontextprotocol/sdk/types.js");Ht();var Nn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ht(r,e){let t=hr(r),n=hr(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:$n(t.pre,n.pre)>0}function hr(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(Nn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function $n(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),u=/^\d+$/.test(o);if(c&&u){let m=Number(i)-Number(o);if(m!==0)return m}else{if(c)return-1;if(u)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function gt(){return!!(gr(process.env.VISA_CLI_NO_UPDATE_CHECK)||gr(process.env.CI)||process.env.NODE_ENV==="test")}function gr(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var Ft="1.6.0-rc.4",yt=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={},!gt()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&ht(n,Ft)&&(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 Ft}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 Vt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":Ft},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(m){throw m.name==="AbortError"||m.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 m=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}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 u;try{u=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(u?.error||`Request failed (${c.status}). Try again.`);return u}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 setBiometricPreference(e,t){return this.request("POST","/v1/biometric-preference",{...e,confirm:!0},void 0,t)}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 Gt=require("child_process"),xr=require("util"),Sr=R(require("crypto")),$=R(require("fs")),kr=R(require("os")),J=R(require("path"));var D=R(require("fs")),zt=R(require("path")),yr=R(require("os")),Wt=zt.join(yr.homedir(),".visa-mcp"),Qe=zt.join(Wt,"mcp-server.log"),Ln=5*1024*1024,Bt=null;function jn(){D.existsSync(Wt)||D.mkdirSync(Wt,{recursive:!0,mode:448})}function Mn(){if(!Bt){if(jn(),D.existsSync(Qe)&&D.statSync(Qe).size>Ln){let e=Qe+".1";D.existsSync(e)&&D.unlinkSync(e),D.renameSync(Qe,e)}Bt=D.createWriteStream(Qe,{flags:"a"})}return Bt}function _t(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}
2
+ "use strict";var Tn=Object.create;var Ut=Object.defineProperty;var In=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var An=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var On=(r,e)=>()=>(r&&(e=r(r=0)),e);var Cn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pr=(r,e)=>{for(var t in e)Ut(r,t,{get:e[t],enumerable:!0})},Pn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rn(e))!En.call(r,s)&&s!==t&&Ut(r,s,{get:()=>e[s],enumerable:!(n=In(e,s))||n.enumerable});return r};var R=(r,e,t)=>(t=r!=null?Tn(An(r)):{},Pn(e||!r||!r.__esModule?Ut(t,"default",{value:r,enumerable:!0}):t,r));var fr={};pr(fr,{fetchWithTimeout:()=>Vt});async function Vt(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 Ht=On(()=>{"use strict"});var fn=Cn((Do,vi)=>{vi.exports={name:"@visa/cli",version:"1.7.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"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var vn=require("@modelcontextprotocol/sdk/server/index.js"),bn=require("@modelcontextprotocol/sdk/server/stdio.js"),se=require("@modelcontextprotocol/sdk/types.js");Ht();var Nn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ht(r,e){let t=hr(r),n=hr(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:$n(t.pre,n.pre)>0}function hr(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(Nn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function $n(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),u=/^\d+$/.test(o);if(c&&u){let m=Number(i)-Number(o);if(m!==0)return m}else{if(c)return-1;if(u)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function gt(){return!!(gr(process.env.VISA_CLI_NO_UPDATE_CHECK)||gr(process.env.CI)||process.env.NODE_ENV==="test")}function gr(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var Ft="1.7.0-rc.0",yt=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={},!gt()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&ht(n,Ft)&&(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 Ft}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 Vt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":Ft},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(m){throw m.name==="AbortError"||m.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 m=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}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 u;try{u=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(u?.error||`Request failed (${c.status}). Try again.`);return u}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 setBiometricPreference(e,t){return this.request("POST","/v1/biometric-preference",{...e,confirm:!0},void 0,t)}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 Gt=require("child_process"),xr=require("util"),Sr=R(require("crypto")),$=R(require("fs")),kr=R(require("os")),J=R(require("path"));var D=R(require("fs")),zt=R(require("path")),yr=R(require("os")),Wt=zt.join(yr.homedir(),".visa-mcp"),Qe=zt.join(Wt,"mcp-server.log"),Ln=5*1024*1024,Bt=null;function jn(){D.existsSync(Wt)||D.mkdirSync(Wt,{recursive:!0,mode:448})}function Mn(){if(!Bt){if(jn(),D.existsSync(Qe)&&D.statSync(Qe).size>Ln){let e=Qe+".1";D.existsSync(e)&&D.unlinkSync(e),D.renameSync(Qe,e)}Bt=D.createWriteStream(Qe,{flags:"a"})}return Bt}function _t(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),Mn().write(s)}var l={debug:(...r)=>_t("DEBUG",...r),info:(...r)=>_t("INFO",...r),warn:(...r)=>_t("WARN",...r),error:(...r)=>_t("ERROR",...r)};var Ve=(0,xr.promisify)(Gt.execFile),wt=J.join(kr.homedir(),".visa-mcp","bin"),ve=J.join(wt,"Visa CLI"),qn=J.join(__dirname,"..","native"),_r="5",vr=J.join(wt,"visa-keychain.version"),br=J.join(wt,"visa-keychain.sha256");function wr(r){let e=$.readFileSync(r);return Sr.createHash("sha256").update(e).digest("hex")}async function Tr(){try{if($.readFileSync(vr,"utf-8").trim()===_r&&$.existsSync(ve)){let n=$.readFileSync(br,"utf-8").trim();if(wr(ve)!==n)l.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),$.unlinkSync(ve);else return ve}}catch{}let r=J.join(qn,"visa-keychain.m");if($.existsSync(r)||(r=J.resolve(__dirname,"..","..","native","visa-keychain.m")),$.existsSync(r)||(r=J.resolve(__dirname,"..","native","visa-keychain.m")),!$.existsSync(r))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");$.mkdirSync(wt,{recursive:!0,mode:448});try{await Ve("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",ve,r],{timeout:3e4})}catch(t){throw t.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):t}let e=wr(ve);return $.writeFileSync(br,e,{mode:384}),$.writeFileSync(vr,_r,{mode:384}),ve}async function Ir(r){let e=await Tr(),t;try{t=(await Ve(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 Zt=null;function He(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Zt!==null?Zt:(Zt=!0,!0)}var vt="visa-cli",bt="attestation-key";async function Dn(r){try{await Ve("security",["delete-generic-password","-s",vt,"-a",bt],{timeout:5e3})}catch{}await Ve("security",["add-generic-password","-s",vt,"-a",bt,"-w",r],{timeout:5e3})}async function Un(){try{let{stdout:r}=await Ve("security",["find-generic-password","-s",vt,"-a",bt,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Rr(){let r=await Ir(["generate-key"]);if(!r)throw new Error("Key generation returned no output");let e=r.indexOf(":");if(e<0)throw new Error("Unexpected generate-key output format");let t=r.slice(0,e),n=r.slice(e+1);return await Dn(t),n}async function Ar(r,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let t=await Un();if(!t)throw new Error("Attestation key not found. Run setup to generate a new key.");let n=await Tr(),s=["sign",r];return e&&s.push(e),new Promise((a,i)=>{let o=(0,Gt.execFile)(n,s,{timeout:6e4},(c,u)=>{let m=(u||"").trim();if(c){m.startsWith("ERROR:")?i(new Error(m.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}m.startsWith("OK:")?a(m.slice(3)):i(new Error(m.startsWith("ERROR:")?m.slice(6):"Unknown error"))});o.stdin.write(t),o.stdin.end()})}async function Er(){try{await Ve("security",["delete-generic-password","-s",vt,"-a",bt],{timeout:5e3})}catch{}try{await Ir(["delete-key"])}catch{}}var kt=require("child_process"),Cr=require("util"),me=R(require("fs")),Tt=R(require("os")),Xt=R(require("path")),X=(0,Cr.promisify)(kt.execFile),Qt=Xt.join(Tt.homedir(),".visa-mcp"),xt=Xt.join(Qt,"session-token"),B="visa-cli",de="session-token",St="rc-access",Vn=5e3;async function Hn(){try{let{stdout:r}=await X("security",["find-generic-password","-s",B,"-a",de,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Fn(r){try{try{await X("security",["delete-generic-password","-s",B,"-a",de],{timeout:5e3})}catch{}return await X("security",["add-generic-password","-s",B,"-a",de,"-w",r],{timeout:5e3}),!0}catch{return!1}}async function Bn(){try{await X("security",["delete-generic-password","-s",B,"-a",de],{timeout:5e3})}catch{}}async function Wn(){if(!er())return null;try{let{stdout:r}=await X("secret-tool",["lookup","service",B,"account",de],{timeout:5e3});return r.trim()||null}catch{return null}}async function zn(r){if(!er())return!1;try{let e=(0,kt.execFile)("secret-tool",["store","--label",`${B} ${de}`,"service",B,"account",de]);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"))},Vn))]),!0):!1}catch{return!1}}async function Zn(){if(er())try{await X("secret-tool",["clear","service",B,"account",de],{timeout:5e3})}catch{}}function er(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Gn(){try{let{stdout:r}=await X("security",["find-generic-password","-s",B,"-a",St,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Kn(r){try{try{await X("security",["delete-generic-password","-s",B,"-a",St],{timeout:5e3})}catch{}await X("security",["add-generic-password","-s",B,"-a",St,"-w",r],{timeout:5e3})}catch{}}async function Yn(){try{await X("security",["delete-generic-password","-s",B,"-a",St],{timeout:5e3})}catch{}}function Yt(){try{return me.readFileSync(xt,"utf-8").trim()||null}catch{return null}}function Pr(r){me.mkdirSync(Qt,{recursive:!0,mode:448}),me.writeFileSync(xt,r,{mode:384}),process.platform==="win32"&&Jn(xt)}function Jt(){try{me.unlinkSync(xt)}catch{}}function Jn(r){try{let e=Tt.userInfo().username;(0,kt.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 Kt(){switch(process.platform){case"darwin":return{get:Hn,store:Fn,delete:Bn};case"linux":return{get:Wn,store:zn,delete:Zn};default:return{get:async()=>Yt(),store:async r=>{try{return Pr(r),!0}catch{return!1}},delete:async()=>Jt()}}}var j=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=Kt(),t=await e.get();if(t)return t;let n=Yt();return n?(await e.store(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let t=Kt();if(await t.store(e)){if(await t.get()===e){Jt();return}await t.delete()}if(Pr(e),Yt()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Qt} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Gn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Kn(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Kt().delete(),Jt()}static async clearAll(){await this.deleteSessionToken(),await Yn()}};var It={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 et(){return process.env.VISA_SPECIFIC_TOOLS!=="false"}function tt(){return process.env.VISA_META_TOOLS!=="false"}function rt(){return process.env.VISA_DISCOVER_TOOLS!=="false"}function Nr(r){let e=It[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 $r(r){let e=It[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 Rt(r,e){if(!be.includes(r))return r;let t=It[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 Lr(r,e,t){let n=Rt(r,e.tier),{tier:s,...a}=e;return E.executeTool({tool_id:n,...a},t)}var be=Object.keys(It);function jr(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 Mr(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 at=R(require("crypto")),Vr=require("child_process"),F=R(require("fs")),it=R(require("os")),ot=R(require("path"));var Xn="# visa-cli-hud-v1";function At(r){return typeof r!="string"?!1:r.includes(Xn)?!0:r.includes("visa-cli")&&r.includes("statusline")}async function qr(r,e){try{return await e()}catch(t){if(t.message==="Invalid signature"&&He()){l.warn("attestation:key-mismatch",{action:"reregistering"});try{let n=await Rr();await r.registerAttestationKey(n),l.info("attestation:key-reregistered")}catch(n){throw l.error("attestation:reregister-failure",{error:n.message}),t}return await e()}throw t}}var Et=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",x=new yt(()=>j.getSessionToken()),Qn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Dr=["","","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:",...Qn.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 H(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=jr();if(n.headless){l.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let s=Mr(t);if(!s){l.info(`No browser command for platform "${it.platform()}". URL: ${t}`);return}(0,Vr.execFile)(s.cmd,s.args,a=>{a&&l.warn(`Browser open failed: ${a.message}. URL: ${t}`)})}async function M(r){return qr(x,r)}var nt=null,es=3e4;function Hr(){nt=null}async function ts(r){let e=Date.now();if(nt&&nt.expiresAt>e)return nt.value;try{let n=(await x.getStatus(r)).attestationRequired!==!1;return nt={value:n,expiresAt:e+es},n}catch{return!0}}async function P(r,e,t,n,s){if(!He()){l.warn("attestation:unavailable",{context:r});return}if(!await ts(s)){l.info("attestation:skipped-by-server-policy",{context:r});return}l.info("attestation:attempt",{context:r,amount:e,merchant:t});try{let{nonce:i}=await x.getAttestationChallenge(),o=Buffer.from(JSON.stringify({nonce:i,amount:e,merchant:t,context:r})).toString("base64");l.info("touchid:prompt",{context:r,amount:e,merchant:t});let c=await Ar(o,n);return l.info("attestation:success",{context:r,amount:e,merchant:t}),{signature:c,nonce:i,amount:e,merchant:t}}catch(i){throw l.error("attestation:failure",{context:r,amount:e,merchant:t,error:i.message}),i}}async function G(r,e,t){let n=await x.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 Q(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 Fr(){return ot.join(it.homedir(),".visa-mcp","allium-results")}var rs=16*1024,ns=50*1024*1024,ss=10;function as(r){return r.replace(/[^A-Za-z0-9_\-]/g,"_").slice(0,128)}function is(r,e){let t=Fr();F.mkdirSync(t,{recursive:!0});let n=as(r),s=ot.join(t,`${n}.csv`);F.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 l.error("catalog:discover:error",{error:e.message}),new Error(`Failed to search tool catalog: ${e.message}`)}}async function Fs(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.");l.info("catalog:execute",{tool:t});let i=await G(t,void 0,e);l.info("payment:attempt",{tool:t,amount:i.amount,merchant:i.merchantName});try{return await M(async()=>{let o=await P(t,i.amount,i.merchantName,Q(i)),c=await x.shortcut(t,{...a,attestation:o},12e4,e);if(l.info("payment:success",{tool:t,amount:i.amount,merchant:i.merchantName}),c.urls?.length){c.urls.forEach(m=>H(m));let u=c.mediaType||(c.urls[0]?.match(/\.(mp4|webm|mov)/)?"video":"image");ct({prompt:a.prompt||`${t} execution`,tool:t,mediaUrl:c.urls[0],mediaType:u,cost:c.amount??i.amount,transactionId:c.transactionId,userContext:e})}return c})}catch(o){throw l.error("payment:failure",{tool:t,amount:i.amount,merchant:i.merchantName,error:o.message}),o}}var E=class{static async getStatus(e){return Rs(e)}static async pay(e,t){return cs(e,t)}static async getCards(e){return As(e)}static async transactionHistory(e){return Es(e)}static async feedback(e,t){return Os(e,t)}static async updateSpendingControls(e,t){return Cs(e,t)}static async biometricStatus(e){return Ps(e)}static async biometricOn(e){return Ns(e)}static async biometricOff(e,t){return $s(e,t)}static async reset(e,t){return Us(e,t)}static async login(e){return qs(e)}static async addCard(e){return Ds(e)}static async removeCard(e,t){return js(e,t)}static async setDefaultCard(e,t){return Ms(e,t)}static async batch(e,t){return Ts(e,t)}static async discoverTools(e){return Hs(e)}static async executeTool(e,t){return Fs(e,t)}static async shortcut(e,t,n){switch(e){case"generate_image_card":return us(t,n);case"generate_image_fast_card":return ls(t,n);case"generate_video_tempo_card":return ds(t,n);case"generate_music_tempo_card":return ms(t,n);case"check_music_status_tempo_card":return ps(t,n);case"query_onchain_prices_card":return fs(t,n);case"allium_explorer_card":return hs(t,n);case"allium_explorer_results_card":return gs(t,n);case"pxlwall_card":return _s(t,n);default:{l.info("payment:attempt",{tool:e});try{let s=await P(e,0,""),a=await x.shortcut(e,{...t,attestation:s},void 0,n);return l.info("payment:success",{tool:e}),a.urls?.length&&a.urls.forEach(i=>H(i)),a}catch(s){throw l.error("payment:failure",{tool:e,error:s.message}),s}}}}static async submitFeedback(e,t,n){l.info("feedback:submit",{length:e.length});try{let s=await x.submitFeedback(e,t,n);return l.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw l.error("feedback:error",{error:a}),s}}static async getFeedback(e,t){l.info("feedback:list",{limit:e||20});try{let n=await x.getFeedback(e,t);return l.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let s=n instanceof Error?n.message:"Unknown error";throw l.error("feedback:error",{error:s}),n}}};var tr=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"]),rr=new Set(["discover_tools","execute_tool"]),Bs=new Set(be);function Wr(r){return tr.has(r)&&!et()?"VISA_SPECIFIC_TOOLS":rr.has(r)&&!rt()?"VISA_DISCOVER_TOOLS":Bs.has(r)&&!tt()?"VISA_META_TOOLS":null}var Ot=R(require("fs")),zr=R(require("path")),Zr=R(require("os"));var nr=zr.join(Zr.homedir(),".visa-mcp"),pe=class{static ensureConfigDir(){Ot.existsSync(nr)||Ot.mkdirSync(nr,{recursive:!0,mode:448})}static getConfigDir(){return nr}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 sr=["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"],Ws={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 zs(r){return Ws[r]||r}var we=null;async function Ct(r){if(we!==null)return we;try{let{transactions:e}=await r.getTransactions();we={};for(let t of e)t.status==="completed"&&(we[t.tool_name]=(we[t.tool_name]||0)+1)}catch{l.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),we={}}return we}function Gr(r,e,t){return sr.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${zs(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 ut=R(require("fs")),Kr=R(require("path"));var Zs=5,Gs={shownCodes:[]},xe=null;function Yr(){return process.env.VISA_CLI_REFERRAL_NUDGE_FILE||Kr.join(pe.getConfigDir(),"referral-nudges.json")}function Ks(){if(xe)return xe;try{let r=ut.readFileSync(Yr(),"utf8"),e=JSON.parse(r);return xe={shownCodes:Array.isArray(e.shownCodes)?e.shownCodes.filter(t=>typeof t=="string"):[]},xe}catch{return xe={...Gs},xe}}function Ys(r){xe=r;try{pe.ensureConfigDir(),ut.writeFileSync(Yr(),JSON.stringify(r,null,2)+`
17
- `,{mode:384})}catch{}}function Js(r){return r.trim().toLowerCase()}function Jr(r,e){if(e<Zs)return{};if(!r.referralCode||!r.referralLink)return{};let t=Js(r.referralCode);if(!t)return{};let n=Ks();return n.shownCodes.includes(t)?{}:(Ys({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 T={};pr(T,{BRAND:()=>Sa,DIRTY:()=>Se,EMPTY_PATH:()=>ta,INVALID:()=>g,NEVER:()=>oi,OK:()=>L,ParseStatus:()=>N,Schema:()=>w,ZodAny:()=>ge,ZodArray:()=>le,ZodBigInt:()=>Te,ZodBoolean:()=>Ie,ZodBranded:()=>dt,ZodCatch:()=>Me,ZodDate:()=>Re,ZodDefault:()=>je,ZodDiscriminatedUnion:()=>$t,ZodEffects:()=>Z,ZodEnum:()=>$e,ZodError:()=>U,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>jt,ZodIntersection:()=>Ce,ZodIssueCode:()=>d,ZodLazy:()=>Pe,ZodLiteral:()=>Ne,ZodMap:()=>Ge,ZodNaN:()=>Ye,ZodNativeEnum:()=>Le,ZodNever:()=>K,ZodNull:()=>Ee,ZodNullable:()=>re,ZodNumber:()=>ke,ZodObject:()=>V,ZodOptional:()=>W,ZodParsedType:()=>f,ZodPipeline:()=>mt,ZodPromise:()=>ye,ZodReadonly:()=>qe,ZodRecord:()=>Lt,ZodSchema:()=>w,ZodSet:()=>Ke,ZodString:()=>he,ZodSymbol:()=>ze,ZodTransformer:()=>Z,ZodTuple:()=>te,ZodType:()=>w,ZodUndefined:()=>Ae,ZodUnion:()=>Oe,ZodUnknown:()=>ue,ZodVoid:()=>Ze,addIssueToContext:()=>p,any:()=>Pa,array:()=>ja,bigint:()=>Ra,boolean:()=>un,coerce:()=>ii,custom:()=>an,date:()=>Aa,datetimeRegex:()=>nn,defaultErrorMap:()=>oe,discriminatedUnion:()=>Ua,effect:()=>Xa,enum:()=>Ka,function:()=>za,getErrorMap:()=>Fe,getParsedType:()=>ee,instanceof:()=>Ta,intersection:()=>Va,isAborted:()=>Pt,isAsync:()=>Be,isDirty:()=>Nt,isValid:()=>fe,late:()=>ka,lazy:()=>Za,literal:()=>Ga,makeIssue:()=>lt,map:()=>Ba,nan:()=>Ia,nativeEnum:()=>Ya,never:()=>$a,null:()=>Ca,nullable:()=>ei,number:()=>cn,object:()=>Ma,objectUtil:()=>ar,oboolean:()=>ai,onumber:()=>si,optional:()=>Qa,ostring:()=>ni,pipeline:()=>ri,preprocess:()=>ti,promise:()=>Ja,quotelessJson:()=>Xs,record:()=>Fa,set:()=>Wa,setErrorMap:()=>ea,strictObject:()=>qa,string:()=>on,symbol:()=>Ea,transformer:()=>Xa,tuple:()=>Ha,undefined:()=>Oa,union:()=>Da,unknown:()=>Na,util:()=>k,void:()=>La});var k;(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})(k||(k={}));var ar;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ar||(ar={}));var f=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=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=k.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"]),Xs=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 u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],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,k.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 Qs=(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,k.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${k.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${k.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${k.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}"`:k.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,k.assertNever(r)}return{message:t}},oe=Qs;var Xr=oe;function ea(r){Xr=r}function Fe(){return Xr}var lt=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(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},ta=[];function p(r,e){let t=Fe(),n=lt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===oe?void 0:oe].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"}),Se=r=>({status:"dirty",value:r}),L=r=>({status:"valid",value:r}),Pt=r=>r.status==="aborted",Nt=r=>r.status==="dirty",fe=r=>r.status==="valid",Be=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 z=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}},Qr=(r,e)=>{if(fe(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 b(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 w=class{get description(){return this._def.description}_getType(e){return ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(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:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Be(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:ee(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Qr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return fe(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=>fe(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:ee(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Be(s)?s:Promise.resolve(s));return Qr(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 Z({schema:this,typeName:y.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 W.create(this,this._def)}nullable(){return re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return ye.create(this,this._def)}or(e){return Oe.create([this,e],this._def)}and(e){return Ce.create(this,e,this._def)}transform(e){return new Z({...b(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new je({...b(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new dt({typeName:y.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Me({...b(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return mt.create(this,e)}readonly(){return qe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ra=/^c[^\s-]{8,}$/i,na=/^[0-9a-z]+$/,sa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aa=/^[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,ia=/^[a-z0-9_-]{21}$/i,oa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ca=/^[-+]?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)?)??$/,ua=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,la="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ir,da=/^(?:(?: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])$/,ma=/^(?:(?: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])$/,pa=/^(([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]))$/,fa=/^(([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])$/,ha=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ga=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tn="((\\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])))",ya=new RegExp(`^${tn}$`);function rn(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 _a(r){return new RegExp(`^${rn(r)}$`)}function nn(r){let e=`${tn}T${rn(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 va(r,e){return!!((e==="v4"||!e)&&da.test(r)||(e==="v6"||!e)&&pa.test(r))}function ba(r,e){if(!oa.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 wa(r,e){return!!((e==="v4"||!e)&&ma.test(r)||(e==="v6"||!e)&&fa.test(r))}var he=class r extends w{_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")ua.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")ir||(ir=new RegExp(la,"u")),ir.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")aa.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")ia.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")ra.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")na.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")sa.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"?nn(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"?ya.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?_a(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"?ca.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?va(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"?ba(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"?wa(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"?ha.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?ga.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):k.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}};he.create=r=>new he({checks:[],typeName:y.ZodString,coerce:r?.coerce??!1,...b(r)});function xa(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 ke=class r extends w{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"?k.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"?xa(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()):k.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"&&k.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)}};ke.create=r=>new ke({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Te=class r extends w{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()):k.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}};Te.create=r=>new Te({checks:[],typeName:y.ZodBigInt,coerce:r?.coerce??!1,...b(r)});var Ie=class extends w{_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 L(e.data)}};Ie.create=r=>new Ie({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Re=class r extends w{_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()):k.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}};Re.create=r=>new Re({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...b(r)});var ze=class extends w{_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 L(e.data)}};ze.create=r=>new ze({typeName:y.ZodSymbol,...b(r)});var Ae=class extends w{_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 L(e.data)}};Ae.create=r=>new Ae({typeName:y.ZodUndefined,...b(r)});var Ee=class extends w{_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 L(e.data)}};Ee.create=r=>new Ee({typeName:y.ZodNull,...b(r)});var ge=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}};ge.create=r=>new ge({typeName:y.ZodAny,...b(r)});var ue=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}};ue.create=r=>new ue({typeName:y.ZodUnknown,...b(r)});var K=class extends w{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};K.create=r=>new K({typeName:y.ZodNever,...b(r)});var Ze=class extends w{_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 L(e.data)}};Ze.create=r=>new Ze({typeName:y.ZodVoid,...b(r)});var le=class r extends w{_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 z(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new z(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)}};le.create=(r,e)=>new le({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...b(e)});function We(r){if(r instanceof V){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=W.create(We(n))}return new V({...r._def,shape:()=>e})}else return r instanceof le?new le({...r._def,type:We(r.element)}):r instanceof W?W.create(We(r.unwrap())):r instanceof re?re.create(We(r.unwrap())):r instanceof te?te.create(r.items.map(e=>We(e))):r}var V=class r extends w{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=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:d.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof K&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let m=a[u],_=s.data[u];c.push({key:{status:"valid",value:u},value:m._parse(new z(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof K){let u=this._def.unknownKeys;if(u==="passthrough")for(let m of o)c.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(u==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let m of o){let _=s.data[m];c.push({key:{status:"valid",value:m},value:u._parse(new z(s,_,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let m of c){let _=await m.key,O=await m.value;u.push({key:_,value:O,alwaysSet:m.alwaysSet})}return u}).then(u=>N.mergeObjectSync(n,u)):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:y.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 k.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 k.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return We(this)}partial(e){let t={};for(let n of k.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 k.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof W;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return sn(k.objectKeys(this.shape))}};V.create=(r,e)=>new V({shape:()=>r,unknownKeys:"strip",catchall:K.create(),typeName:y.ZodObject,...b(e)});V.strictCreate=(r,e)=>new V({shape:()=>r,unknownKeys:"strict",catchall:K.create(),typeName:y.ZodObject,...b(e)});V.lazycreate=(r,e)=>new V({shape:r,unknownKeys:"strip",catchall:K.create(),typeName:y.ZodObject,...b(e)});var Oe=class extends w{_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 u={...t,common:{...t.common,issues:[]},parent:null},m=c._parseSync({data:t.data,path:t.path,parent:u});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:u}),u.common.issues.length&&i.push(u.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}};Oe.create=(r,e)=>new Oe({options:r,typeName:y.ZodUnion,...b(e)});var ce=r=>r instanceof Pe?ce(r.schema):r instanceof Z?ce(r.innerType()):r instanceof Ne?[r.value]:r instanceof $e?r.options:r instanceof Le?k.objectValues(r.enum):r instanceof je?ce(r._def.innerType):r instanceof Ae?[void 0]:r instanceof Ee?[null]:r instanceof W?[void 0,...ce(r.unwrap())]:r instanceof re?[null,...ce(r.unwrap())]:r instanceof dt||r instanceof qe?ce(r.unwrap()):r instanceof Me?ce(r._def.innerType):[],$t=class r extends w{_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=ce(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:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...b(n)})}};function or(r,e){let t=ee(r),n=ee(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=k.objectKeys(e),a=k.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=or(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=or(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 Ce=class extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Pt(a)||Pt(i))return g;let o=or(a.value,i.value);return o.valid?((Nt(a)||Nt(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}))}};Ce.create=(r,e,t)=>new Ce({left:r,right:e,typeName:y.ZodIntersection,...b(t)});var te=class r extends w{_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 z(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})}};te.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new te({items:r,typeName:y.ZodTuple,rest:null,...b(e)})};var Lt=class r extends w{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 z(n,o,n.path,o)),value:i._parse(new z(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 w?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...b(n)}):new r({keyType:he.create(),valueType:e,typeName:y.ZodRecord,...b(t)})}},Ge=class extends w{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],u)=>({key:s._parse(new z(n,o,n.path,[u,"key"])),value:a._parse(new z(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,m=await c.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),o.set(u.value,m.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,m=c.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),o.set(u.value,m.value)}return{status:t.value,value:o}}}};Ge.create=(r,e,t)=>new Ge({valueType:e,keyType:r,typeName:y.ZodMap,...b(t)});var Ke=class r extends w{_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 u=new Set;for(let m of c){if(m.status==="aborted")return g;m.status==="dirty"&&t.dirty(),u.add(m.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new z(n,c,n.path,u)));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)}};Ke.create=(r,e)=>new Ke({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...b(e)});var jt=class r extends w{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 lt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Fe(),oe].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return lt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Fe(),oe].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ye){let o=this;return L(async function(...c){let u=new U([]),m=await o._def.args.parseAsync(c,a).catch(v=>{throw u.addIssue(n(c,v)),u}),_=await Reflect.apply(i,this,m);return await o._def.returns._def.type.parseAsync(_,a).catch(v=>{throw u.addIssue(s(_,v)),u})})}else{let o=this;return L(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new U([n(c,u.error)]);let m=Reflect.apply(i,this,u.data),_=o._def.returns.safeParse(m,a);if(!_.success)throw new U([s(m,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:te.create(e).rest(ue.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||te.create([]).rest(ue.create()),returns:t||ue.create(),typeName:y.ZodFunction,...b(n)})}},Pe=class extends w{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})}};Pe.create=(r,e)=>new Pe({getter:r,typeName:y.ZodLazy,...b(e)});var Ne=class extends w{_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}};Ne.create=(r,e)=>new Ne({value:r,typeName:y.ZodLiteral,...b(e)});function sn(r,e){return new $e({values:r,typeName:y.ZodEnum,...b(e)})}var $e=class r extends w{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:k.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 L(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})}};$e.create=sn;var Le=class extends w{_parse(e){let t=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=k.objectValues(t);return p(n,{expected:k.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=k.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return L(e.data)}get enum(){return this._def.values}};Le.create=(r,e)=>new Le({values:r,typeName:y.ZodNativeEnum,...b(e)});var ye=class extends w{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 L(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ye.create=(r,e)=>new ye({type:r,typeName:y.ZodPromise,...b(e)});var Z=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.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"?Se(c.value):t.value==="dirty"?Se(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"?Se(o.value):t.value==="dirty"?Se(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(!fe(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=>fe(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);k.assertNever(s)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:y.ZodEffects,effect:e,...b(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...b(t)});var W=class extends w{_parse(e){return this._getType(e)===f.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};W.create=(r,e)=>new W({innerType:r,typeName:y.ZodOptional,...b(e)});var re=class extends w{_parse(e){return this._getType(e)===f.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};re.create=(r,e)=>new re({innerType:r,typeName:y.ZodNullable,...b(e)});var je=class extends w{_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}};je.create=(r,e)=>new je({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var Me=class extends w{_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 Be(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}};Me.create=(r,e)=>new Me({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var Ye=class extends w{_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}}};Ye.create=r=>new Ye({typeName:y.ZodNaN,...b(r)});var Sa=Symbol("zod_brand"),dt=class extends w{_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}},mt=class r extends w{_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(),Se(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:y.ZodPipeline})}},qe=class extends w{_parse(e){let t=this._def.innerType._parse(e),n=s=>(fe(s)&&(s.value=Object.freeze(s.value)),s);return Be(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};qe.create=(r,e)=>new qe({innerType:r,typeName:y.ZodReadonly,...b(e)});function en(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function an(r,e={},t){return r?ge.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=en(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=en(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):ge.create()}var ka={object:V.lazycreate},y;(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"})(y||(y={}));var Ta=(r,e={message:`Input not instance of ${r.name}`})=>an(t=>t instanceof r,e),on=he.create,cn=ke.create,Ia=Ye.create,Ra=Te.create,un=Ie.create,Aa=Re.create,Ea=ze.create,Oa=Ae.create,Ca=Ee.create,Pa=ge.create,Na=ue.create,$a=K.create,La=Ze.create,ja=le.create,Ma=V.create,qa=V.strictCreate,Da=Oe.create,Ua=$t.create,Va=Ce.create,Ha=te.create,Fa=Lt.create,Ba=Ge.create,Wa=Ke.create,za=jt.create,Za=Pe.create,Ga=Ne.create,Ka=$e.create,Ya=Le.create,Ja=ye.create,Xa=Z.create,Qa=W.create,ei=re.create,ti=Z.createWithPreprocess,ri=mt.create,ni=()=>on().optional(),si=()=>cn().optional(),ai=()=>un().optional(),ii={string:(r=>he.create({...r,coerce:!0})),number:(r=>ke.create({...r,coerce:!0})),boolean:(r=>Ie.create({...r,coerce:!0})),bigint:(r=>Te.create({...r,coerce:!0})),date:(r=>Re.create({...r,coerce:!0}))};var oi=g;var ln="1.6.0-rc.4",dn=T.object({name:T.string().max(100).nullable(),location:T.string().max(100).nullable(),member_since:T.string()}),mn=T.object({total_transactions:T.number(),total_spent:T.number(),tools_used:T.record(T.string(),T.number()),last_active:T.string().nullable(),themes:T.array(T.string().max(100)).max(20),recent_prompts:T.array(T.string().max(500)).max(50).optional().default([])}),pn=T.object({daily_remaining:T.number(),daily_limit:T.number()}),ci=T.object({message:T.string().max(500),tool:T.string(),reason:T.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),ui=T.object({proactive:ci,reactive:T.record(T.string(),T.array(T.string().max(500)).nullable())}),li=T.object({user:dn,usage:mn,budget:pn,suggestions:ui}),di=T.object({user:dn,usage:mn,budget:pn});function mi(r){let e=li.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=di.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function De(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 pi=`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 Js(r){return r.trim().toLowerCase()}function Jr(r,e){if(e<Zs)return{};if(!r.referralCode||!r.referralLink)return{};let t=Js(r.referralCode);if(!t)return{};let n=Ks();return n.shownCodes.includes(t)?{}:(Ys({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 T={};pr(T,{BRAND:()=>Sa,DIRTY:()=>Se,EMPTY_PATH:()=>ta,INVALID:()=>g,NEVER:()=>oi,OK:()=>L,ParseStatus:()=>N,Schema:()=>w,ZodAny:()=>ge,ZodArray:()=>le,ZodBigInt:()=>Te,ZodBoolean:()=>Ie,ZodBranded:()=>dt,ZodCatch:()=>Me,ZodDate:()=>Re,ZodDefault:()=>je,ZodDiscriminatedUnion:()=>$t,ZodEffects:()=>Z,ZodEnum:()=>$e,ZodError:()=>U,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>jt,ZodIntersection:()=>Ce,ZodIssueCode:()=>d,ZodLazy:()=>Pe,ZodLiteral:()=>Ne,ZodMap:()=>Ge,ZodNaN:()=>Ye,ZodNativeEnum:()=>Le,ZodNever:()=>K,ZodNull:()=>Ee,ZodNullable:()=>re,ZodNumber:()=>ke,ZodObject:()=>V,ZodOptional:()=>W,ZodParsedType:()=>f,ZodPipeline:()=>mt,ZodPromise:()=>ye,ZodReadonly:()=>qe,ZodRecord:()=>Lt,ZodSchema:()=>w,ZodSet:()=>Ke,ZodString:()=>he,ZodSymbol:()=>ze,ZodTransformer:()=>Z,ZodTuple:()=>te,ZodType:()=>w,ZodUndefined:()=>Ae,ZodUnion:()=>Oe,ZodUnknown:()=>ue,ZodVoid:()=>Ze,addIssueToContext:()=>p,any:()=>Pa,array:()=>ja,bigint:()=>Ra,boolean:()=>un,coerce:()=>ii,custom:()=>an,date:()=>Aa,datetimeRegex:()=>nn,defaultErrorMap:()=>oe,discriminatedUnion:()=>Ua,effect:()=>Xa,enum:()=>Ka,function:()=>za,getErrorMap:()=>Fe,getParsedType:()=>ee,instanceof:()=>Ta,intersection:()=>Va,isAborted:()=>Pt,isAsync:()=>Be,isDirty:()=>Nt,isValid:()=>fe,late:()=>ka,lazy:()=>Za,literal:()=>Ga,makeIssue:()=>lt,map:()=>Ba,nan:()=>Ia,nativeEnum:()=>Ya,never:()=>$a,null:()=>Ca,nullable:()=>ei,number:()=>cn,object:()=>Ma,objectUtil:()=>ar,oboolean:()=>ai,onumber:()=>si,optional:()=>Qa,ostring:()=>ni,pipeline:()=>ri,preprocess:()=>ti,promise:()=>Ja,quotelessJson:()=>Xs,record:()=>Fa,set:()=>Wa,setErrorMap:()=>ea,strictObject:()=>qa,string:()=>on,symbol:()=>Ea,transformer:()=>Xa,tuple:()=>Ha,undefined:()=>Oa,union:()=>Da,unknown:()=>Na,util:()=>k,void:()=>La});var k;(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})(k||(k={}));var ar;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ar||(ar={}));var f=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=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=k.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"]),Xs=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 u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],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,k.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 Qs=(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,k.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${k.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${k.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${k.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}"`:k.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,k.assertNever(r)}return{message:t}},oe=Qs;var Xr=oe;function ea(r){Xr=r}function Fe(){return Xr}var lt=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(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},ta=[];function p(r,e){let t=Fe(),n=lt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===oe?void 0:oe].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"}),Se=r=>({status:"dirty",value:r}),L=r=>({status:"valid",value:r}),Pt=r=>r.status==="aborted",Nt=r=>r.status==="dirty",fe=r=>r.status==="valid",Be=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 z=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}},Qr=(r,e)=>{if(fe(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 b(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 w=class{get description(){return this._def.description}_getType(e){return ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(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:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Be(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:ee(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Qr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return fe(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=>fe(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:ee(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Be(s)?s:Promise.resolve(s));return Qr(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 Z({schema:this,typeName:y.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 W.create(this,this._def)}nullable(){return re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return ye.create(this,this._def)}or(e){return Oe.create([this,e],this._def)}and(e){return Ce.create(this,e,this._def)}transform(e){return new Z({...b(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new je({...b(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new dt({typeName:y.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Me({...b(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return mt.create(this,e)}readonly(){return qe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ra=/^c[^\s-]{8,}$/i,na=/^[0-9a-z]+$/,sa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aa=/^[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,ia=/^[a-z0-9_-]{21}$/i,oa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ca=/^[-+]?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)?)??$/,ua=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,la="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ir,da=/^(?:(?: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])$/,ma=/^(?:(?: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])$/,pa=/^(([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]))$/,fa=/^(([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])$/,ha=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ga=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tn="((\\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])))",ya=new RegExp(`^${tn}$`);function rn(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 _a(r){return new RegExp(`^${rn(r)}$`)}function nn(r){let e=`${tn}T${rn(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 va(r,e){return!!((e==="v4"||!e)&&da.test(r)||(e==="v6"||!e)&&pa.test(r))}function ba(r,e){if(!oa.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 wa(r,e){return!!((e==="v4"||!e)&&ma.test(r)||(e==="v6"||!e)&&fa.test(r))}var he=class r extends w{_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")ua.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")ir||(ir=new RegExp(la,"u")),ir.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")aa.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")ia.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")ra.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")na.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")sa.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"?nn(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"?ya.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?_a(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"?ca.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?va(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"?ba(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"?wa(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"?ha.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?ga.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):k.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}};he.create=r=>new he({checks:[],typeName:y.ZodString,coerce:r?.coerce??!1,...b(r)});function xa(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 ke=class r extends w{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"?k.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"?xa(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()):k.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"&&k.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)}};ke.create=r=>new ke({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Te=class r extends w{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()):k.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}};Te.create=r=>new Te({checks:[],typeName:y.ZodBigInt,coerce:r?.coerce??!1,...b(r)});var Ie=class extends w{_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 L(e.data)}};Ie.create=r=>new Ie({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Re=class r extends w{_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()):k.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}};Re.create=r=>new Re({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...b(r)});var ze=class extends w{_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 L(e.data)}};ze.create=r=>new ze({typeName:y.ZodSymbol,...b(r)});var Ae=class extends w{_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 L(e.data)}};Ae.create=r=>new Ae({typeName:y.ZodUndefined,...b(r)});var Ee=class extends w{_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 L(e.data)}};Ee.create=r=>new Ee({typeName:y.ZodNull,...b(r)});var ge=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}};ge.create=r=>new ge({typeName:y.ZodAny,...b(r)});var ue=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}};ue.create=r=>new ue({typeName:y.ZodUnknown,...b(r)});var K=class extends w{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};K.create=r=>new K({typeName:y.ZodNever,...b(r)});var Ze=class extends w{_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 L(e.data)}};Ze.create=r=>new Ze({typeName:y.ZodVoid,...b(r)});var le=class r extends w{_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 z(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new z(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)}};le.create=(r,e)=>new le({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...b(e)});function We(r){if(r instanceof V){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=W.create(We(n))}return new V({...r._def,shape:()=>e})}else return r instanceof le?new le({...r._def,type:We(r.element)}):r instanceof W?W.create(We(r.unwrap())):r instanceof re?re.create(We(r.unwrap())):r instanceof te?te.create(r.items.map(e=>We(e))):r}var V=class r extends w{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=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:d.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof K&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let m=a[u],_=s.data[u];c.push({key:{status:"valid",value:u},value:m._parse(new z(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof K){let u=this._def.unknownKeys;if(u==="passthrough")for(let m of o)c.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(u==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let m of o){let _=s.data[m];c.push({key:{status:"valid",value:m},value:u._parse(new z(s,_,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let m of c){let _=await m.key,O=await m.value;u.push({key:_,value:O,alwaysSet:m.alwaysSet})}return u}).then(u=>N.mergeObjectSync(n,u)):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:y.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 k.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 k.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return We(this)}partial(e){let t={};for(let n of k.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 k.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof W;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return sn(k.objectKeys(this.shape))}};V.create=(r,e)=>new V({shape:()=>r,unknownKeys:"strip",catchall:K.create(),typeName:y.ZodObject,...b(e)});V.strictCreate=(r,e)=>new V({shape:()=>r,unknownKeys:"strict",catchall:K.create(),typeName:y.ZodObject,...b(e)});V.lazycreate=(r,e)=>new V({shape:r,unknownKeys:"strip",catchall:K.create(),typeName:y.ZodObject,...b(e)});var Oe=class extends w{_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 u={...t,common:{...t.common,issues:[]},parent:null},m=c._parseSync({data:t.data,path:t.path,parent:u});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:u}),u.common.issues.length&&i.push(u.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}};Oe.create=(r,e)=>new Oe({options:r,typeName:y.ZodUnion,...b(e)});var ce=r=>r instanceof Pe?ce(r.schema):r instanceof Z?ce(r.innerType()):r instanceof Ne?[r.value]:r instanceof $e?r.options:r instanceof Le?k.objectValues(r.enum):r instanceof je?ce(r._def.innerType):r instanceof Ae?[void 0]:r instanceof Ee?[null]:r instanceof W?[void 0,...ce(r.unwrap())]:r instanceof re?[null,...ce(r.unwrap())]:r instanceof dt||r instanceof qe?ce(r.unwrap()):r instanceof Me?ce(r._def.innerType):[],$t=class r extends w{_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=ce(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:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...b(n)})}};function or(r,e){let t=ee(r),n=ee(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=k.objectKeys(e),a=k.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=or(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=or(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 Ce=class extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Pt(a)||Pt(i))return g;let o=or(a.value,i.value);return o.valid?((Nt(a)||Nt(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}))}};Ce.create=(r,e,t)=>new Ce({left:r,right:e,typeName:y.ZodIntersection,...b(t)});var te=class r extends w{_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 z(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})}};te.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new te({items:r,typeName:y.ZodTuple,rest:null,...b(e)})};var Lt=class r extends w{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 z(n,o,n.path,o)),value:i._parse(new z(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 w?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...b(n)}):new r({keyType:he.create(),valueType:e,typeName:y.ZodRecord,...b(t)})}},Ge=class extends w{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],u)=>({key:s._parse(new z(n,o,n.path,[u,"key"])),value:a._parse(new z(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,m=await c.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),o.set(u.value,m.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,m=c.value;if(u.status==="aborted"||m.status==="aborted")return g;(u.status==="dirty"||m.status==="dirty")&&t.dirty(),o.set(u.value,m.value)}return{status:t.value,value:o}}}};Ge.create=(r,e,t)=>new Ge({valueType:e,keyType:r,typeName:y.ZodMap,...b(t)});var Ke=class r extends w{_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 u=new Set;for(let m of c){if(m.status==="aborted")return g;m.status==="dirty"&&t.dirty(),u.add(m.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new z(n,c,n.path,u)));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)}};Ke.create=(r,e)=>new Ke({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...b(e)});var jt=class r extends w{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 lt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Fe(),oe].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return lt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Fe(),oe].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ye){let o=this;return L(async function(...c){let u=new U([]),m=await o._def.args.parseAsync(c,a).catch(v=>{throw u.addIssue(n(c,v)),u}),_=await Reflect.apply(i,this,m);return await o._def.returns._def.type.parseAsync(_,a).catch(v=>{throw u.addIssue(s(_,v)),u})})}else{let o=this;return L(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new U([n(c,u.error)]);let m=Reflect.apply(i,this,u.data),_=o._def.returns.safeParse(m,a);if(!_.success)throw new U([s(m,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:te.create(e).rest(ue.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||te.create([]).rest(ue.create()),returns:t||ue.create(),typeName:y.ZodFunction,...b(n)})}},Pe=class extends w{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})}};Pe.create=(r,e)=>new Pe({getter:r,typeName:y.ZodLazy,...b(e)});var Ne=class extends w{_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}};Ne.create=(r,e)=>new Ne({value:r,typeName:y.ZodLiteral,...b(e)});function sn(r,e){return new $e({values:r,typeName:y.ZodEnum,...b(e)})}var $e=class r extends w{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:k.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 L(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})}};$e.create=sn;var Le=class extends w{_parse(e){let t=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=k.objectValues(t);return p(n,{expected:k.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=k.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return L(e.data)}get enum(){return this._def.values}};Le.create=(r,e)=>new Le({values:r,typeName:y.ZodNativeEnum,...b(e)});var ye=class extends w{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 L(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ye.create=(r,e)=>new ye({type:r,typeName:y.ZodPromise,...b(e)});var Z=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.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"?Se(c.value):t.value==="dirty"?Se(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"?Se(o.value):t.value==="dirty"?Se(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(!fe(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=>fe(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);k.assertNever(s)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:y.ZodEffects,effect:e,...b(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...b(t)});var W=class extends w{_parse(e){return this._getType(e)===f.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};W.create=(r,e)=>new W({innerType:r,typeName:y.ZodOptional,...b(e)});var re=class extends w{_parse(e){return this._getType(e)===f.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};re.create=(r,e)=>new re({innerType:r,typeName:y.ZodNullable,...b(e)});var je=class extends w{_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}};je.create=(r,e)=>new je({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var Me=class extends w{_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 Be(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}};Me.create=(r,e)=>new Me({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var Ye=class extends w{_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}}};Ye.create=r=>new Ye({typeName:y.ZodNaN,...b(r)});var Sa=Symbol("zod_brand"),dt=class extends w{_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}},mt=class r extends w{_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(),Se(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:y.ZodPipeline})}},qe=class extends w{_parse(e){let t=this._def.innerType._parse(e),n=s=>(fe(s)&&(s.value=Object.freeze(s.value)),s);return Be(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};qe.create=(r,e)=>new qe({innerType:r,typeName:y.ZodReadonly,...b(e)});function en(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function an(r,e={},t){return r?ge.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=en(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=en(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):ge.create()}var ka={object:V.lazycreate},y;(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"})(y||(y={}));var Ta=(r,e={message:`Input not instance of ${r.name}`})=>an(t=>t instanceof r,e),on=he.create,cn=ke.create,Ia=Ye.create,Ra=Te.create,un=Ie.create,Aa=Re.create,Ea=ze.create,Oa=Ae.create,Ca=Ee.create,Pa=ge.create,Na=ue.create,$a=K.create,La=Ze.create,ja=le.create,Ma=V.create,qa=V.strictCreate,Da=Oe.create,Ua=$t.create,Va=Ce.create,Ha=te.create,Fa=Lt.create,Ba=Ge.create,Wa=Ke.create,za=jt.create,Za=Pe.create,Ga=Ne.create,Ka=$e.create,Ya=Le.create,Ja=ye.create,Xa=Z.create,Qa=W.create,ei=re.create,ti=Z.createWithPreprocess,ri=mt.create,ni=()=>on().optional(),si=()=>cn().optional(),ai=()=>un().optional(),ii={string:(r=>he.create({...r,coerce:!0})),number:(r=>ke.create({...r,coerce:!0})),boolean:(r=>Ie.create({...r,coerce:!0})),bigint:(r=>Te.create({...r,coerce:!0})),date:(r=>Re.create({...r,coerce:!0}))};var oi=g;var ln="1.7.0-rc.0",dn=T.object({name:T.string().max(100).nullable(),location:T.string().max(100).nullable(),member_since:T.string()}),mn=T.object({total_transactions:T.number(),total_spent:T.number(),tools_used:T.record(T.string(),T.number()),last_active:T.string().nullable(),themes:T.array(T.string().max(100)).max(20),recent_prompts:T.array(T.string().max(500)).max(50).optional().default([])}),pn=T.object({daily_remaining:T.number(),daily_limit:T.number()}),ci=T.object({message:T.string().max(500),tool:T.string(),reason:T.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),ui=T.object({proactive:ci,reactive:T.record(T.string(),T.array(T.string().max(500)).nullable())}),li=T.object({user:dn,usage:mn,budget:pn,suggestions:ui}),di=T.object({user:dn,usage:mn,budget:pn});function mi(r){let e=li.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=di.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function De(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 pi=`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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visa/cli",
3
- "version": "1.6.0-rc.4",
3
+ "version": "1.7.0-rc.0",
4
4
  "description": "AI-powered payments for Claude Code",
5
5
  "bin": {
6
6
  "visa-cli": "./bin/visa-cli.js"