@visa/cli 1.2.1-rc.0 → 1.2.1-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,40 +1,7 @@
1
- "use strict";var wr=Object.create;var Ye=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var $r=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Pr=Object.prototype.hasOwnProperty;var $=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Cr=(e,t)=>{for(var n in t)Ye(e,n,{get:t[n],enumerable:!0})},kr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $r(t))!Pr.call(e,o)&&o!==n&&Ye(e,o,{get:()=>t[o],enumerable:!(r=vr(t,o))||r.enumerable});return e};var g=(e,t,n)=>(n=e!=null?wr(xr(e)):{},kr(t||!e||!e.__esModule?Ye(n,"default",{value:e,enumerable:!0}):n,e));async function Rr(){try{let{stdout:e}=await V("security",["find-generic-password","-s",M,"-a",G,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Ar(e){try{try{await V("security",["delete-generic-password","-s",M,"-a",G],{timeout:5e3})}catch{}return await V("security",["add-generic-password","-s",M,"-a",G,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Ir(){try{await V("security",["delete-generic-password","-s",M,"-a",G],{timeout:5e3})}catch{}}async function Lr(){if(!nt())return null;try{let{stdout:e}=await V("secret-tool",["lookup","service",M,"account",G],{timeout:5e3});return e.trim()||null}catch{return null}}async function Mr(e){if(!nt())return!1;try{let t=(0,xe.execFile)("secret-tool",["store","--label",`${M} ${G}`,"service",M,"account",G]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Er))]),!0):!1}catch{return!1}}async function Nr(){if(nt())try{await V("secret-tool",["clear","service",M,"account",G],{timeout:5e3})}catch{}}function nt(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Or(){try{let{stdout:e}=await V("security",["find-generic-password","-s",M,"-a",$e,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Ur(e){try{try{await V("security",["delete-generic-password","-s",M,"-a",$e],{timeout:5e3})}catch{}await V("security",["add-generic-password","-s",M,"-a",$e,"-w",e],{timeout:5e3})}catch{}}async function Dr(){try{await V("security",["delete-generic-password","-s",M,"-a",$e],{timeout:5e3})}catch{}}function Ze(){try{return W.readFileSync(ve,"utf-8").trim()||null}catch{return null}}function Mt(e){W.mkdirSync(tt,{recursive:!0,mode:448}),W.writeFileSync(ve,e,{mode:384}),process.platform==="win32"&&jr(ve)}function Qe(){try{W.unlinkSync(ve)}catch{}}function jr(e){try{let t=Pe.userInfo().username;(0,xe.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 Xe(){switch(process.platform){case"darwin":return{get:Rr,store:Ar,delete:Ir};case"linux":return{get:Lr,store:Mr,delete:Nr};default:return{get:async()=>Ze(),store:async e=>{try{return Mt(e),!0}catch{return!1}},delete:async()=>Qe()}}}var xe,Lt,W,Pe,et,V,tt,ve,M,G,$e,Er,v,le=$(()=>{"use strict";xe=require("child_process"),Lt=require("util"),W=g(require("fs")),Pe=g(require("os")),et=g(require("path")),V=(0,Lt.promisify)(xe.execFile),tt=et.join(Pe.homedir(),".visa-mcp"),ve=et.join(tt,"session-token"),M="visa-cli",G="session-token",$e="rc-access",Er=5e3;v=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Xe(),n=await t.get();if(n)return n;let r=Ze();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Xe();if(await n.store(t)){if(await n.get()===t){Qe();return}await n.delete()}if(Mt(t),Ze()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${tt} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Or()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Ur(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Xe().delete(),Qe()}static async clearAll(){await this.deleteSessionToken(),await Dr()}}});var rt=Tr((rs,Hr)=>{Hr.exports={name:"@visa/cli",version:"1.2.1-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});function Dt(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 Br(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(`
2
- `)}function jt(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 Ht(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,o=t.platform??process.platform,s=t.spawn??((c,l,u)=>{(0,Ut.execFile)(c,l,m=>u(m))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of Br(e).split(`
3
- `))n(` ${c}`);n("");let i=Dt(r,o);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=jt(e,o);if(!a){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{s(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 Ut,st=$(()=>{"use strict";Ut=require("child_process")});async function Qt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var en=$(()=>{"use strict"});function nn(e,t){let n=tn(e),r=tn(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:ao(n.pre,r.pre)>0}function tn(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(io);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function ao(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],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}var io,rn=$(()=>{"use strict";io=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function J(){return!!(on(process.env.VISA_CLI_NO_UPDATE_CHECK)||on(process.env.CI)||process.env.NODE_ENV==="test")}function on(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Re=$(()=>{"use strict"});var lt,q,Ae=$(()=>{"use strict";en();rn();Re();lt="1.2.1-rc.0",q=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={},!J()){let r=t.headers.get("X-Latest-Version"),o=t.headers.get("X-Update-Message");r&&nn(r,lt)&&(this.lastSignals.updateAvailable={version:r,message:o||`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 lt}async request(t,n,r,o,s){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}`};s&&(t==="GET"?a["X-User-Context"]=s.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:s}),r&&(a["Content-Type"]="application/json");let c;try{c=await Qt(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":lt},body:r?JSON.stringify(r):void 0,timeoutMs:o})}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,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o)}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 o=r.toString();return this.request("GET",`/v1/catalog${o?`?${o}`:""}`)}async catalogTool(t){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`)}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getTransactions(t){return this.request("GET","/v1/transactions",void 0,void 0,t)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}}});function lo(){I.existsSync(dt)||I.mkdirSync(dt,{recursive:!0,mode:448})}function uo(){if(!ut){if(lo(),I.existsSync(de)&&I.statSync(de).size>co){let t=de+".1";I.existsSync(t)&&I.unlinkSync(t),I.renameSync(de,t)}ut=I.createWriteStream(de,{flags:"a"})}return ut}function Ie(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
4
- `;process.stderr.write(o),uo().write(o)}var I,mt,sn,dt,de,co,ut,Y,pt=$(()=>{"use strict";I=g(require("fs")),mt=g(require("path")),sn=g(require("os")),dt=mt.join(sn.homedir(),".visa-mcp"),de=mt.join(dt,"mcp-server.log"),co=5*1024*1024,ut=null;Y={debug:(...e)=>Ie("DEBUG",...e),info:(...e)=>Ie("INFO",...e),warn:(...e)=>Ie("WARN",...e),error:(...e)=>Ie("ERROR",...e)}});function un(e){let t=T.readFileSync(e);return mn.createHash("sha256").update(t).digest("hex")}async function gn(){try{if(T.readFileSync(cn,"utf-8").trim()===an&&T.existsSync(ee)){let r=T.readFileSync(ln,"utf-8").trim();if(un(ee)!==r)Y.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),T.unlinkSync(ee);else return ee}}catch{}let e=B.join(mo,"visa-keychain.m");if(T.existsSync(e)||(e=B.resolve(__dirname,"..","..","native","visa-keychain.m")),T.existsSync(e)||(e=B.resolve(__dirname,"..","native","visa-keychain.m")),!T.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");T.mkdirSync(Ne,{recursive:!0,mode:448});try{await ie("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",ee,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=un(ee);return T.writeFileSync(ln,t,{mode:384}),T.writeFileSync(cn,an,{mode:384}),ee}async function fn(e){let t=await gn(),n;try{n=(await ie(t,e,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}function te(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:gt!==null?gt:(gt=!0,!0)}async function po(e){try{await ie("security",["delete-generic-password","-s",Le,"-a",Me],{timeout:5e3})}catch{}await ie("security",["add-generic-password","-s",Le,"-a",Me,"-w",e],{timeout:5e3})}async function go(){try{let{stdout:e}=await ie("security",["find-generic-password","-s",Le,"-a",Me,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function hn(){let e=await fn(["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 po(n),r}async function Oe(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await go();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await gn(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,ft.execFile)(r,o,{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:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function ht(){try{await ie("security",["delete-generic-password","-s",Le,"-a",Me],{timeout:5e3})}catch{}try{await fn(["delete-key"])}catch{}}var ft,dn,mn,T,pn,B,ie,Ne,ee,mo,an,cn,ln,gt,Le,Me,yt=$(()=>{"use strict";ft=require("child_process"),dn=require("util"),mn=g(require("crypto")),T=g(require("fs")),pn=g(require("os")),B=g(require("path"));pt();ie=(0,dn.promisify)(ft.execFile),Ne=B.join(pn.homedir(),".visa-mcp","bin"),ee=B.join(Ne,"Visa CLI"),mo=B.join(__dirname,"..","native"),an="5",cn=B.join(Ne,"visa-keychain.version"),ln=B.join(Ne,"visa-keychain.sha256");gt=null;Le="visa-cli",Me="attestation-key"});async function Ge(e){let{model:t,messages:n,tools:r,maxTokens:o=4096,temperature:s=.7,attestation:i,sessionBudgetId:a}=e;return await Do.shortcut(t,{prompt:"",messages:n,...r?.length?{tools:r}:{},max_tokens:o,temperature:s,...i?{attestation:i}:{},...a?{session_budget_id:a}:{}},12e4)}function Hn(e,t){let n={"or-claude-sonnet":{inPerM:3,outPerM:15},"or-gpt-4o":{inPerM:5,outPerM:15},"or-gpt-4o-mini":{inPerM:.15,outPerM:.6},"or-gemini-pro":{inPerM:.25,outPerM:1},"or-llama-70b":{inPerM:.59,outPerM:.79},"or-deepseek-chat":{inPerM:.27,outPerM:1.1},"or-deepseek-r1":{inPerM:.55,outPerM:2.19},"or-mistral-large":{inPerM:2,outPerM:6}},r=n[t]||n["or-gpt-4o-mini"],o=e.prompt_tokens/1e6*r.inPerM*100,s=e.completion_tokens/1e6*r.outPerM*100;return Math.ceil(o+s)}var Do,kt=$(()=>{"use strict";Ae();le();Do=new q(()=>v.getSessionToken())});function Vn(e){let t=[];t.push(`You are an AI coding assistant powered by Visa CLI.
5
- You can read, write, and edit files. You can run shell commands.
6
- You can generate images, music, video, and query data \u2014 each costs money.
7
- The user pays per-use via their Visa card. Show costs before expensive operations.
8
-
9
- Working directory: ${e}`);let n=Et.join(e,"CLAUDE.md");if(ce.existsSync(n)){let o=ce.readFileSync(n,"utf-8");t.push(`
10
- --- Project Context (CLAUDE.md) ---
11
- ${o.slice(0,4e3)}`)}let r=Et.join(e,".env");if(ce.existsSync(r)){let o=ce.readFileSync(r,"utf-8").split(`
12
- `).filter(s=>s.includes("=")&&!s.startsWith("#")).map(s=>s.split("=")[0]);o.length&&t.push(`
13
- Environment variables present: ${o.join(", ")}`)}try{let o=(0,Fn.execSync)("git branch --show-current",{cwd:e,encoding:"utf-8"}).trim();t.push(`
14
- Git branch: ${o}`)}catch{}return t.join(`
15
- `)}async function qn(e,t){let n=e[0],r=Math.max(1,e.length-6),o=e.slice(r),s=e.slice(1,r);if(s.length===0)return e;let i=s.filter(l=>l.role!=="tool").map(l=>`${l.role}: ${typeof l.content=="string"?l.content?.slice(0,200):"[tool call]"}`).join(`
16
- `),c=(await Ge({model:t,messages:[{role:"system",content:"Summarize this conversation concisely. Focus on what was done, decisions made, and current state. Under 500 words."},{role:"user",content:i}],maxTokens:1024})).choices[0]?.message?.content||"Previous conversation context unavailable.";return[n,{role:"user",content:`[Previous conversation summary]
17
- ${c}`},{role:"assistant",content:"Understood. I have context from our previous conversation. How can I help?"},...o]}var ce,Et,Fn,Bn=$(()=>{"use strict";ce=g(require("fs")),Et=g(require("path")),Fn=require("child_process");kt()});var O,K,Rt,Kn,Gn,Wn=$(()=>{"use strict";O=g(require("fs")),K=g(require("path")),Rt=require("child_process"),Kn=[{type:"function",function:{name:"read_file",description:"Read a file. Returns contents with line numbers.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd)"},offset:{type:"number",description:"Start line (0-indexed)"},limit:{type:"number",description:"Max lines to read"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Write full content to a file (create or overwrite).",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative to cwd)"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace a string in a file. old_string must be unique in the file.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_string:{type:"string",description:"Exact string to find"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g. "**/*.ts")'},path:{type:"string",description:"Directory to search in"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern"},path:{type:"string",description:"Directory or file to search"},include:{type:"string",description:'Glob to filter files (e.g. "*.ts")'}},required:["pattern"]}}},{type:"function",function:{name:"list_dir",description:"List directory contents.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"}},required:["path"]}}}],Gn={read_file(e,t){let n=K.resolve(t,e.path),o=O.readFileSync(n,"utf-8").split(`
18
- `),s=e.offset||0,i=e.limit||o.length;return{content:o.slice(s,s+i).map((l,u)=>`${s+u+1} ${l}`).join(`
19
- `),isError:!1}},write_file(e,t){let n=K.resolve(t,e.path),r=K.dirname(n);return O.existsSync(r)||O.mkdirSync(r,{recursive:!0}),O.writeFileSync(n,e.content),{content:`Wrote ${n}`,isError:!1}},edit_file(e,t){let n=K.resolve(t,e.path),r=O.readFileSync(n,"utf-8"),o=e.old_string,s=e.new_string,i=r.indexOf(o);return i===-1?{content:`old_string not found in ${n}`,isError:!0}:r.indexOf(o,i+1)!==-1?{content:`old_string is not unique in ${n}`,isError:!0}:(O.writeFileSync(n,r.replace(o,s)),{content:`Edited ${n}`,isError:!1})},glob(e,t){let n=e.path?K.resolve(t,e.path):t,r=e.pattern;try{return{content:(0,Rt.execFileSync)("find",[n,"-path",`*${r}`,"-not","-path","*/node_modules/*","-not","-path","*/.git/*"],{encoding:"utf-8",timeout:5e3}).split(`
20
- `).filter(Boolean).slice(0,100).join(`
21
- `)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},grep(e,t){let n=e.path?K.resolve(t,e.path):t,r=e.pattern,o=e.include,s=["-rn",...o?["--include",o]:[],r,n];try{return{content:(0,Rt.execFileSync)("grep",s,{encoding:"utf-8",timeout:1e4}).split(`
22
- `).filter(Boolean).slice(0,50).join(`
23
- `)||"No matches",isError:!1}}catch{return{content:"No matches",isError:!1}}},list_dir(e,t){let n=K.resolve(t,e.path||".");return{content:O.readdirSync(n,{withFileTypes:!0}).map(s=>`${s.isDirectory()?"d":"f"} ${s.name}`).join(`
24
- `),isError:!1}}}});var zn,jo,Jn,Yn,Xn=$(()=>{"use strict";zn=require("child_process"),jo=[/rm\s+-rf\s+\//,/mkfs/,/dd\s+if=/,/:()\{\s*:\|:&\s*\};:/,/>\s*\/dev\/sd/],Jn=[{type:"function",function:{name:"bash",description:"Run a bash command. Returns stdout + stderr.",parameters:{type:"object",properties:{command:{type:"string",description:"Bash command to execute"}},required:["command"]}}}],Yn={bash(e,t){let n=e.command;for(let r of jo)if(r.test(n))return{content:"Blocked: dangerous command pattern",isError:!0};try{return{content:(0,zn.execSync)(n,{cwd:t,encoding:"utf-8",timeout:3e4,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).slice(0,1e4),isError:!1}}catch(r){return{content:((r.stdout||"")+(r.stderr||"")).slice(0,1e4)||r.message,isError:!0}}}}});async function Qn(e,t,n){let r=Ho[e];if(!r)return{content:`Unknown tool: ${e}`,isError:!0};try{return r(t,n)}catch(o){return{content:o.message||String(o),isError:!0}}}var Zn,Ho,er=$(()=>{"use strict";Wn();Xn();Zn=[...Kn,...Jn],Ho={...Gn,...Yn}});async function tr(e,t,n,r,o,s){let i=process.cwd(),a=[{role:"system",content:Vn(i)}],c=qo[e.model]||128e3;for(;e.turns<Fo;){let l=await n();if(l===null)break;if(!l.trim())continue;if(l.startsWith("/")){if(l.startsWith("/model ")){e.model=l.slice(7).trim(),r(`Switched to ${e.model}`);continue}if(l==="/budget"||l==="/cost"){r(`Spent: $${(e.spentCents/100).toFixed(2)} / $${(e.budgetCents/100).toFixed(2)}`);continue}if(l==="/quit"||l==="/exit")break}a.push({role:"user",content:l});let u=0,m=0;for(;;){if(e.turns++,e.spentCents>=e.budgetCents){r("Session budget exhausted. Run /budget to check or start a new session.");return}let p;try{p=await Ge({model:e.model,messages:a,tools:Zn,maxTokens:4096,temperature:.7,...t?{attestation:t}:{}})}catch(E){r(`Error: ${E.message||E}`),a.pop();break}let _=Hn(p.usage,e.model);e.spentCents+=_,e.inputTokens+=p.usage.prompt_tokens,e.outputTokens+=p.usage.completion_tokens,u+=_;let x=p.choices[0];if(!x)break;let P=x.message;if(P.content&&r(P.content),a.push(P),!P.tool_calls?.length||x.finish_reason==="stop")break;for(let E of P.tool_calls){let H=E.function.name,F;try{F=JSON.parse(E.function.arguments)}catch{F={}}o(H,F);let{content:R}=await Qn(H,F,i);a.push({role:"tool",content:R.slice(0,1e4),tool_call_id:E.id})}}if(s(u,m),Bo(a)>c*Vo){let p=await qn(a,e.model);a.length=0,a.push(...p)}}}function Bo(e){let t=0;for(let n of e)if(typeof n.content=="string"&&(t+=n.content.length),n.tool_calls)for(let r of n.tool_calls)t+=r.function.arguments.length+r.function.name.length;return Math.ceil(t/3.5)}var Fo,Vo,qo,nr=$(()=>{"use strict";kt();Bn();er();Fo=50,Vo=.7,qo={"or-claude-sonnet":2e5,"or-gpt-4o":128e3,"or-gpt-4o-mini":128e3,"or-gemini-pro":1e6,"or-deepseek-r1":64e3}});var Ko,Hs,rr=$(()=>{"use strict";At();Ko={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"]}},Hs=Object.keys(Ko)});async function or(e,t,n,r){if(!te()){Y.warn("attestation:unavailable",{context:e});return}Y.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:o}=await Go.getAttestationChallenge(),s=Buffer.from(JSON.stringify({nonce:o,amount:t,merchant:n,context:e})).toString("base64");Y.info("touchid:prompt",{context:e,amount:t,merchant:n});let i=await Oe(s,r);return Y.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:i,nonce:o,amount:t,merchant:n}}catch(o){throw Y.error("attestation:failure",{context:e,amount:t,merchant:n,error:o.message}),o}}var Ys,Go,Wo,Xs,Zs,Qs,At=$(()=>{"use strict";Ae();yt();le();pt();rr();st();Ys=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",Go=new q(()=>v.getSessionToken()),Wo=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Xs=["","","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:",...Wo.map(e=>`\u2022 "${e.replace(/_/g," ")}" \u2192 ${e}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
25
- `);Zs=16*1024,Qs=50*1024*1024});function ir(e="or-claude-sonnet"){return{model:e,budgetCents:sr,spentCents:0,turns:0,inputTokens:0,outputTokens:0}}async function ar(e=sr){try{return{attestation:await or("visa-client-session",e/100,"Visa CLI",`Visa CLI session budget: $${(e/100).toFixed(2)}`)||void 0,budgetCents:e}}catch{return{attestation:void 0,budgetCents:e}}}function We(e){let t=(e.budgetCents-e.spentCents)/100,n=e.spentCents/100;return`$${t.toFixed(2)} remaining ($${n.toFixed(2)} spent, ${e.turns} turns)`}var sr,cr=$(()=>{"use strict";At();sr=500});var ur={};Cr(ur,{startClient:()=>Yo});async function Yo(e={}){let t=ir(e.model);console.log(Jo),console.log(`
26
- ${ne}Model: ${t.model}${Z}`),console.log(` ${ne}Authorizing session budget: $${(t.budgetCents/100).toFixed(2)}${Z}`);let n=await ar(e.budget||t.budgetCents);t.budgetCents=n.budgetCents,n.attestation?console.log(` ${ne}Touch ID authorized. ${We(t)}${Z}
27
- `):console.log(` ${ne}No attestation (Touch ID unavailable). ${We(t)}${Z}
28
- `);let r=lr.createInterface({input:process.stdin,output:process.stdout,prompt:`${zo}dove>${Z} `}),o=()=>new Promise(c=>{r.prompt(),r.once("line",l=>c(l)),r.once("close",()=>c(null))}),s=c=>{console.log(`
29
- ${c.split(`
30
- `).join(`
31
- `)}
32
- `)},i=(c,l)=>{let u=c==="bash"?l.command?.slice(0,60):l.path||"";console.log(` ${ne}\u25B8 ${c}${Z} ${u}`)},a=(c,l)=>{let u=c+l,m=[`$${(c/100).toFixed(3)} inference`];l>0&&m.push(`$${(l/100).toFixed(3)} tools`),console.log(` ${ne}${m.join(" \xB7 ")} \xB7 $${(u/100).toFixed(3)} this turn${Z}`)};await tr(t,n.attestation,o,s,i,a),console.log(`
33
- ${ne}Session ended. ${We(t)}${Z}`),r.close()}var lr,Z,zo,ne,Jo,dr=$(()=>{"use strict";lr=g(require("readline"));nr();cr();Z="\x1B[0m",zo="\x1B[38;5;33m",ne="\x1B[2m",Jo=[" \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E4\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u2807\u28B0\u28F6\u28E6\u28E4\u28C0\u2840\u2812\u2802\u2824\u2824\u2884\u28C0\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u285F\u2880\u28FF\u281F\u283F\u28BF\u28FF\u28FF\u28FF\u28FF\u28F6\u28F6\u28E4\u28C4\u28C9\u2841\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FE\u2801\u28F8\u28FF\u28F7\u28F6\u28E4\u28E4\u28C8\u2849\u281B\u283B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u2876\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2880\u284F\u28A0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F6\u28E6\u28E4\u28C4\u28C9\u28B9\u28FF\u2803\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2838\u2800\u28FE\u28FF\u28FF\u28FF\u28CF\u28D9\u281B\u283B\u283F\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u284F\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2802\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E6\u28E4\u28F8\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u28FF\u287F\u280B\u28C1\u28E4\u2804\u2880\u2800\u2809\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u2807\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u28FF\u280F\u28C0\u2818\u281B\u2801\u2830\u28FF\u2847\u28B8\u28E6\u2848\u28BF\u28FF\u28FF\u287F\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u284F\u28A0\u28FF\u28FF\u2803\u28F4\u28F6\u28E4\u2844\u2880\u28C9\u2803\u28B8\u28FF\u28FF\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u28FE\u28FF\u28C7\u2800\u28C4\u28C9\u2800\u281B\u283F\u283F\u2801\u28FC\u28FF\u2847\u28B8\u28FF\u284F\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28C4\u2819\u28BF\u2818\u28F7\u2876\u2800\u28E4\u28C8\u2849\u2881\u28FE\u28FF\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2819\u281B\u283F\u283F\u28FF\u28E6\u28C4\u2800\u2809\u2820\u281E\u281B\u28C9\u28F4\u28FF\u28FF\u2807\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u281B\u2812\u2836\u28BF\u28FF\u28FF\u28FF\u287F\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"," \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800"].join(`
34
- `)});var mr=require("commander"),Je=g(require("crypto")),It=g(require("fs")),U=g(require("os")),we=g(require("path")),pr=g(require("readline")),gr=require("child_process"),fr=require("util");le();var Te=g(require("crypto")),Ce=g(require("tty")),ke=g(require("fs"));var Q="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";le();function Fr(e){return/-rc\.|-beta\./.test(e)}function ot(e){return Te.createHash("sha256").update(e.trim()).digest("hex")}function Nt(e){return Q==="SKIP"?!0:Te.timingSafeEqual(Buffer.from(ot(e)),Buffer.from(Q))}function Vr(e){return new Promise((t,n)=>{let r=ke.openSync("/dev/tty","r+"),o=new Ce.ReadStream(r),s=new Ce.WriteStream(r),i=()=>{try{o.destroy()}catch{}try{s.destroy()}catch{}try{ke.closeSync(r)}catch{}};s.write(e),o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let a="";o.on("data",c=>{c==="\r"||c===`
35
- `?(s.write(`
36
- `),i(),t(a)):c===""?(s.write(`
37
- `),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),s.write("\b \b")):(a+=c,s.write("\u2022"))})})}var qr=`
1
+ "use strict";var _n=Object.create;var lt=Object.defineProperty;var xn=Object.getOwnPropertyDescriptor;var kn=Object.getOwnPropertyNames;var Pn=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var Rn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Tn=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of kn(t))!En.call(e,r)&&r!==n&&lt(e,r,{get:()=>t[r],enumerable:!(s=xn(t,r))||s.enumerable});return e};var f=(e,t,n)=>(n=e!=null?_n(Pn(e)):{},Tn(t||!e||!e.__esModule?lt(n,"default",{value:e,enumerable:!0}):n,e));var Ve=Rn((Js,Fn)=>{Fn.exports={name:"@visa/cli",version:"1.2.1-rc.2",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});var gn=require("commander"),Ie=f(require("crypto")),ct=f(require("fs")),N=f(require("os")),fe=f(require("path")),hn=f(require("readline")),yn=require("child_process"),Sn=require("util");var he=require("child_process"),ut=require("util"),j=f(require("fs")),ye=f(require("os")),De=f(require("path")),H=(0,ut.promisify)(he.execFile),Ue=De.join(ye.homedir(),".visa-mcp"),me=De.join(Ue,"session-token"),A="visa-cli",U="session-token",ge="rc-access",An=5e3;async function Ln(){try{let{stdout:e}=await H("security",["find-generic-password","-s",A,"-a",U,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Nn(e){try{try{await H("security",["delete-generic-password","-s",A,"-a",U],{timeout:5e3})}catch{}return await H("security",["add-generic-password","-s",A,"-a",U,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function In(){try{await H("security",["delete-generic-password","-s",A,"-a",U],{timeout:5e3})}catch{}}async function Mn(){if(!je())return null;try{let{stdout:e}=await H("secret-tool",["lookup","service",A,"account",U],{timeout:5e3});return e.trim()||null}catch{return null}}async function On(e){if(!je())return!1;try{let t=(0,he.execFile)("secret-tool",["store","--label",`${A} ${U}`,"service",A,"account",U]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,s)=>{t.on("exit",r=>r===0?n():s(new Error(`secret-tool exited ${r}`))),t.on("error",s)}),new Promise((n,s)=>setTimeout(()=>{t.kill(),s(new Error("secret-tool timed out"))},An))]),!0):!1}catch{return!1}}async function Hn(){if(je())try{await H("secret-tool",["clear","service",A,"account",U],{timeout:5e3})}catch{}}function je(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Dn(){try{let{stdout:e}=await H("security",["find-generic-password","-s",A,"-a",ge,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Un(e){try{try{await H("security",["delete-generic-password","-s",A,"-a",ge],{timeout:5e3})}catch{}await H("security",["add-generic-password","-s",A,"-a",ge,"-w",e],{timeout:5e3})}catch{}}async function jn(){try{await H("security",["delete-generic-password","-s",A,"-a",ge],{timeout:5e3})}catch{}}function Oe(){try{return j.readFileSync(me,"utf-8").trim()||null}catch{return null}}function dt(e){j.mkdirSync(Ue,{recursive:!0,mode:448}),j.writeFileSync(me,e,{mode:384}),process.platform==="win32"&&Vn(me)}function He(){try{j.unlinkSync(me)}catch{}}function Vn(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 Me(){switch(process.platform){case"darwin":return{get:Ln,store:Nn,delete:In};case"linux":return{get:Mn,store:On,delete:Hn};default:return{get:async()=>Oe(),store:async e=>{try{return dt(e),!0}catch{return!1}},delete:async()=>He()}}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Me(),n=await t.get();if(n)return n;let s=Oe();return s?(await t.store(s),s):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Me();if(await n.store(t)){if(await n.get()===t){He();return}await n.delete()}if(dt(t),Oe()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Ue} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Dn()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Un(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Me().delete(),He()}static async clearAll(){await this.deleteSessionToken(),await jn()}};var Se=f(require("crypto")),be=f(require("tty")),ve=f(require("fs"));var G="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function Bn(e){return/-rc\.|-beta\./.test(e)}function Fe(e){return Se.createHash("sha256").update(e.trim()).digest("hex")}function pt(e){return G==="SKIP"?!0:Se.timingSafeEqual(Buffer.from(Fe(e)),Buffer.from(G))}function Kn(e){return new Promise((t,n)=>{let s=ve.openSync("/dev/tty","r+"),r=new be.ReadStream(s),o=new be.WriteStream(s),i=()=>{try{r.destroy()}catch{}try{o.destroy()}catch{}try{ve.closeSync(s)}catch{}};o.write(e),r.setRawMode(!0),r.resume(),r.setEncoding("utf8");let a="";r.on("data",c=>{c==="\r"||c===`
2
+ `?(o.write(`
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 qn=`
38
5
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
39
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
40
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
@@ -43,28 +10,31 @@ ${c}`},{role:"assistant",content:"Understood. I have context from our previous c
43
10
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
44
11
 
45
12
  This is a Release Candidate build. Access is restricted to Visa employees.
46
- `;async function Ot(e={}){let t=e.version??rt().version;if(!Fr(t))return;let n=process.env.VISA_RC_CODE;if(n&&Nt(n)){await v.saveRcAccessToken(ot(n));return}if(e.isMcp??!1){let i=await v.getRcAccessToken();if(i&&(Q==="SKIP"||i===Q))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
47
- `),process.exit(1)}let o=await v.getRcAccessToken();if(o&&(Q==="SKIP"||o===Q))return;console.log(qr);let s=3;for(let i=1;i<=s;i++){let a;try{a=await Vr(" Enter RC access code: ")}catch{process.exit(1)}if(Nt(a)){await v.saveRcAccessToken(ot(a)),console.log(`
13
+ `;async function ft(e={}){let t=e.version??Ve().version;if(!Bn(t))return;let n=process.env.VISA_RC_CODE;if(n&&pt(n)){await $.saveRcAccessToken(Fe(n));return}if(e.isMcp??!1){let i=await $.getRcAccessToken();if(i&&(G==="SKIP"||i===G))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
14
+ `),process.exit(1)}let r=await $.getRcAccessToken();if(r&&(G==="SKIP"||r===G))return;console.log(qn);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Kn(" Enter RC access code: ")}catch{process.exit(1)}if(pt(a)){await $.saveRcAccessToken(Fe(a)),console.log(`
48
15
  Access granted. Welcome.
49
- `);return}i<s&&console.log(`
50
- Invalid code. ${s-i} attempt(s) remaining.
16
+ `);return}i<o&&console.log(`
17
+ Invalid code. ${o-i} attempt(s) remaining.
51
18
  `)}console.log(`
52
19
  Invalid code. Contact your team lead.
53
- `),process.exit(1)}st();var Vt=g(require("crypto")),A=g(require("fs")),Ee=g(require("path"));function qt(e,t){A.mkdirSync(Ee.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Vt.randomBytes(8).toString("hex")}.tmp`;try{A.writeFileSync(n,JSON.stringify(t,null,2)+`
54
- `),A.renameSync(n,e)}catch(r){try{A.unlinkSync(n)}catch{}throw r}}function Ft(e){return`'${e.replace(/'/g,"'\\''")}'`}var Bt="# visa-cli-hud-v1";function Kr(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",o=r?Ee.resolve(r):"";return`${o?`${Ft(n)} ${Ft(o)} statusline`:"visa-cli statusline"} ${Bt}`}function Kt(e){return typeof e!="string"?!1:e.includes(Bt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function it(e,t=Kr){let n={},r=!1;if(A.existsSync(e)){r=!0;try{n=JSON.parse(A.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli hud enable`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return Kt(o)?{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()},qt(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(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli hud enable`}}}function Gt(e){if(!A.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(A.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 Kt(n)?(delete t.statusLine,qt(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 z=g(require("fs")),ue=g(require("path")),Gr=50,Wr=64*1024,Wt=10,at=80;function zr(){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 ct=zr(),y={reset:"\x1B[0m",visaBlue:ct?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ct?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ct?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function b(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${y.reset}`}function zt(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Yt(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},s=u=>{r||(r=!0,o(),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 s(null);try{let m=JSON.parse(u);s(m&&typeof m=="object"?m:null)}catch{s(null)}},c=()=>s(null),l=setTimeout(()=>{n.length>0?a():s(null)},Gr);e.on("data",i),e.on("end",a),e.on("error",c)})}function Xt(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${b(r||"",y.visaBlueSoft)}${b(o||"",y.dim)}`}function Jt(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 Jr(e){let t=se(e.model?.display_name)||"claude",n=e.cwd?se(ue.basename(e.cwd)):"",r=oo(e.workspace),o=n||r,s=r&&r!==o?` ${b(`@${r}`,y.visaBlueSoft)}`:"",i=so(e.session_id),a=Number(e.context_window?.current_usage?.input_tokens??0),c=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:null,u=l!==null?Math.max(0,Math.min(1,l/100)):c>0?Math.max(0,Math.min(1,a/c)):0,m=b(`[${t}]`,y.visaBlue),d=o?` ${b(o,y.visaGold)}${s}${i}`:i,p;if(c>0||l!==null){let E=`${String(Math.round(u*100)).padStart(2," ")}%`,H=c>0?` ${b(`(${Jt(a)}/${Jt(c)})`,y.dim)}`:"";p=`${b("ctx",y.dim)} ${Xt(u)} ${b(E,y.green)}${H}`}else p=`${b("ctx",y.dim)} ${b("-",y.dim)}`;let _=Yr(e.rate_limits?.five_hour),x=` ${b("\u2502",y.dim)} `,P=[`${m}${d}`,p];return _&&P.push(_),P.join(x)}function Yr(e){if(!e||typeof e.used_percentage!="number")return null;let t=Math.max(0,Math.min(100,e.used_percentage)),n=t/100,r=Xt(n),o=`${String(Math.round(t)).padStart(2," ")}%`,s="";if(typeof e.resets_at=="number"&&e.resets_at>0){let c=(e.resets_at>1e12?e.resets_at:e.resets_at*1e3)-Date.now();if(c>0&&c<10080*60*1e3){let l=Math.floor(c/6e4),u=Math.floor(l/60),m=l%60,d=u>0?`${u}h ${m}m`:`${m}m`;s=` ${b(`(${d})`,y.dim)}`}}let i=t>=70?y.visaGold:y.green;return`${b("5h",y.dim)} ${r} ${b(o,i)}${s}`}function Xr(e){let t;try{let n=z.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,Wr),s=r-o;t=z.openSync(e,"r");let i=Buffer.alloc(o);z.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=a.indexOf(`
55
- `);c>=0&&(a=a.slice(c+1))}return a}catch{return null}finally{if(t!==void 0)try{z.closeSync(t)}catch{}}}function Zr(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 o=t[r];if(typeof o=="string"&&o.length>0)return r.endsWith("_path")||r==="path"?ue.basename(o):o}}function Qr(e){let t=e.split(`
56
- `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<Wt*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}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 m=u;if(m.type==="tool_result"&&typeof m.tool_use_id=="string")r.add(m.tool_use_id);else if(m.type==="tool_use"&&typeof m.name=="string"){let d=typeof m.id=="string"?m.id:"",p=d.length>0?!r.has(d):!1;n.push({name:m.name,target:Zr(m.input),running:p})}}}return n.reverse(),n.slice(Math.max(0,n.length-Wt))}function eo(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 to(e){let t=e.running?b("\u25D0",y.visaGold):b("\u2713",y.green),n=e.running?y.visaGold:y.visaBlueSoft,r=b(e.name,n),o=e.target?`${b(":",y.dim)} ${b(e.target,y.dim)}`:"",s=e.count>1?` ${b(`\xD7${e.count}`,y.dim)}`:"";return o?`${t} ${r}${o}${s}`:`${t} ${r}${s}`}function no(e){let t=` ${b("\u2502",y.dim)} `,n=zt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(zt(c)<=at)return c;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>at-n-1?i.slice(0,at-n-1)+o:i;return`${b(o,y.dim)}${t}${a}`}async function ro(e){if(!e||typeof e!="string")return null;let t=Xr(e);if(!t)return null;let n;try{n=Qr(t)}catch{return null}if(n.length===0)return null;let o=eo(n).map(to);return no(o)||null}async function Zt(e,t){let n=[e];if(t){let r=Jr(t);if(r&&n.push(r),t.transcript_path){let o=await ro(t.transcript_path);o&&n.push(o)}}return n.join(`
57
- `)}function se(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 oo(e){if(typeof e=="string")return se(ue.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 se(t?ue.basename(t):e.name)}function so(e){let t=se(e);return t?` ${b(`#${t.slice(0,8)}`,y.visaBlueSoft)}`:""}Ae();yt();Re();function _n(e,t=process.stderr){if(J()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
20
+ `),process.exit(1)}var mt=require("child_process");function Gn(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 zn(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 Jn(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 gt(e,t={}){let n=t.log??(c=>console.log(c)),s=t.env??process.env,r=t.platform??process.platform,o=t.spawn??((c,p,u)=>{(0,mt.execFile)(c,p,d=>u(d))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of zn(e).split(`
22
+ `))n(` ${c}`);n("");let i=Gn(s,r);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=Jn(e,r);if(!a){n(` No known browser-open command for platform "${r}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(a.cmd,a.args,p=>{p?(n(` Could not open browser automatically (${p.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}var yt=f(require("crypto")),x=f(require("fs")),we=f(require("path"));function St(e,t){x.mkdirSync(we.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${yt.randomBytes(8).toString("hex")}.tmp`;try{x.writeFileSync(n,JSON.stringify(t,null,2)+`
23
+ `),x.renameSync(n,e)}catch(s){try{x.unlinkSync(n)}catch{}throw s}}function ht(e){return`'${e.replace(/'/g,"'\\''")}'`}var bt="# visa-cli-hud-v1";function Wn(e,t){let n=e??process.execPath,s=t??process.argv[1]??"",r=s?we.resolve(s):"";return`${r?`${ht(n)} ${ht(r)} statusline`:"visa-cli statusline"} ${bt}`}function vt(e){return typeof e!="string"?!1:e.includes(bt)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Be(e,t=Wn){let n={},s=!1;if(x.existsSync(e)){s=!0;try{n=JSON.parse(x.readFileSync(e,"utf-8"))}catch(r){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${r.message}). Fix the file manually, then run: visa-cli hud enable`}}}if(n.statusLine){let r=typeof n.statusLine=="object"?n.statusLine.command:"";return vt(r)?{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()},St(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${s?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(r){return{installed:"error",message:`Failed to write settings: ${r.message}. Enable manually later with: visa-cli hud enable`}}}function wt(e){if(!x.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(x.readFileSync(e,"utf-8"))}catch(s){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${s.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return vt(n)?(delete t.statusLine,St(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 V=f(require("fs")),te=f(require("path")),Yn=50,Xn=64*1024,$t=10,Ke=80;function Zn(){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 qe=Zn(),y={reset:"\x1B[0m",visaBlue:qe?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:qe?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:qe?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function b(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${y.reset}`}function Ct(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function xt(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],s=!1,r=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(p)},o=u=>{s||(s=!0,r(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),p=setTimeout(()=>{n.length>0?a():o(null)},Yn);e.on("data",i),e.on("end",a),e.on("error",c)})}function kt(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),s="\u2588".repeat(n),r="\u2591".repeat(10-n);return`${b(s||"",y.visaBlueSoft)}${b(r||"",y.dim)}`}function _t(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 Qn(e){let t=Y(e.model?.display_name)||"claude",n=e.cwd?Y(te.basename(e.cwd)):"",s=cs(e.workspace),r=n||s,o=s&&s!==r?` ${b(`@${s}`,y.visaBlueSoft)}`:"",i=ls(e.session_id),a=Number(e.context_window?.current_usage?.input_tokens??0),c=Number(e.context_window?.context_window_size??0),p=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:null,u=p!==null?Math.max(0,Math.min(1,p/100)):c>0?Math.max(0,Math.min(1,a/c)):0,d=b(`[${t}]`,y.visaBlue),l=r?` ${b(r,y.visaGold)}${o}${i}`:i,m;if(c>0||p!==null){let K=`${String(Math.round(u*100)).padStart(2," ")}%`,q=c>0?` ${b(`(${_t(a)}/${_t(c)})`,y.dim)}`:"";m=`${b("ctx",y.dim)} ${kt(u)} ${b(K,y.green)}${q}`}else m=`${b("ctx",y.dim)} ${b("-",y.dim)}`;let v=es(e.rate_limits?.five_hour),R=` ${b("\u2502",y.dim)} `,O=[`${d}${l}`,m];return v&&O.push(v),O.join(R)}function es(e){if(!e||typeof e.used_percentage!="number")return null;let t=Math.max(0,Math.min(100,e.used_percentage)),n=t/100,s=kt(n),r=`${String(Math.round(t)).padStart(2," ")}%`,o="";if(typeof e.resets_at=="number"&&e.resets_at>0){let c=(e.resets_at>1e12?e.resets_at:e.resets_at*1e3)-Date.now();if(c>0&&c<10080*60*1e3){let p=Math.floor(c/6e4),u=Math.floor(p/60),d=p%60,l=u>0?`${u}h ${d}m`:`${d}m`;o=` ${b(`(${l})`,y.dim)}`}}let i=t>=70?y.visaGold:y.green;return`${b("5h",y.dim)} ${s} ${b(r,i)}${o}`}function ts(e){let t;try{let n=V.statSync(e);if(!n.isFile())return null;let s=n.size;if(s===0)return null;let r=Math.min(s,Xn),o=s-r;t=V.openSync(e,"r");let i=Buffer.alloc(r);V.readSync(t,i,0,r,o);let a=i.toString("utf-8");if(o>0){let c=a.indexOf(`
24
+ `);c>=0&&(a=a.slice(c+1))}return a}catch{return null}finally{if(t!==void 0)try{V.closeSync(t)}catch{}}}function ns(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let s of n){let r=t[s];if(typeof r=="string"&&r.length>0)return s.endsWith("_path")||s==="path"?te.basename(r):r}}function ss(e){let t=e.split(`
25
+ `),n=[],s=new Set;for(let r=t.length-1;r>=0&&n.length<$t*3;r-=1){let o=t[r].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let p=c.content;if(Array.isArray(p))for(let u of p){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")s.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let l=typeof d.id=="string"?d.id:"",m=l.length>0?!s.has(l):!1;n.push({name:d.name,target:ns(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-$t))}function rs(e){let t=[];for(let n of e){let s=t[t.length-1];s&&!s.running&&!n.running&&s.name===n.name&&s.target===void 0&&n.target===void 0?s.count+=1:t.push({...n,count:1})}return t}function os(e){let t=e.running?b("\u25D0",y.visaGold):b("\u2713",y.green),n=e.running?y.visaGold:y.visaBlueSoft,s=b(e.name,n),r=e.target?`${b(":",y.dim)} ${b(e.target,y.dim)}`:"",o=e.count>1?` ${b(`\xD7${e.count}`,y.dim)}`:"";return r?`${t} ${s}${r}${o}`:`${t} ${s}${o}`}function is(e){let t=` ${b("\u2502",y.dim)} `,n=Ct(t),s=e.slice();for(;s.length>0;){let c=s.join(t);if(Ct(c)<=Ke)return c;s=s.slice(1)}if(e.length===0)return"";let r="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Ke-n-1?i.slice(0,Ke-n-1)+r:i;return`${b(r,y.dim)}${t}${a}`}async function as(e){if(!e||typeof e!="string")return null;let t=ts(e);if(!t)return null;let n;try{n=ss(t)}catch{return null}if(n.length===0)return null;let r=rs(n).map(os);return is(r)||null}async function Pt(e,t){let n=[e];if(t){let s=Qn(t);if(s&&n.push(s),t.transcript_path){let r=await as(t.transcript_path);r&&n.push(r)}}return n.join(`
26
+ `)}function Y(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function cs(e){if(typeof e=="string")return Y(te.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return Y(t?te.basename(t):e.name)}function ls(e){let t=Y(e);return t?` ${b(`#${t.slice(0,8)}`,y.visaBlueSoft)}`:""}async function Et(e,t){let n=t?.timeoutMs??3e4,s=new AbortController,r=setTimeout(()=>s.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:s.signal})}finally{clearTimeout(r)}}var us=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Tt(e,t){let n=Rt(e),s=Rt(t);if(!n||!s)return!1;for(let r=0;r<3;r++)if(n.main[r]!==s.main[r])return n.main[r]>s.main[r];return n.pre&&!s.pre?!1:!n.pre&&s.pre?!0:!n.pre&&!s.pre?!1:ds(n.pre,s.pre)>0}function Rt(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(us);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function ds(e,t){let n=e.split("."),s=t.split("."),r=Math.max(n.length,s.length);for(let o=0;o<r;o++){if(o>=n.length)return-1;if(o>=s.length)return 1;let i=n[o],a=s[o],c=/^\d+$/.test(i),p=/^\d+$/.test(a);if(c&&p){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(p)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function F(){return!!(At(process.env.VISA_CLI_NO_UPDATE_CHECK)||At(process.env.CI)||process.env.NODE_ENV==="test")}function At(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ge="1.2.1-rc.2",X=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={},!F()){let s=t.headers.get("X-Latest-Version"),r=t.headers.get("X-Update-Message");s&&Tt(s,Ge)&&(this.lastSignals.updateAvailable={version:s,message:r||`Update available: v${s}. 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 Ge}async request(t,n,s,r,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):s={...s||{},user_context:o}),s&&(a["Content-Type"]="application/json");let c;try{c=await Et(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Ge},body:s?JSON.stringify(s):void 0,timeoutMs:r})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let p;try{p=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(p?.error||`Request failed (${c.status}). Try again.`);return p}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,s,r){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,s,r)}async batch(t,n,s){return this.request("POST","/v1/batch",t,n,s)}async catalogSearch(t,n){let s=new URLSearchParams;t&&s.set("q",t),n&&s.set("category",n);let r=s.toString();return this.request("GET",`/v1/catalog${r?`?${r}`:""}`)}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,s){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,s)}async setDefaultCard(t,n,s){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,s)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,s){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,s)}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 s=n.toString();return this.request("GET",`/v1/feed${s?"?"+s:""}`)}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,s){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,s)}async getFeedback(t,n){let s=new URLSearchParams;t&&s.set("limit",String(t));let r=s.toString();return this.request("GET",`/v1/feedback${r?"?"+r:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var Xe=require("child_process"),Dt=require("util"),Ut=f(require("crypto")),C=f(require("fs")),jt=f(require("os")),D=f(require("path"));var k=f(require("fs")),We=f(require("path")),Lt=f(require("os")),Je=We.join(Lt.homedir(),".visa-mcp"),ne=We.join(Je,"mcp-server.log"),ps=5*1024*1024,ze=null;function fs(){k.existsSync(Je)||k.mkdirSync(Je,{recursive:!0,mode:448})}function ms(){if(!ze){if(fs(),k.existsSync(ne)&&k.statSync(ne).size>ps){let t=ne+".1";k.existsSync(t)&&k.unlinkSync(t),k.renameSync(ne,t)}ze=k.createWriteStream(ne,{flags:"a"})}return ze}function $e(e,...t){let n=new Date().toISOString(),s=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),r=`[${n}] [${e}] ${s}
27
+ `;process.stderr.write(r),ms().write(r)}var Nt={debug:(...e)=>$e("DEBUG",...e),info:(...e)=>$e("INFO",...e),warn:(...e)=>$e("WARN",...e),error:(...e)=>$e("ERROR",...e)};var Z=(0,Dt.promisify)(Xe.execFile),xe=D.join(jt.homedir(),".visa-mcp","bin"),z=D.join(xe,"Visa CLI"),gs=D.join(__dirname,"..","native"),It="5",Mt=D.join(xe,"visa-keychain.version"),Ot=D.join(xe,"visa-keychain.sha256");function Ht(e){let t=C.readFileSync(e);return Ut.createHash("sha256").update(t).digest("hex")}async function Vt(){try{if(C.readFileSync(Mt,"utf-8").trim()===It&&C.existsSync(z)){let s=C.readFileSync(Ot,"utf-8").trim();if(Ht(z)!==s)Nt.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),C.unlinkSync(z);else return z}}catch{}let e=D.join(gs,"visa-keychain.m");if(C.existsSync(e)||(e=D.resolve(__dirname,"..","..","native","visa-keychain.m")),C.existsSync(e)||(e=D.resolve(__dirname,"..","native","visa-keychain.m")),!C.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");C.mkdirSync(xe,{recursive:!0,mode:448});try{await Z("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",z,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ht(z);return C.writeFileSync(Ot,t,{mode:384}),C.writeFileSync(Mt,It,{mode:384}),z}async function Ft(e){let t=await Vt(),n;try{n=(await Z(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 s=n.trim();if(s.startsWith("OK:"))return s.slice(3);if(s==="OK")return;let r=s.startsWith("ERROR:")?s.slice(6):"Unknown error";throw new Error(r)}var Ye=null;function se(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ye!==null?Ye:(Ye=!0,!0)}var Ce="visa-cli",_e="attestation-key";async function hs(e){try{await Z("security",["delete-generic-password","-s",Ce,"-a",_e],{timeout:5e3})}catch{}await Z("security",["add-generic-password","-s",Ce,"-a",_e,"-w",e],{timeout:5e3})}async function ys(){try{let{stdout:e}=await Z("security",["find-generic-password","-s",Ce,"-a",_e,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Bt(){let e=await Ft(["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),s=e.slice(t+1);return await hs(n),s}async function Kt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await ys();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let s=await Vt(),r=["sign",e];return t&&r.push(t),new Promise((o,i)=>{let a=(0,Xe.execFile)(s,r,{timeout:6e4},(c,p)=>{let u=(p||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function qt(){try{await Z("security",["delete-generic-password","-s",Ce,"-a",_e],{timeout:5e3})}catch{}try{await Ft(["delete-key"])}catch{}}function Gt(e,t=process.stderr){if(F()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
58
28
  \x1B[33m\u2191 ${n}\x1B[0m
59
- `),!0):!1}function bn(e,t,n,r){let s=wo(e.spendingControls).dailyLimit,i=Math.max(0,me(e.dailySpent)),a=s>0?Math.min(s,Math.max(0,me(e.dailyRemaining??s-i))):0,c=s>0?Math.min(1,i/s):0,u=(Array.isArray(t)?t:[]).filter(yo),m=u.slice(0,3),d=_o(u,3),p=(e.cards??[]).slice(0,3),_=r.latestVersion?_t(r.latestVersion):"",x=r.updateCheckDisabled?"update checks disabled":_?`update available: v${_}`:"up to date",P=Math.round(c*100),E=X(e.status,e.enrolled?"approved":"not enrolled"),F=["VISA CLI HUD",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${E} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${x}`,`Spend meter: ${Sn(c)} ${String(P).padStart(3," ")}% | remaining ${ae(a)} | cap ${ae(s)}`,"","Spend",` Remaining ${ae(a)} / ${ae(s)}`,` Usage ${Sn(c)} ${P}%`,` Spent today ${ae(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(R=>` ${bo(R)}`):[" No cards enrolled"],"","Last 3 services",...d.length>0?d.map((R,br)=>` ${br+1}. ${R}`):[" No paid services yet"],"","Recent receipts",...m.length>0?m.map(R=>` ${So(R)}`):[" No receipts yet"]];return r.updateMessage&&F.push("",`Update: ${_t(r.updateMessage)}`),`${F.join(`
29
+ `),!0):!1}function Jt(e,t,n,s){let o=xs(e.spendingControls).dailyLimit,i=Math.max(0,re(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,re(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(ws),d=u.slice(0,3),l=$s(u,3),m=(e.cards??[]).slice(0,3),v=s.latestVersion?Ze(s.latestVersion):"",R=s.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",O=Math.round(c*100),K=B(e.status,e.enrolled?"approved":"not enrolled"),ee=["VISA CLI HUD",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${K} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s.currentVersion} | ${R}`,`Spend meter: ${zt(c)} ${String(O).padStart(3," ")}% | remaining ${Q(a)} | cap ${Q(o)}`,"","Spend",` Remaining ${Q(a)} / ${Q(o)}`,` Usage ${zt(c)} ${O}%`,` Spent today ${Q(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...m.length>0?m.map(T=>` ${_s(T)}`):[" No cards enrolled"],"","Last 3 services",...l.length>0?l.map((T,Cn)=>` ${Cn+1}. ${T}`):[" No paid services yet"],"","Recent receipts",...d.length>0?d.map(T=>` ${Cs(T)}`):[" No receipts yet"]];return s.updateMessage&&ee.push("",`Update: ${Ze(s.updateMessage)}`),`${ee.join(`
60
30
  `)}
61
- `}function fo(e){return e.tool_name!=null}function ho(e){return me(e.amount)===0&&e.status==="failed"}function yo(e){return fo(e)&&!ho(e)}function _o(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=X(o.merchant_name,"Unknown merchant"),i=X(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function So(e){let t=X(e.merchant_name,"Unknown merchant"),n=X(e.tool_name,"unknown_tool"),r=ae(me(e.amount)),o=X(e.status,"unknown"),s=vo(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function bo(e){let t=X(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function wo(e){return{dailyLimit:me(e?.daily_limit??e?.dailyLimit??0)}}function me(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function ae(e){return`$${e.toFixed(2)}`}function Sn(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 X(e,t){let n=_t(e??"").trim();return n.length>0?n:t}function vo(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?X(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function _t(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 h=g(require("fs")),Ve=g(require("os")),w=g(require("path")),vn=require("child_process"),$o=2,Ue="# >>> visa-cli shell hud v2 >>>",De="# <<< visa-cli shell hud v2 <<<",xo="# >>> visa-cli shell hud >>>",Po="# <<< visa-cli shell hud <<<",$n=3e4,To=3e4;function vt(){try{return w.join(Rn(),".visa-cli")}catch{return w.join(Ve.tmpdir(),".visa-cli")}}function ge(){return w.join(vt(),"shell-hud.json")}function he(){return w.join(vt(),"shell-hud.line")}function xn(){return w.join(vt(),"shell-hud.lock")}function qe(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 Be(e){let t=Rn();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 Co(e){let t="$HOME/.visa-cli/shell-hud.line",n=Lo(e),r=Mo(e);if(e==="zsh")return`${Ue}
31
+ `}function bs(e){return e.tool_name!=null}function vs(e){return re(e.amount)===0&&e.status==="failed"}function ws(e){return bs(e)&&!vs(e)}function $s(e,t=1/0){let n=new Set,s=[];for(let r of e){if(s.length>=t)break;let o=B(r.merchant_name,"Unknown merchant"),i=B(r.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),s.push(`${o} [${i}]`))}return s}function Cs(e){let t=B(e.merchant_name,"Unknown merchant"),n=B(e.tool_name,"unknown_tool"),s=Q(re(e.amount)),r=B(e.status,"unknown"),o=ks(e.created_at);return`${s} ${r.padEnd(9)} ${t} [${n}] ${o}`}function _s(e){let t=B(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${Number.isInteger(e.id)?`#${e.id} `:""}${t} ****${e.last4}${n}`}function xs(e){return{dailyLimit:re(e?.daily_limit??e?.dailyLimit??0)}}function re(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Q(e){return`$${e.toFixed(2)}`}function zt(e,t=20){let n=Math.max(0,Math.min(1,e)),s=Math.round(n*t);return`[${"\u2588".repeat(s)}${"\u2591".repeat(t-s)}]`}function B(e,t){let n=Ze(e??"").trim();return n.length>0?n:t}function ks(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?B(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Ze(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 h=f(require("fs")),Re=f(require("os")),w=f(require("path")),Yt=require("child_process"),Ps=2,ke="# >>> visa-cli shell hud v2 >>>",Pe="# <<< visa-cli shell hud v2 <<<",Es="# >>> visa-cli shell hud >>>",Rs="# <<< visa-cli shell hud <<<",Xt=3e4,Ts=3e4;function nt(){try{return w.join(rn(),".visa-cli")}catch{return w.join(Re.tmpdir(),".visa-cli")}}function ie(){return w.join(nt(),"shell-hud.json")}function ce(){return w.join(nt(),"shell-hud.line")}function Zt(){return w.join(nt(),"shell-hud.lock")}function Te(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 Ae(e){let t=rn();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 As(e){let t="$HOME/.visa-cli/shell-hud.line",n=Hs(e),s=Ds(e);if(e==="zsh")return`${ke}
62
32
  _visa_cli_shell_hud_precmd() {
63
33
  setopt localoptions no_bg_nice
64
34
  if [[ -f "${t}" ]]; then
65
35
  print -r -- "$(cat "${t}")"
66
36
  fi
67
- if ${r}; then
37
+ if ${s}; then
68
38
  ${n} &>/dev/null &!
69
39
  fi
70
40
  }
@@ -72,15 +42,15 @@ autoload -Uz add-zsh-hook
72
42
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
73
43
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
74
44
  fi
75
- ${De}`;if(e==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Ue}
45
+ ${Pe}`;if(e==="powershell"){let r="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${ke}
76
46
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
77
47
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
78
48
  }
79
49
  function global:prompt {
80
- if (Test-Path ${o}) {
81
- Write-Host (Get-Content ${o} -Raw)
50
+ if (Test-Path ${r}) {
51
+ Write-Host (Get-Content ${r} -Raw)
82
52
  }
83
- if (${r}) {
53
+ if (${s}) {
84
54
  # Reap any completed visa-hud jobs before starting a new one so the session
85
55
  # doesn't accumulate job records over time.
86
56
  Get-Job -Name __visa_hud_refresh -ErrorAction SilentlyContinue | Where-Object { $_.State -in 'Completed','Failed','Stopped' } | Remove-Job -Force -ErrorAction SilentlyContinue
@@ -88,12 +58,12 @@ function global:prompt {
88
58
  }
89
59
  & $function:global:__visa_cli_original_prompt
90
60
  }
91
- ${De}`}return`${Ue}
61
+ ${Pe}`}return`${ke}
92
62
  __visa_cli_shell_hud_precmd() {
93
63
  if [ -f "${t}" ]; then
94
64
  cat "${t}"
95
65
  fi
96
- if ${r}; then
66
+ if ${s}; then
97
67
  ${n} &>/dev/null &
98
68
  fi
99
69
  }
@@ -101,22 +71,22 @@ case ";$PROMPT_COMMAND;" in
101
71
  *";__visa_cli_shell_hud_precmd;"*) ;;
102
72
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
103
73
  esac
104
- ${De}`}function Pn(e){let t=e;for(let[n,r]of[[Ue,De],[xo,Po]])t=t.replace(new RegExp(`\\n?${wn(n)}[\\s\\S]*?${wn(r)}\\n?`,"g"),"");return t.trimEnd()}function ko(e,t){let n=Pn(e).trimEnd(),r=Co(t);return n.length>0?`${n}
74
+ ${Pe}`}function Qt(e){let t=e;for(let[n,s]of[[ke,Pe],[Es,Rs]])t=t.replace(new RegExp(`\\n?${Wt(n)}[\\s\\S]*?${Wt(s)}\\n?`,"g"),"");return t.trimEnd()}function Ls(e,t){let n=Qt(e).trimEnd(),s=As(t);return n.length>0?`${n}
105
75
 
106
- ${r}
107
- `:`${r}
108
- `}function Tn(e=qe()){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=Be(e);let n=h.existsSync(t)?h.readFileSync(t,"utf-8"):"",r=ko(n,e),o=r!==n;return o&&Fe(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`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}: ${An(n)}`}}}function Cn(e=qe()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Be(e),!h.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=h.readFileSync(t,"utf-8"),r=Pn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Fe(t,r.length>0?`${r}
109
- `:""),{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}: ${An(n)}`}}}function $t(e,t){let n=fe(t.currentVersion),r=t.latestVersion?fe(t.latestVersion):void 0,o=t.updateCheckDisabled?`v${n} | updates paused`:r?`v${n} -> v${r}`:`v${n}`;if(!e.enrolled)return`${D("[VISA PAY]",N.visaBlue)} ${D("setup needed",N.visaGold)} | ${D(o,N.visaBlueSoft)}`;let s=St(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),i=Math.max(0,St(e.dailySpent)),a=s>0?Math.min(s,Math.max(0,St(e.dailyRemaining??s-i))):0,c=s>0?Math.max(0,Math.min(1,i/s)):0,l=Ao(e),u=`${String(Math.round(c*100)).padStart(3," ")}%`,m=`${D("[VISA PAY]",N.visaBlue)} ${Ro(c)} ${D(u,N.green)} | ${D(l,N.visaGold)} | ${D(o,N.visaBlueSoft)}`,d=`${D("Spend",N.dim)} ${bt(i)} / ${bt(s)} | ${D("Left",N.dim)} ${bt(a)}`;return`${m}
110
- ${d}`}function kn(){let e=En();return!!e&&Date.now()-e.renderedAt<=$n}function xt(){let e=En();if(e&&Date.now()-e.renderedAt<=$n||(Eo(),e?.line))return e.line;try{let t=he();if(h.existsSync(t))return h.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function Ke(e){try{let t=w.dirname(ge());h.mkdirSync(t,{recursive:!0});let n=fe(e),r={hudVersion:$o,renderedAt:Date.now(),line:n};Fe(ge(),JSON.stringify(r)+`
111
- `),Fe(he(),n+`
112
- `)}catch{}}function pe(){try{h.unlinkSync(xn())}catch{}}function En(){let e=ge();if(!h.existsSync(e))return null;try{return JSON.parse(h.readFileSync(e,"utf-8"))}catch{return null}}function Eo(){let e=xn();try{if(h.mkdirSync(w.dirname(e),{recursive:!0}),!No(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){pe();return}let n=(0,vn.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",pe),n.unref()}catch{pe()}}function St(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function fe(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Ro(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${D(r||"",N.green)}${D(o||"",N.dim)}`}function bt(e){return`$${e.toFixed(2)}`}function Ao(e){let t=e.cards?.find(s=>s.isDefault)??e.cards?.[0];if(!t)return"card none";let n=fe((t.brand??"card").toUpperCase()),r=fe(t.last4);return`${t.isDefault?"default":"active"} ${n} ****${r}`}function Io(){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 wt=Io(),N={reset:"\x1B[0m",visaBlue:wt?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:wt?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:wt?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function D(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${N.reset}`}function wn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rn(){let e=Ve.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function Lo(e){let t=process.argv[1]?w.resolve(process.argv[1]):"";return t?e==="powershell"?`& ${He(process.execPath)} ${He(t)} shell-hud refresh`:`${je(process.execPath)} ${je(t)} shell-hud refresh`:"visa-cli shell-hud refresh"}function Mo(e){let t=process.argv[1]?w.resolve(process.argv[1]):"";return t?e==="powershell"?`((Test-Path ${He(process.execPath)}) -and (Test-Path ${He(t)}))`:`[ -x ${je(process.execPath)} ] && [ -f ${je(t)} ]`:e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function je(e){return`'${e.replace(/'/g,"'\\''")}'`}function He(e){return`'${e.replace(/'/g,"''")}'`}function No(e){for(let t=0;t<2;t+=1){let n;try{return n=h.openSync(e,"wx"),h.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=h.statSync(e);if(Date.now()-o.mtimeMs<=To)return!1;h.unlinkSync(e)}catch{}}finally{n!==void 0&&h.closeSync(n)}}return!1}function An(e){return e instanceof Error?e.message:"unknown file system error"}function Fe(e,t){h.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;h.writeFileSync(n,t),h.renameSync(n,e)}Re();var L=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},In=["GET","POST"];function Ln(e){let t;try{t=new URL(e)}catch{throw new L(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new L(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function Mn(e){let t=(e??"GET").toUpperCase();if(!In.includes(t))throw new L(`Unsupported HTTP method "${e}". Supported: ${In.join(", ")}.`);return t}function Nn(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new L(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function On(e){if(!e||typeof e!="object")throw new L("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new L("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new L("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new L(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new L("Merchant returned an empty currency.");if(t.currency.length>10)throw new L(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var S=g(require("fs")),f=g(require("path")),Un=g(require("os")),C=Un.homedir(),j=[{id:"claude",displayName:"Claude Code",globalConfigPath:f.join(C,".claude.json"),configKey:"mcpServers",detectPaths:[f.join(C,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:f.join(C,"Library","Application Support","Claude","claude_desktop_config.json"),configKey:"mcpServers",detectPaths:[f.join(C,"Library","Application Support","Claude")],postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:f.join(C,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[f.join(C,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:f.join(C,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[f.join(C,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:f.join(C,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[f.join(C,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:f.join(C,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[f.join(C,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:f.join(C,".vscode","mcp.json"),configKey:"servers",detectPaths:[f.join(C,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:f.join(C,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[f.join(C,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})}];function Pt(e){return j.find(t=>t.id===e)}function ye(e){return e.detectPaths.some(t=>{if(t.includes("*")){let n=f.dirname(t),r=f.basename(t).replaceAll("*","");if(!S.existsSync(n))return!1;try{return S.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return S.existsSync(t)})}function Dn(){return{command:"node",args:[f.resolve(__dirname,"mcp-server/index.js")]}}function _e(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):e.globalConfigPath,r=f.dirname(n);S.existsSync(r)||S.mkdirSync(r,{recursive:!0});let o={};if(S.existsSync(n))try{o=JSON.parse(S.readFileSync(n,"utf-8"))}catch{o={}}o[e.configKey]=o[e.configKey]||{};let s=Dn();return o[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,S.writeFileSync(n,JSON.stringify(o,null,2)+`
113
- `),{installed:!0,configPath:n,message:e.postInstallHint}}function Tt(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):e.globalConfigPath;if(!S.existsSync(n))return{removed:!1,configPath:n};let r;try{r=JSON.parse(S.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=r[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],S.writeFileSync(n,JSON.stringify(r,null,2)+`
114
- `),{removed:!0,configPath:n})}function jn(e,t="global"){let n=t==="project"?f.join(process.cwd(),".mcp.json"):e.globalConfigPath;if(!S.existsSync(n))return!1;try{return!!JSON.parse(S.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Oo(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 Uo(e,t){if(e===t)return!0;let n=f.resolve(e),r=f.resolve(t);if(n===r)return!0;try{let o=S.realpathSync(n),s=S.realpathSync(r);return o===s}catch{return!1}}function Se(){let e=Dn(),t=e.args[e.args.length-1],n=[];for(let r of j){let o=r.globalConfigPath;if(!S.existsSync(o))continue;let s;try{s=JSON.parse(S.readFileSync(o,"utf-8"))}catch{continue}let i=s?.[r.configKey]?.["visa-cli"];if(!i)continue;let a=Oo(i);if(!a||Uo(a,t))continue;let c=S.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function Ct(e){return{configPath:_e(e.client,"global").configPath}}var Xo=(0,fr.promisify)(gr.execFile);function Zo(e,t){return process.stdin.isTTY?new Promise(n=>{let r=pr.createInterface({input:process.stdin,output:process.stdout});r.question(e,o=>{r.close();let s=o.trim().toLowerCase();if(s===""){n(t);return}n(s==="y"||s==="yes")})}):Promise.resolve(t)}function Qo(e){let t=U.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
115
- ${r}: ${n(e.currentPath)}`}function hr(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(Qo(n))}var k=new mr.Command,ze=null,be=!1;function re(){return ze=new q(()=>v.getSessionToken()),ze}k.name("visa-cli").description("Visa CLI - AI payment orchestration").version(rt().version);k.hook("preAction",async()=>{await Ot()});k.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=Se();hr(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=Se(),n=new Map(t.map(d=>[d.client.id,d])),r=new Set;for(let d of j)if(ye(d)){let p=_e(d),_=n.get(d.id),x=_?` \u2014 repaired stale ${_.staleReason} entry`:"";console.log(` \u2713 ${d.displayName} (${p.configPath.replace(U.homedir(),"~")})${x}`),_&&r.add(d.id)}let o=t.filter(d=>!r.has(d.client.id));for(let d of o)Ct(d),console.log(` \u2713 ${d.client.displayName} (${d.configPath.replace(U.homedir(),"~")}) \u2014 repaired stale ${d.staleReason} entry`);let s=r.size+o.length;console.log(s===0?" \u2713 MCP config verified \u2014 nothing to repair.":` \u2713 Repaired ${s} stale MCP config ${s===1?"entry":"entries"}.`),console.log(`
116
- Step 2: Checking authentication...`);let i=await v.getSessionToken();if(i)try{await new q(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(d){let p=d instanceof Error?d.message:"";p.includes("session has expired")||p.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await v.clearAll(),i=null):console.log(` Couldn't verify session (${p||"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,p)=>{let _=Je.randomBytes(16).toString("hex"),x=`https://auth.visacli.sh/login?state=${_}`;await Ht(x);let P=3e4,E=300*1e3,H=Date.now()+E;for(;Date.now()<H;)try{let F=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:_,timeout:P}),signal:AbortSignal.timeout(P+5e3)});if(!F.ok)continue;let R=await F.json();if(R.status==="pending")continue;if(R.status==="expired"){p(new Error("Session expired. Please run setup again."));return}if(R.status==="complete"&&R.sessionToken){console.log(` Signed in as ${R.user}.`),d(R.sessionToken);return}}catch{}p(new Error("Login timed out after 5 minutes. Please run setup again."))}),await v.saveSessionToken(i),console.log(" Session token saved.")),console.log(`
117
- Step 3: Setting up authentication...`),!te())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Xo("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 hn();console.log(" Attestation key generated."),await re().registerAttestationKey(d),console.log(" Attestation key registered with server.")}catch(d){console.log(` Skipped: ${d.message}`)}}let a=we.join(U.homedir(),".claude","settings.json"),c=It.existsSync(we.join(U.homedir(),".claude.json")),l=e.hud===!1;if(c&&!l){console.log(`
118
- 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 Zo(" Enable Visa HUD? [Y/n] ",!0):(d=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),d){let p=it(a),_=p.installed==="new"||p.installed==="already-visa"||p.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${_}${p.message}`);try{let x=re(),P=await x.getStatus(),E={currentVersion:x.getClientVersion(),latestVersion:x.lastSignals?.updateAvailable?.version,updateMessage:x.lastSignals?.updateAvailable?.message,updateCheckDisabled:J()},H=$t(P,E);Ke(H),console.log(` Preview: ${H.split(`
119
- `)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let u="\x1B[1m",m="\x1B[0m";console.log(`
76
+ ${s}
77
+ `:`${s}
78
+ `}function en(e=Te()){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=Ae(e);let n=h.existsSync(t)?h.readFileSync(t,"utf-8"):"",s=Ls(n,e),r=s!==n;return r&&Ee(t,s),{installed:!0,changed:r,shell:e,rcPath:t,message:r?`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}: ${on(n)}`}}}function tn(e=Te()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=Ae(e),!h.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=h.readFileSync(t,"utf-8"),s=Qt(n);return s===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Ee(t,s.length>0?`${s}
79
+ `:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${on(n)}`}}}function st(e,t){let n=ae(t.currentVersion),s=t.latestVersion?ae(t.latestVersion):void 0,r=t.updateCheckDisabled?`v${n} | updates paused`:s?`v${n} -> v${s}`:`v${n}`;if(!e.enrolled)return`${I("[VISA PAY]",L.visaBlue)} ${I("setup needed",L.visaGold)} | ${I(r,L.visaBlueSoft)}`;let o=Qe(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),i=Math.max(0,Qe(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,Qe(e.dailyRemaining??o-i))):0,c=o>0?Math.max(0,Math.min(1,i/o)):0,p=Ms(e),u=`${String(Math.round(c*100)).padStart(3," ")}%`,d=`${I("[VISA PAY]",L.visaBlue)} ${Is(c)} ${I(u,L.green)} | ${I(p,L.visaGold)} | ${I(r,L.visaBlueSoft)}`,l=`${I("Spend",L.dim)} ${et(i)} / ${et(o)} | ${I("Left",L.dim)} ${et(a)}`;return`${d}
80
+ ${l}`}function nn(){let e=sn();return!!e&&Date.now()-e.renderedAt<=Xt}function rt(){let e=sn();if(e&&Date.now()-e.renderedAt<=Xt||(Ns(),e?.line))return e.line;try{let t=ce();if(h.existsSync(t))return h.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function Le(e){try{let t=w.dirname(ie());h.mkdirSync(t,{recursive:!0});let n=ae(e),s={hudVersion:Ps,renderedAt:Date.now(),line:n};Ee(ie(),JSON.stringify(s)+`
81
+ `),Ee(ce(),n+`
82
+ `)}catch{}}function oe(){try{h.unlinkSync(Zt())}catch{}}function sn(){let e=ie();if(!h.existsSync(e))return null;try{return JSON.parse(h.readFileSync(e,"utf-8"))}catch{return null}}function Ns(){let e=Zt();try{if(h.mkdirSync(w.dirname(e),{recursive:!0}),!Us(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){oe();return}let n=(0,Yt.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",oe),n.unref()}catch{oe()}}function Qe(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 Is(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),s="\u2588".repeat(n),r="\u2591".repeat(10-n);return`${I(s||"",L.green)}${I(r||"",L.dim)}`}function et(e){return`$${e.toFixed(2)}`}function Ms(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",s=typeof t.last4=="string"?t.last4:"????",r=ae(n.toUpperCase()),o=ae(s);return`${t.isDefault?"default":"active"} ${r} ****${o}`}function Os(){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 tt=Os(),L={reset:"\x1B[0m",visaBlue:tt?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:tt?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:tt?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function I(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${L.reset}`}function Wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rn(){let e=Re.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function Hs(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function Ds(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Us(e){for(let t=0;t<2;t+=1){let n;try{return n=h.openSync(e,"wx"),h.writeFileSync(n,String(Date.now())),!0}catch(s){if(s?.code!=="EEXIST")return!1;try{let r=h.statSync(e);if(Date.now()-r.mtimeMs<=Ts)return!1;h.unlinkSync(e)}catch{}}finally{n!==void 0&&h.closeSync(n)}}return!1}function on(e){return e instanceof Error?e.message:"unknown file system error"}function Ee(e,t){h.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;h.writeFileSync(n,t),h.renameSync(n,e)}var P=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},an=["GET","POST"];function cn(e){let t;try{t=new URL(e)}catch{throw new P(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new P(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function ln(e){let t=(e??"GET").toUpperCase();if(!an.includes(t))throw new P(`Unsupported HTTP method "${e}". Supported: ${an.join(", ")}.`);return t}function un(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new P(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function dn(e){if(!e||typeof e!="object")throw new P("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new P("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new P("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new P(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new P("Merchant returned an empty currency.");if(t.currency.length>10)throw new P(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var S=f(require("fs")),g=f(require("path")),pn=f(require("os")),_=pn.homedir(),M=[{id:"claude",displayName:"Claude Code",globalConfigPath:g.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[g.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:g.join(_,"Library","Application Support","Claude","claude_desktop_config.json"),configKey:"mcpServers",detectPaths:[g.join(_,"Library","Application Support","Claude")],postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:g.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:g.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[g.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:g.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[g.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:g.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[g.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:g.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[g.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:g.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[g.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})}];function ot(e){return M.find(t=>t.id===e)}function le(e){return e.detectPaths.some(t=>{if(t.includes("*")){let n=g.dirname(t),s=g.basename(t).replaceAll("*","");if(!S.existsSync(n))return!1;try{return S.readdirSync(n).some(r=>r.startsWith(s))}catch{return!1}}return S.existsSync(t)})}function fn(){return{command:"node",args:[g.resolve(__dirname,"mcp-server/index.js")]}}function ue(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):e.globalConfigPath,s=g.dirname(n);S.existsSync(s)||S.mkdirSync(s,{recursive:!0});let r={};if(S.existsSync(n))try{r=JSON.parse(S.readFileSync(n,"utf-8"))}catch{r={}}r[e.configKey]=r[e.configKey]||{};let o=fn();return r[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,S.writeFileSync(n,JSON.stringify(r,null,2)+`
83
+ `),{installed:!0,configPath:n,message:e.postInstallHint}}function it(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):e.globalConfigPath;if(!S.existsSync(n))return{removed:!1,configPath:n};let s;try{s=JSON.parse(S.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let r=s[e.configKey];return!r||!r["visa-cli"]?{removed:!1,configPath:n}:(delete r["visa-cli"],S.writeFileSync(n,JSON.stringify(s,null,2)+`
84
+ `),{removed:!0,configPath:n})}function mn(e,t="global"){let n=t==="project"?g.join(process.cwd(),".mcp.json"):e.globalConfigPath;if(!S.existsSync(n))return!1;try{return!!JSON.parse(S.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function js(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 Vs(e,t){if(e===t)return!0;let n=g.resolve(e),s=g.resolve(t);if(n===s)return!0;try{let r=S.realpathSync(n),o=S.realpathSync(s);return r===o}catch{return!1}}function de(){let e=fn(),t=e.args[e.args.length-1],n=[];for(let s of M){let r=s.globalConfigPath;if(!S.existsSync(r))continue;let o;try{o=JSON.parse(S.readFileSync(r,"utf-8"))}catch{continue}let i=o?.[s.configKey]?.["visa-cli"];if(!i)continue;let a=js(i);if(!a||Vs(a,t))continue;let c=S.existsSync(a)?"mismatch":"missing";n.push({client:s,configPath:r,currentPath:a,expectedPath:t,staleReason:c})}return n}function at(e){return{configPath:ue(e.client,"global").configPath}}var Fs=(0,Sn.promisify)(yn.execFile);function Bs(e,t){return process.stdin.isTTY?new Promise(n=>{let s=hn.createInterface({input:process.stdin,output:process.stdout});s.question(e,r=>{s.close();let o=r.trim().toLowerCase();if(o===""){n(t);return}n(o==="y"||o==="yes")})}):Promise.resolve(t)}function Ks(e){let t=N.homedir(),n=r=>r.replace(t,"~"),s=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
85
+ ${s}: ${n(e.currentPath)}`}function bn(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(Ks(n))}var E=new gn.Command,Ne=null,pe=!1;function J(){return Ne=new X(()=>$.getSessionToken()),Ne}E.name("visa-cli").description("Visa CLI - AI payment orchestration").version(Ve().version);E.hook("preAction",async()=>{await ft()});E.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();bn(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])),s=new Set;for(let l of M)if(le(l)){let m=ue(l),v=n.get(l.id),R=v?` \u2014 repaired stale ${v.staleReason} entry`:"";console.log(` \u2713 ${l.displayName} (${m.configPath.replace(N.homedir(),"~")})${R}`),v&&s.add(l.id)}let r=t.filter(l=>!s.has(l.client.id));for(let l of r)at(l),console.log(` \u2713 ${l.client.displayName} (${l.configPath.replace(N.homedir(),"~")}) \u2014 repaired stale ${l.staleReason} entry`);let o=s.size+r.length;console.log(o===0?" \u2713 MCP config verified \u2014 nothing to repair.":` \u2713 Repaired ${o} stale MCP config ${o===1?"entry":"entries"}.`),console.log(`
86
+ Step 2: Checking authentication...`);let i=await $.getSessionToken();if(i)try{await new X(()=>Promise.resolve(i)).getStatus(),console.log(" Already authenticated.")}catch(l){let m=l instanceof Error?l.message:"";m.includes("session has expired")||m.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await $.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(l,m)=>{let v=Ie.randomBytes(16).toString("hex"),R=`https://auth.visacli.sh/login?state=${v}`;await gt(R);let O=3e4,K=300*1e3,q=Date.now()+K;for(;Date.now()<q;)try{let ee=await globalThis.fetch("https://auth.visacli.sh/v1/auth-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:v,timeout:O}),signal:AbortSignal.timeout(O+5e3)});if(!ee.ok)continue;let T=await ee.json();if(T.status==="pending")continue;if(T.status==="expired"){m(new Error("Session expired. Please run setup again."));return}if(T.status==="complete"&&T.sessionToken){console.log(` Signed in as ${T.user}.`),l(T.sessionToken);return}}catch{}m(new Error("Login timed out after 5 minutes. Please run setup again."))}),await $.saveSessionToken(i),console.log(" Session token saved.")),console.log(`
87
+ Step 3: Setting up authentication...`),!se())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Fs("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 Bt();console.log(" Attestation key generated."),await J().registerAttestationKey(l),console.log(" Attestation key registered with server.")}catch(l){console.log(` Skipped: ${l.message}`)}}let a=fe.join(N.homedir(),".claude","settings.json"),c=ct.existsSync(fe.join(N.homedir(),".claude.json")),p=e.hud===!1;if(c&&!p){console.log(`
88
+ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info below the Claude Code input, so"),console.log(" you can see your spend, card, and session usage in real time.");let l;if(e.yes?(l=!0,console.log(" (--yes) Enabling Visa HUD.")):process.stdin.isTTY?l=await Bs(" Enable Visa HUD? [Y/n] ",!0):(l=!1,console.log(" Non-interactive shell \u2014 skipping prompt. Enable with: visa-cli hud enable")),l){let m=Be(a),v=m.installed==="new"||m.installed==="already-visa"||m.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${v}${m.message}`);try{let R=J(),O=await R.getStatus(),K={currentVersion:R.getClientVersion(),latestVersion:R.lastSignals?.updateAvailable?.version,updateMessage:R.lastSignals?.updateAvailable?.message,updateCheckDisabled:F()},q=st(O,K);Le(q),console.log(` Preview: ${q.split(`
89
+ `)[0]}`)}catch{}}else(e.yes===!1||process.stdin.isTTY)&&console.log(" Skipped. Enable any time with: visa-cli hud enable")}let u="\x1B[1m",d="\x1B[0m";console.log(`
120
90
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
121
91
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
122
92
  \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
@@ -124,30 +94,30 @@ Step 4: Enable the Visa spend HUD?`),console.log(" Pins your spend + card info
124
94
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
125
95
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
126
96
 
127
- ${u}Setup complete.${m} Restart Claude Code or run /mcp to connect.
97
+ ${u}Setup complete.${d} Restart Claude Code or run /mcp to connect.
128
98
 
129
- ${u}Try it out:${m}
99
+ ${u}Try it out:${d}
130
100
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
131
101
  \u2022 Ask Claude: "What's the price of ETH on Base?"
132
102
  \u2022 Or run: visa-cli pay <merchant-url>
133
103
 
134
- ${u}Verify:${m} visa-cli status
135
- ${u}HUD:${m} Restart Claude Code to see your spend pinned below the input
136
- ${u}Docs:${m} https://visacli.sh
137
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});k.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 s=Se();hr(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Se();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Ct(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(U.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
138
- Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
104
+ ${u}Verify:${d} visa-cli status
105
+ ${u}HUD:${d} Restart Claude Code to see your spend pinned below the input
106
+ ${u}Docs:${d} https://visacli.sh
107
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});E.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();bn(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)at(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(N.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
108
+ Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
139
109
  \x1B[1mSupported MCP Clients\x1B[0m
140
- `),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 j){let c=ye(a),l=jn(a),u=c?"Yes":"No",m=l?"Yes":"No",d=a.globalConfigPath.replace(U.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${m.padEnd(11)} ${d}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of j){if(!ye(a)){i.push(a.displayName);continue}_e(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.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(`
141
- Supported clients: ${j.map(s=>s.id).join(", ")}`),process.exit(1));let r=Pt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${j.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!ye(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=_e(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});k.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 s=[];for(let i of j)Tt(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.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(`
142
- Supported clients: ${j.map(s=>s.id).join(", ")}`),process.exit(1));let r=Pt(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${j.map(s=>s.id).join(", ")}`),process.exit(1));let o=Tt(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});k.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{Ln(e);let n=Mn(t.method),r=Nn(t.body),o=new q(()=>v.getSessionToken());console.log(`Checking payment for ${e}...`);let s=On(await o.paymentPreview({url:e}));console.log(` Merchant: ${s.merchantName}`),console.log(` Amount: $${s.amount.toFixed(2)} ${s.currency}`),console.log(` Rail: auto-detected
143
- `);let i;if(te())try{let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:s.amount,merchant:s.merchantName,context:e})).toString("base64");i={signature:await Oe(l,`pay $${s.amount.toFixed(2)} to ${s.merchantName}`),nonce:c,amount:s.amount,merchant:s.merchantName}}catch(c){console.error(`Touch ID confirmation failed: ${c?.message||"user cancelled or biometric error"}`),process.exit(1)}else console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let a=await o.pay({url:e,method:n,body:r,attestation:i,idempotencyKey:Je.randomUUID()});if(a.success){if(console.log(`Payment complete: $${(a.amount??s.amount).toFixed(2)} \u2192 ${a.merchantName??s.merchantName}`),a.receipt?.urls?.length){console.log(`
144
- Result URLs:`);for(let c of a.receipt.urls)console.log(` ${c}`)}}else console.error(`Payment failed: ${a.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof L?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});k.command("status").alias("hud").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{be=!1;try{let e=re(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:J()},r=await e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
145
- `)}return{transactions:[]}});process.stdout.write(bn(t,Array.isArray(r?.transactions)?r.transactions:[],te(),n)),be=!0}catch(e){be=!1,console.error("Error:",e.message),process.exit(1)}});k.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
146
- `);try{await re().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await v.clearAll(),console.log(" Keychain credentials cleared."),te())try{await ht(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
147
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});k.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 v.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await re().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var oe=k.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function yr(){let e=Tn();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function _r(){let e=Cn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}oe.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(yr);oe.command("enable").description("Enable the persistent shell HUD").action(yr);oe.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(_r);oe.command("disable").description("Disable the persistent shell HUD").action(_r);oe.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${xt()}
148
- `)});oe.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(m,d,p)=>{console.log(` ${d?"\u2713":"\u2717"} ${m}: ${p}`),d||(n=!1)};console.log(`Shell HUD Doctor
149
- `);let o=qe();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let m=Be(o),d=e(m);if(r("RC file exists",d,m.replace(U.homedir(),"~")),d){let _=t(m,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",_,_?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let s=ge(),i=e(s);if(r("Cache file",i,i?s.replace(U.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let m=JSON.parse(t(s,"utf-8")),d=Date.now()-(m.renderedAt??0),p=Math.round(d/1e3),_=p<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${p}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=he(),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 v.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await re().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(m){let d=m instanceof Error?m.message:"unknown error";r("API connectivity",!1,d)}console.log(n?`
110
+ `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of M){let c=le(a),p=mn(a),u=c?"Yes":"No",d=p?"Yes":"No",l=a.globalConfigPath.replace(N.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${l}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of M){if(!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(`
111
+ Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let s=ot(e);s||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!le(s)&&(console.error(`${s.displayName} not detected on this machine.`),console.error(`Expected: ${s.detectPaths.join(", ")}`),process.exit(1));let r=ue(s,n);console.log(`Registered visa-cli MCP server in ${r.configPath}`),console.log(r.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});E.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)it(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
112
+ Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let s=ot(e);s||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${M.map(o=>o.id).join(", ")}`),process.exit(1));let r=it(s,n);r.removed?console.log(`Removed visa-cli from ${r.configPath}`):console.log(`visa-cli was not installed for ${s.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});E.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{cn(e);let n=ln(t.method),s=un(t.body),r=new X(()=>$.getSessionToken());console.log(`Checking payment for ${e}...`);let o=dn(await r.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
113
+ `);let i;if(se())try{let{nonce:c}=await r.getAttestationChallenge(),p=Buffer.from(JSON.stringify({nonce:c,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");i={signature:await Kt(p,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:c,amount:o.amount,merchant:o.merchantName}}catch(c){console.error(`Touch ID confirmation failed: ${c?.message||"user cancelled or biometric error"}`),process.exit(1)}else console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let a=await r.pay({url:e,method:n,body:s,attestation:i,idempotencyKey:Ie.randomUUID()});if(a.success){if(console.log(`Payment complete: $${(a.amount??o.amount).toFixed(2)} \u2192 ${a.merchantName??o.merchantName}`),a.receipt?.urls?.length){console.log(`
114
+ Result URLs:`);for(let c of a.receipt.urls)console.log(` ${c}`)}}else console.error(`Payment failed: ${a.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof P?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});E.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{pe=!1;try{let e=J(),t=await e.getStatus(),n={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.version,updateMessage:e.lastSignals.updateAvailable?.message,updateCheckDisabled:F()},s=await e.getTransactions().catch(r=>{if(process.env.VISA_CLI_DEBUG){let o=r instanceof Error?r.message:String(r);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
115
+ `)}return{transactions:[]}});process.stdout.write(Jt(t,Array.isArray(s?.transactions)?s.transactions:[],se(),n)),pe=!0}catch(e){pe=!1,console.error("Error:",e.message),process.exit(1)}});E.command("reset").description("Log out and clear all credentials").action(async()=>{try{console.log(`Resetting Visa CLI...
116
+ `);try{await J().logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await $.clearAll(),console.log(" Keychain credentials cleared."),se())try{await qt(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
117
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});E.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 J().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}});var W=E.command("shell-hud").description("Manage the persistent Visa HUD shown in your shell prompt");function vn(){let e=en();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function wn(){let e=tn();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}W.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(vn);W.command("enable").description("Enable the persistent shell HUD").action(vn);W.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(wn);W.command("disable").description("Disable the persistent shell HUD").action(wn);W.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${rt()}
118
+ `)});W.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,s=(d,l,m)=>{console.log(` ${l?"\u2713":"\u2717"} ${d}: ${m}`),l||(n=!1)};console.log(`Shell HUD Doctor
119
+ `);let r=Te();if(s("Shell detected",!!r,r??"none (zsh, bash, or PowerShell required)"),r){let d=Ae(r),l=e(d);if(s("RC file exists",l,d.replace(N.homedir(),"~")),l){let v=t(d,"utf-8").includes("visa-cli shell hud v2");s("HUD block installed",v,v?"found in rc file":"missing \u2014 run: visa-cli shell-hud install")}}let o=ie(),i=e(o);if(s("Cache file",i,i?o.replace(N.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),l=Date.now()-(d.renderedAt??0),m=Math.round(l/1e3),v=m<=30;console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${m}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{s("Cache readable",!1,"corrupt JSON")}let a=ce(),c=e(a),p="missing";if(c)try{p=t(a,"utf-8").trim().slice(0,80)}catch{p="unreadable"}s("Line file",c,p);let u=!1;try{u=!!await $.getSessionToken()}catch{}if(s("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await J().getStatus(),s("API connectivity",!0,"GET /v1/status OK")}catch(d){let l=d instanceof Error?d.message:"unknown error";s("API connectivity",!1,l)}console.log(n?`
150
120
  All checks passed.`:`
151
- Some checks failed \u2014 see above.`),n||process.exit(1)});oe.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&&kn()))try{let t=re(),n=await t.getStatus(),r={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:J()},o=$t(n,r);Ke(o)}catch{try{It.existsSync(he())||Ke("[VISA] run visa-cli setup to activate")}catch{}}finally{pe()}});k.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await Yt(),n=xt().split(`
152
- `)[0],r=await Zt(n,e);process.stdout.write(`${r}
153
- `)});var Sr=k.command("hud").description("Manage the Visa HUD pinned below Claude Code input");Sr.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=we.join(U.homedir(),".claude","settings.json"),t=it(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Sr.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=we.join(U.homedir(),".claude","settings.json"),t=Gt(e);console.log(t.message),t.removed||process.exit(1)});k.command("dove").alias("d").description("Launch Visa Dove \u2014 AI coding agent").option("--model <model>","Model to use (e.g. or-claude-sonnet, or-gpt-4o-mini)").action(async e=>{let{startClient:t}=await Promise.resolve().then(()=>(dr(),ur));await t({model:e.model})});k.hook("postAction",()=>{if(be){be=!1;return}ze&&_n(ze.lastSignals)});k.parse();
121
+ Some checks failed \u2014 see above.`),n||process.exit(1)});W.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&&nn()))try{let t=J(),n=await t.getStatus(),s={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.version,updateMessage:t.lastSignals.updateAvailable?.message,updateCheckDisabled:F()},r=st(n,s);Le(r)}catch{try{ct.existsSync(ce())||Le("[VISA] run visa-cli setup to activate")}catch{}}finally{oe()}});E.command("statusline").description("Output the multi-line Visa HUD for Claude Code statusLine integration").action(async()=>{let e=await xt(),n=rt().split(`
122
+ `)[0],s=await Pt(n,e);process.stdout.write(`${s}
123
+ `)});var $n=E.command("hud").description("Manage the Visa HUD pinned below Claude Code input");$n.command("enable").description("Register Visa HUD as the Claude Code statusLine").action(()=>{let e=fe.join(N.homedir(),".claude","settings.json"),t=Be(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});$n.command("disable").description("Remove Visa HUD from Claude Code statusLine (leaves other tools untouched)").action(()=>{let e=fe.join(N.homedir(),".claude","settings.json"),t=wt(e);console.log(t.message),t.removed||process.exit(1)});E.hook("postAction",()=>{if(pe){pe=!1;return}Ne&&Gt(Ne.lastSignals)});E.parse();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var mn=Object.create;var Ct=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var yn=(r,e)=>()=>(r&&(e=r(r=0)),e);var _n=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),or=(r,e)=>{for(var t in e)Ct(r,t,{get:e[t],enumerable:!0})},vn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fn(e))!gn.call(r,s)&&s!==t&&Ct(r,s,{get:()=>e[s],enumerable:!(n=pn(e,s))||n.enumerable});return r};var A=(r,e,t)=>(t=r!=null?mn(hn(r)):{},vn(e||!r||!r.__esModule?Ct(t,"default",{value:r,enumerable:!0}):t,r));var cr={};or(cr,{fetchWithTimeout:()=>Pt});async function Pt(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 Nt=yn(()=>{"use strict"});var sn=_n((ho,ei)=>{ei.exports={name:"@visa/cli",version:"1.2.1-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});var un=require("@modelcontextprotocol/sdk/server/index.js"),ln=require("@modelcontextprotocol/sdk/server/stdio.js"),te=require("@modelcontextprotocol/sdk/types.js");Nt();var wn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function it(r,e){let t=ur(r),n=ur(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:bn(t.pre,n.pre)>0}function ur(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(wn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function bn(r,e){let t=r.split("."),n=e.split("."),s=Math.max(t.length,n.length);for(let a=0;a<s;a++){if(a>=t.length)return-1;if(a>=n.length)return 1;let i=t[a],o=n[a],c=/^\d+$/.test(i),l=/^\d+$/.test(o);if(c&&l){let u=Number(i)-Number(o);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function ot(){return!!(lr(process.env.VISA_CLI_NO_UPDATE_CHECK)||lr(process.env.CI)||process.env.NODE_ENV==="test")}function lr(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var $t="1.2.1-rc.0",ct=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={},!ot()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&it(n,$t)&&(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 $t}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 Pt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":$t},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${t}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(e,t){return this.request("POST","/v1/pay",e,void 0,t)}async shortcut(e,t,n,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,t,n,s)}async batch(e,t,n){return this.request("POST","/v1/batch",e,t,n)}async catalogSearch(e,t){let n=new URLSearchParams;e&&n.set("q",e),t&&n.set("category",t);let s=n.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,t){return this.request("POST","/v1/payment-preview",e,void 0,t)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,t){return this.request("POST","/v1/spending-controls",e,void 0,t)}async removeCard(e,t,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,t,void 0,n)}async setDefaultCard(e,t,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,t,void 0,n)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,t){return this.request("POST","/v1/logout",e,void 0,t)}async feedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let t=new URLSearchParams;e?.tab&&t.set("tab",e.tab),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let n=t.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(e,t){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:t})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async getFeedback(e,t){let n=new URLSearchParams;e&&n.set("limit",String(e));let s=n.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,t)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var Ut=require("child_process"),gr=require("util"),yr=A(require("crypto")),N=A(require("fs")),_r=A(require("os")),Z=A(require("path"));var j=A(require("fs")),jt=A(require("path")),dr=A(require("os")),Mt=jt.join(dr.homedir(),".visa-mcp"),Ze=jt.join(Mt,"mcp-server.log"),xn=5*1024*1024,Lt=null;function kn(){j.existsSync(Mt)||j.mkdirSync(Mt,{recursive:!0,mode:448})}function Sn(){if(!Lt){if(kn(),j.existsSync(Ze)&&j.statSync(Ze).size>xn){let e=Ze+".1";j.existsSync(e)&&j.unlinkSync(e),j.renameSync(Ze,e)}Lt=j.createWriteStream(Ze,{flags:"a"})}return Lt}function ut(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 mn=Object.create;var Ct=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var yn=(r,e)=>()=>(r&&(e=r(r=0)),e);var _n=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),or=(r,e)=>{for(var t in e)Ct(r,t,{get:e[t],enumerable:!0})},vn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fn(e))!gn.call(r,s)&&s!==t&&Ct(r,s,{get:()=>e[s],enumerable:!(n=pn(e,s))||n.enumerable});return r};var A=(r,e,t)=>(t=r!=null?mn(hn(r)):{},vn(e||!r||!r.__esModule?Ct(t,"default",{value:r,enumerable:!0}):t,r));var cr={};or(cr,{fetchWithTimeout:()=>Pt});async function Pt(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 Nt=yn(()=>{"use strict"});var sn=_n((ho,ei)=>{ei.exports={name:"@visa/cli",version:"1.2.1-rc.2",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});var un=require("@modelcontextprotocol/sdk/server/index.js"),ln=require("@modelcontextprotocol/sdk/server/stdio.js"),te=require("@modelcontextprotocol/sdk/types.js");Nt();var wn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function it(r,e){let t=ur(r),n=ur(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:bn(t.pre,n.pre)>0}function ur(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(wn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function bn(r,e){let t=r.split("."),n=e.split("."),s=Math.max(t.length,n.length);for(let a=0;a<s;a++){if(a>=t.length)return-1;if(a>=n.length)return 1;let i=t[a],o=n[a],c=/^\d+$/.test(i),l=/^\d+$/.test(o);if(c&&l){let u=Number(i)-Number(o);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function ot(){return!!(lr(process.env.VISA_CLI_NO_UPDATE_CHECK)||lr(process.env.CI)||process.env.NODE_ENV==="test")}function lr(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var $t="1.2.1-rc.2",ct=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={},!ot()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&it(n,$t)&&(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 $t}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 Pt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":$t},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${t}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(e,t){return this.request("POST","/v1/pay",e,void 0,t)}async shortcut(e,t,n,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,t,n,s)}async batch(e,t,n){return this.request("POST","/v1/batch",e,t,n)}async catalogSearch(e,t){let n=new URLSearchParams;e&&n.set("q",e),t&&n.set("category",t);let s=n.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,t){return this.request("POST","/v1/payment-preview",e,void 0,t)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,t){return this.request("POST","/v1/spending-controls",e,void 0,t)}async removeCard(e,t,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,t,void 0,n)}async setDefaultCard(e,t,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,t,void 0,n)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,t){return this.request("POST","/v1/logout",e,void 0,t)}async feedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let t=new URLSearchParams;e?.tab&&t.set("tab",e.tab),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let n=t.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(e,t){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:t})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async getFeedback(e,t){let n=new URLSearchParams;e&&n.set("limit",String(e));let s=n.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,t)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var Ut=require("child_process"),gr=require("util"),yr=A(require("crypto")),N=A(require("fs")),_r=A(require("os")),Z=A(require("path"));var j=A(require("fs")),jt=A(require("path")),dr=A(require("os")),Mt=jt.join(dr.homedir(),".visa-mcp"),Ze=jt.join(Mt,"mcp-server.log"),xn=5*1024*1024,Lt=null;function kn(){j.existsSync(Mt)||j.mkdirSync(Mt,{recursive:!0,mode:448})}function Sn(){if(!Lt){if(kn(),j.existsSync(Ze)&&j.statSync(Ze).size>xn){let e=Ze+".1";j.existsSync(e)&&j.unlinkSync(e),j.renameSync(Ze,e)}Lt=j.createWriteStream(Ze,{flags:"a"})}return Lt}function ut(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),Sn().write(s)}var m={debug:(...r)=>ut("DEBUG",...r),info:(...r)=>ut("INFO",...r),warn:(...r)=>ut("WARN",...r),error:(...r)=>ut("ERROR",...r)};var lt=(0,gr.promisify)(Ut.execFile),dt=Z.join(_r.homedir(),".visa-mcp","bin"),he=Z.join(dt,"Visa CLI"),Tn=Z.join(__dirname,"..","native"),mr="5",pr=Z.join(dt,"visa-keychain.version"),fr=Z.join(dt,"visa-keychain.sha256");function hr(r){let e=N.readFileSync(r);return yr.createHash("sha256").update(e).digest("hex")}async function vr(){try{if(N.readFileSync(pr,"utf-8").trim()===mr&&N.existsSync(he)){let n=N.readFileSync(fr,"utf-8").trim();if(hr(he)!==n)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),N.unlinkSync(he);else return he}}catch{}let r=Z.join(Tn,"visa-keychain.m");if(N.existsSync(r)||(r=Z.resolve(__dirname,"..","..","native","visa-keychain.m")),N.existsSync(r)||(r=Z.resolve(__dirname,"..","native","visa-keychain.m")),!N.existsSync(r))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");N.mkdirSync(dt,{recursive:!0,mode:448});try{await lt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",he,r],{timeout:3e4})}catch(t){throw t.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):t}let e=hr(he);return N.writeFileSync(fr,e,{mode:384}),N.writeFileSync(pr,mr,{mode:384}),he}async function In(r){let e=await vr(),t;try{t=(await lt(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 qt=null;function Dt(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:qt!==null?qt:(qt=!0,!0)}var wr="visa-cli",br="attestation-key";async function Rn(){try{let{stdout:r}=await lt("security",["find-generic-password","-s",wr,"-a",br,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function xr(r,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let t=await Rn();if(!t)throw new Error("Attestation key not found. Run setup to generate a new key.");let n=await vr(),s=["sign",r];return e&&s.push(e),new Promise((a,i)=>{let o=(0,Ut.execFile)(n,s,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?a(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});o.stdin.write(t),o.stdin.end()})}async function kr(){try{await lt("security",["delete-generic-password","-s",wr,"-a",br],{timeout:5e3})}catch{}try{await In(["delete-key"])}catch{}}var ft=require("child_process"),Sr=require("util"),oe=A(require("fs")),ht=A(require("os")),Bt=A(require("path")),G=(0,Sr.promisify)(ft.execFile),Wt=Bt.join(ht.homedir(),".visa-mcp"),mt=Bt.join(Wt,"session-token"),V="visa-cli",ie="session-token",pt="rc-access",An=5e3;async function On(){try{let{stdout:r}=await G("security",["find-generic-password","-s",V,"-a",ie,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Cn(r){try{try{await G("security",["delete-generic-password","-s",V,"-a",ie],{timeout:5e3})}catch{}return await G("security",["add-generic-password","-s",V,"-a",ie,"-w",r],{timeout:5e3}),!0}catch{return!1}}async function Pn(){try{await G("security",["delete-generic-password","-s",V,"-a",ie],{timeout:5e3})}catch{}}async function Nn(){if(!zt())return null;try{let{stdout:r}=await G("secret-tool",["lookup","service",V,"account",ie],{timeout:5e3});return r.trim()||null}catch{return null}}async function $n(r){if(!zt())return!1;try{let e=(0,ft.execFile)("secret-tool",["store","--label",`${V} ${ie}`,"service",V,"account",ie]);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"))},An))]),!0):!1}catch{return!1}}async function Ln(){if(zt())try{await G("secret-tool",["clear","service",V,"account",ie],{timeout:5e3})}catch{}}function zt(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Mn(){try{let{stdout:r}=await G("security",["find-generic-password","-s",V,"-a",pt,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function jn(r){try{try{await G("security",["delete-generic-password","-s",V,"-a",pt],{timeout:5e3})}catch{}await G("security",["add-generic-password","-s",V,"-a",pt,"-w",r],{timeout:5e3})}catch{}}async function qn(){try{await G("security",["delete-generic-password","-s",V,"-a",pt],{timeout:5e3})}catch{}}function Ht(){try{return oe.readFileSync(mt,"utf-8").trim()||null}catch{return null}}function Tr(r){oe.mkdirSync(Wt,{recursive:!0,mode:448}),oe.writeFileSync(mt,r,{mode:384}),process.platform==="win32"&&Un(mt)}function Ft(){try{oe.unlinkSync(mt)}catch{}}function Un(r){try{let e=ht.userInfo().username;(0,ft.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 Vt(){switch(process.platform){case"darwin":return{get:On,store:Cn,delete:Pn};case"linux":return{get:Nn,store:$n,delete:Ln};default:return{get:async()=>Ht(),store:async r=>{try{return Tr(r),!0}catch{return!1}},delete:async()=>Ft()}}}var L=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=Vt(),t=await e.get();if(t)return t;let n=Ht();return n?(await e.store(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let t=Vt();if(await t.store(e)){if(await t.get()===e){Ft();return}await t.delete()}if(Tr(e),Ht()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Wt} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Mn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await jn(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Vt().delete(),Ft()}static async clearAll(){await this.deleteSessionToken(),await qn()}};var gt={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 Ge(){return process.env.VISA_SPECIFIC_TOOLS!=="false"}function Ke(){return process.env.VISA_META_TOOLS!=="false"}function Ye(){return process.env.VISA_DISCOVER_TOOLS!=="false"}function Ir(r){let e=gt[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 Rr(r){let e=gt[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 yt(r,e){if(!ge.includes(r))return r;let t=gt[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 Er(r,e,t){let n=yt(r,e.tier),{tier:s,...a}=e;return O.executeTool({tool_id:n,...a},t)}var ge=Object.keys(gt);function Ar(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 Or(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 Xe=A(require("crypto")),Nr=require("child_process"),K=A(require("fs")),_t=A(require("os")),vt=A(require("path")),wt=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",S=new ct(()=>L.getSessionToken()),Dn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Cr=["","","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:",...Dn.map(r=>`\u2022 "${r.replace(/_/g," ")}" \u2192 ${r}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
5
5
  `);function D(r){if(!r||typeof r!="string"||process.env.VISA_SUPPRESS_BROWSER==="true")return;let e;try{e=new URL(r)}catch{return}if(e.protocol!=="https:"&&e.protocol!=="http:")return;let t=e.toString(),n=Ar();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let s=Or(t);if(!s){m.info(`No browser command for platform "${_t.platform()}". URL: ${t}`);return}(0,Nr.execFile)(s.cmd,s.args,a=>{a&&m.warn(`Browser open failed: ${a.message}. URL: ${t}`)})}async function C(r,e,t,n){if(!Dt()){m.warn("attestation:unavailable",{context:r});return}m.info("attestation:attempt",{context:r,amount:e,merchant:t});try{let{nonce:s}=await S.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:s,amount:e,merchant:t,context:r})).toString("base64");m.info("touchid:prompt",{context:r,amount:e,merchant:t});let i=await xr(a,n);return m.info("attestation:success",{context:r,amount:e,merchant:t}),{signature:i,nonce:s,amount:e,merchant:t}}catch(s){throw m.error("attestation:failure",{context:r,amount:e,merchant:t,error:s.message}),s}}async function W(r,e,t){let n=await S.paymentPreview({tool:r,url:e},t);if(!n||!n.merchantName||!n.amount||n.amount<=0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(n.amount)||n.amount<0||n.amount>999999)throw new Error(`Invalid payment amount: ${n.amount}. Payment rejected for safety.`);return n}function Y(r){if(r.pricingMode==="max-cap"){let e=typeof r.estimatedAmount=="number"&&r.estimatedAmount>0?` (estimated $${r.estimatedAmount.toFixed(2)})`:"";return`pay up to $${r.amount.toFixed(2)} to ${r.merchantName}${e}`}return`pay $${r.amount.toFixed(2)} to ${r.merchantName}`}function $r(){return vt.join(_t.homedir(),".visa-mcp","allium-results")}var Vn=16*1024,Hn=50*1024*1024,Fn=10;function Bn(r){return r.replace(/[^A-Za-z0-9_\-]/g,"_").slice(0,128)}function Wn(r,e){let t=$r();K.mkdirSync(t,{recursive:!0});let n=Bn(r),s=vt.join(t,`${n}.csv`);K.writeFileSync(s,e);let a=Buffer.byteLength(e),i=e.split(`
@@ -14,7 +14,7 @@
14
14
  ${n}
15
15
 
16
16
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:t}}catch(e){throw m.error("catalog:discover:error",{error:e.message}),new Error(`Failed to search tool catalog: ${e.message}`)}}async function Ss(r,e){let{tool_id:t,params:n,...s}=r,a=n||s;if(!t)throw new Error("tool_id is required. Use discover_tools first to find available tools.");m.info("catalog:execute",{tool:t});let i=await W(t,void 0,e);m.info("payment:attempt",{tool:t,amount:i.amount,merchant:i.merchantName});try{let o=await C(t,i.amount,i.merchantName,Y(i)),c=await S.shortcut(t,{...a,attestation:o},12e4,e);if(m.info("payment:success",{tool:t,amount:i.amount,merchant:i.merchantName}),c.urls?.length){c.urls.forEach(u=>D(u));let l=c.mediaType||(c.urls[0]?.match(/\.(mp4|webm|mov)/)?"video":"image");Qe({prompt:a.prompt||`${t} execution`,tool:t,mediaUrl:c.urls[0],mediaType:l,cost:c.amount??i.amount,transactionId:c.transactionId,userContext:e})}return c}catch(o){throw m.error("payment:failure",{tool:t,amount:i.amount,merchant:i.merchantName,error:o.message}),o}}var O=class{static async getStatus(e){return ds(e)}static async pay(e,t){return Zn(e,t)}static async getCards(e){return ms(e)}static async transactionHistory(e){return ps(e)}static async feedback(e,t){return fs(e,t)}static async updateSpendingControls(e,t){return hs(e,t)}static async reset(e,t){return bs(e,t)}static async login(e){return vs(e)}static async addCard(e){return ws(e)}static async removeCard(e,t){return ys(e,t)}static async setDefaultCard(e,t){return _s(e,t)}static async batch(e,t){return ls(e,t)}static async discoverTools(e){return ks(e)}static async executeTool(e,t){return Ss(e,t)}static async shortcut(e,t,n){switch(e){case"generate_image_card":return Gn(t,n);case"generate_image_fast_card":return Kn(t,n);case"generate_video_tempo_card":return Yn(t,n);case"generate_music_tempo_card":return Jn(t,n);case"check_music_status_tempo_card":return Xn(t,n);case"query_onchain_prices_card":return Qn(t,n);case"allium_explorer_card":return es(t,n);case"allium_explorer_results_card":return ts(t,n);case"pxlwall_card":return ns(t,n);default:{m.info("payment:attempt",{tool:e});try{let s=await C(e,0,""),a=await S.shortcut(e,{...t,attestation:s},void 0,n);return m.info("payment:success",{tool:e}),a.urls?.length&&a.urls.forEach(i=>D(i)),a}catch(s){throw m.error("payment:failure",{tool:e,error:s.message}),s}}}}static async submitFeedback(e,t,n){m.info("feedback:submit",{length:e.length});try{let s=await S.submitFeedback(e,t,n);return m.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw m.error("feedback:error",{error:a}),s}}static async getFeedback(e,t){m.info("feedback:list",{limit:e||20});try{let n=await S.getFeedback(e,t);return m.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let s=n instanceof Error?n.message:"Unknown error";throw m.error("feedback:error",{error:s}),n}}};var Zt=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"]),Gt=new Set(["discover_tools","execute_tool"]),Ts=new Set(ge);function Mr(r){return Zt.has(r)&&!Ge()?"VISA_SPECIFIC_TOOLS":Gt.has(r)&&!Ye()?"VISA_DISCOVER_TOOLS":Ts.has(r)&&!Ke()?"VISA_META_TOOLS":null}var bt=A(require("fs")),jr=A(require("path")),qr=A(require("os"));var Kt=jr.join(qr.homedir(),".visa-mcp"),ce=class{static ensureConfigDir(){bt.existsSync(Kt)||bt.mkdirSync(Kt,{recursive:!0,mode:448})}static getConfigDir(){return Kt}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 Yt=["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"],Is={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 Rs(r){return Is[r]||r}var ye=null;async function Jt(r){if(ye!==null)return ye;try{let{transactions:e}=await r.getTransactions();ye={};for(let t of e)t.status==="completed"&&(ye[t.tool_name]=(ye[t.tool_name]||0)+1)}catch{m.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),ye={}}return ye}function Ur(r,e,t){return Yt.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${Rs(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 et=A(require("fs")),Dr=A(require("path"));var Es=5,As={shownCodes:[]},_e=null;function Vr(){return process.env.VISA_CLI_REFERRAL_NUDGE_FILE||Dr.join(ce.getConfigDir(),"referral-nudges.json")}function Os(){if(_e)return _e;try{let r=et.readFileSync(Vr(),"utf8"),e=JSON.parse(r);return _e={shownCodes:Array.isArray(e.shownCodes)?e.shownCodes.filter(t=>typeof t=="string"):[]},_e}catch{return _e={...As},_e}}function Cs(r){_e=r;try{ce.ensureConfigDir(),et.writeFileSync(Vr(),JSON.stringify(r,null,2)+`
17
- `,{mode:384})}catch{}}function Ps(r){return r.trim().toLowerCase()}function Hr(r,e){if(e<Es)return{};if(!r.referralCode||!r.referralLink)return{};let t=Ps(r.referralCode);if(!t)return{};let n=Os();return n.shownCodes.includes(t)?{}:(Cs({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var k={};or(k,{BRAND:()=>sa,DIRTY:()=>ve,EMPTY_PATH:()=>Ms,INVALID:()=>g,NEVER:()=>Ha,OK:()=>$,ParseStatus:()=>P,Schema:()=>b,ZodAny:()=>de,ZodArray:()=>ae,ZodBigInt:()=>be,ZodBoolean:()=>xe,ZodBranded:()=>rt,ZodCatch:()=>Ne,ZodDate:()=>ke,ZodDefault:()=>Pe,ZodDiscriminatedUnion:()=>St,ZodEffects:()=>B,ZodEnum:()=>Oe,ZodError:()=>q,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>It,ZodIntersection:()=>Re,ZodIssueCode:()=>d,ZodLazy:()=>Ee,ZodLiteral:()=>Ae,ZodMap:()=>He,ZodNaN:()=>Be,ZodNativeEnum:()=>Ce,ZodNever:()=>z,ZodNull:()=>Te,ZodNullable:()=>Q,ZodNumber:()=>we,ZodObject:()=>U,ZodOptional:()=>H,ZodParsedType:()=>f,ZodPipeline:()=>nt,ZodPromise:()=>me,ZodReadonly:()=>$e,ZodRecord:()=>Tt,ZodSchema:()=>b,ZodSet:()=>Fe,ZodString:()=>le,ZodSymbol:()=>De,ZodTransformer:()=>B,ZodTuple:()=>X,ZodType:()=>b,ZodUndefined:()=>Se,ZodUnion:()=>Ie,ZodUnknown:()=>se,ZodVoid:()=>Ve,addIssueToContext:()=>p,any:()=>pa,array:()=>ya,bigint:()=>ca,boolean:()=>Qr,coerce:()=>Va,custom:()=>Yr,date:()=>ua,datetimeRegex:()=>Gr,defaultErrorMap:()=>re,discriminatedUnion:()=>ba,effect:()=>Na,enum:()=>Oa,function:()=>Ra,getErrorMap:()=>je,getParsedType:()=>J,instanceof:()=>ia,intersection:()=>xa,isAborted:()=>xt,isAsync:()=>qe,isDirty:()=>kt,isValid:()=>ue,late:()=>aa,lazy:()=>Ea,literal:()=>Aa,makeIssue:()=>tt,map:()=>Ta,nan:()=>oa,nativeEnum:()=>Ca,never:()=>ha,null:()=>ma,nullable:()=>La,number:()=>Xr,object:()=>_a,objectUtil:()=>Xt,oboolean:()=>Da,onumber:()=>Ua,optional:()=>$a,ostring:()=>qa,pipeline:()=>ja,preprocess:()=>Ma,promise:()=>Pa,quotelessJson:()=>Ns,record:()=>Sa,set:()=>Ia,setErrorMap:()=>Ls,strictObject:()=>va,string:()=>Jr,symbol:()=>la,transformer:()=>Na,tuple:()=>ka,undefined:()=>da,union:()=>wa,unknown:()=>fa,util:()=>x,void:()=>ga});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Xt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Xt||(Xt={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var d=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ns=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),q=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};q.create=r=>new q(r);var $s=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},re=$s;var Fr=re;function Ls(r){Fr=r}function je(){return Fr}var tt=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Ms=[];function p(r,e){let t=je(),n=tt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===re?void 0:re].filter(s=>!!s)});r.common.issues.push(n)}var P=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"}),ve=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),xt=r=>r.status==="aborted",kt=r=>r.status==="dirty",ue=r=>r.status==="valid",qe=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 F=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}},Br=(r,e)=>{if(ue(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 q(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return J(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Br(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ue(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=>ue(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(qe(s)?s:Promise.resolve(s));return Br(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 B({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return H.create(this,this._def)}nullable(){return Q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ae.create(this)}promise(){return me.create(this,this._def)}or(e){return Ie.create([this,e],this._def)}and(e){return Re.create(this,e,this._def)}transform(e){return new B({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Pe({...v(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new rt({typeName:_.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ne({...v(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return nt.create(this,e)}readonly(){return $e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},js=/^c[^\s-]{8,}$/i,qs=/^[0-9a-z]+$/,Us=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ds=/^[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,Vs=/^[a-z0-9_-]{21}$/i,Hs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fs=/^[-+]?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)?)??$/,Bs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ws="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qt,zs=/^(?:(?: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])$/,Zs=/^(?:(?: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])$/,Gs=/^(([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]))$/,Ks=/^(([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])$/,Ys=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Js=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zr="((\\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])))",Xs=new RegExp(`^${zr}$`);function Zr(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 Qs(r){return new RegExp(`^${Zr(r)}$`)}function Gr(r){let e=`${zr}T${Zr(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 ea(r,e){return!!((e==="v4"||!e)&&zs.test(r)||(e==="v6"||!e)&&Gs.test(r))}function ta(r,e){if(!Hs.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 ra(r,e){return!!((e==="v4"||!e)&&Zs.test(r)||(e==="v6"||!e)&&Ks.test(r))}var le=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new P,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")Bs.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")Qt||(Qt=new RegExp(Ws,"u")),Qt.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")Ds.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")Vs.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")js.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")qs.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")Us.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"?Gr(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"?Xs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Qs(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"?Fs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?ea(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"?ta(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"?ra(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"?Ys.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};le.create=r=>new le({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...v(r)});function na(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 we=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new P;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?na(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};we.create=r=>new we({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...v(r)});var be=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new P;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};be.create=r=>new be({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var xe=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.boolean,received:n.parsedType}),g}return $(e.data)}};xe.create=r=>new xe({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var ke=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),g}let n=new P,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):x.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};ke.create=r=>new ke({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...v(r)});var De=class extends b{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.symbol,received:n.parsedType}),g}return $(e.data)}};De.create=r=>new De({typeName:_.ZodSymbol,...v(r)});var Se=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.undefined,received:n.parsedType}),g}return $(e.data)}};Se.create=r=>new Se({typeName:_.ZodUndefined,...v(r)});var Te=class extends b{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.null,received:n.parsedType}),g}return $(e.data)}};Te.create=r=>new Te({typeName:_.ZodNull,...v(r)});var de=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};de.create=r=>new de({typeName:_.ZodAny,...v(r)});var se=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};se.create=r=>new se({typeName:_.ZodUnknown,...v(r)});var z=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};z.create=r=>new z({typeName:_.ZodNever,...v(r)});var Ve=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.void,received:n.parsedType}),g}return $(e.data)}};Ve.create=r=>new Ve({typeName:_.ZodVoid,...v(r)});var ae=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new F(t,i,t.path,o)))).then(i=>P.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new F(t,i,t.path,o)));return P.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)}};ae.create=(r,e)=>new ae({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...v(e)});function Ue(r){if(r instanceof U){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=H.create(Ue(n))}return new U({...r._def,shape:()=>e})}else return r instanceof ae?new ae({...r._def,type:Ue(r.element)}):r instanceof H?H.create(Ue(r.unwrap())):r instanceof Q?Q.create(Ue(r.unwrap())):r instanceof X?X.create(r.items.map(e=>Ue(e))):r}var U=class r extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof z&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let u=a[l],y=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new F(s,y,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof z){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let y=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new F(s,y,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let y=await u.key,R=await u.value;l.push({key:y,value:R,alwaysSet:u.alwaysSet})}return l}).then(l=>P.mergeObjectSync(n,l)):P.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ue(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof H;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Kr(x.objectKeys(this.shape))}};U.create=(r,e)=>new U({shape:()=>r,unknownKeys:"strip",catchall:z.create(),typeName:_.ZodObject,...v(e)});U.strictCreate=(r,e)=>new U({shape:()=>r,unknownKeys:"strict",catchall:z.create(),typeName:_.ZodObject,...v(e)});U.lazycreate=(r,e)=>new U({shape:r,unknownKeys:"strip",catchall:z.create(),typeName:_.ZodObject,...v(e)});var Ie=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new q(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new q(c));return p(t,{code:d.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};Ie.create=(r,e)=>new Ie({options:r,typeName:_.ZodUnion,...v(e)});var ne=r=>r instanceof Ee?ne(r.schema):r instanceof B?ne(r.innerType()):r instanceof Ae?[r.value]:r instanceof Oe?r.options:r instanceof Ce?x.objectValues(r.enum):r instanceof Pe?ne(r._def.innerType):r instanceof Se?[void 0]:r instanceof Te?[null]:r instanceof H?[void 0,...ne(r.unwrap())]:r instanceof Q?[null,...ne(r.unwrap())]:r instanceof rt||r instanceof $e?ne(r.unwrap()):r instanceof Ne?ne(r._def.innerType):[],St=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=ne(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function er(r,e){let t=J(r),n=J(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=x.objectKeys(e),a=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=er(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=er(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 Re=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(xt(a)||xt(i))return g;let o=er(a.value,i.value);return o.valid?((kt(a)||kt(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}))}};Re.create=(r,e,t)=>new Re({left:r,right:e,typeName:_.ZodIntersection,...v(t)});var X=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:d.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return p(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new F(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>P.mergeArray(t,i)):P.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};X.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:r,typeName:_.ZodTuple,rest:null,...v(e)})};var Tt=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:d.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new F(n,o,n.path,o)),value:i._parse(new F(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?P.mergeObjectAsync(t,s):P.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...v(n)}):new r({keyType:le.create(),valueType:e,typeName:_.ZodRecord,...v(t)})}},He=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:d.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],l)=>({key:s._parse(new F(n,o,n.path,[l,"key"])),value:a._parse(new F(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}}}};He.create=(r,e,t)=>new He({valueType:e,keyType:r,typeName:_.ZodMap,...v(t)});var Fe=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:d.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return g;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let o=[...n.data.values()].map((c,l)=>a._parse(new F(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Fe.create=(r,e)=>new Fe({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...v(e)});var It=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return tt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,je(),re].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return tt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,je(),re].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof me){let o=this;return $(async function(...c){let l=new q([]),u=await o._def.args.parseAsync(c,a).catch(w=>{throw l.addIssue(n(c,w)),l}),y=await Reflect.apply(i,this,u);return await o._def.returns._def.type.parseAsync(y,a).catch(w=>{throw l.addIssue(s(y,w)),l})})}else{let o=this;return $(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new q([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),y=o._def.returns.safeParse(u,a);if(!y.success)throw new q([s(u,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:X.create(e).rest(se.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||X.create([]).rest(se.create()),returns:t||se.create(),typeName:_.ZodFunction,...v(n)})}},Ee=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ee.create=(r,e)=>new Ee({getter:r,typeName:_.ZodLazy,...v(e)});var Ae=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ae.create=(r,e)=>new Ae({value:r,typeName:_.ZodLiteral,...v(e)});function Kr(r,e){return new Oe({values:r,typeName:_.ZodEnum,...v(e)})}var Oe=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:x.joinValues(n),received:t.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),g}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Oe.create=Kr;var Ce=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=x.objectValues(t);return p(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return $(e.data)}get enum(){return this._def.values}};Ce.create=(r,e)=>new Ce({values:r,typeName:_.ZodNativeEnum,...v(e)});var me=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};me.create=(r,e)=>new me({type:r,typeName:_.ZodPromise,...v(e)});var B=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?ve(c.value):t.value==="dirty"?ve(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"?ve(o.value):t.value==="dirty"?ve(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(!ue(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=>ue(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);x.assertNever(s)}};B.create=(r,e,t)=>new B({schema:r,typeName:_.ZodEffects,effect:e,...v(t)});B.createWithPreprocess=(r,e,t)=>new B({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...v(t)});var H=class extends b{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};H.create=(r,e)=>new H({innerType:r,typeName:_.ZodOptional,...v(e)});var Q=class extends b{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:_.ZodNullable,...v(e)});var Pe=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Pe.create=(r,e)=>new Pe({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var Ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Be=class extends b{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Be.create=r=>new Be({typeName:_.ZodNaN,...v(r)});var sa=Symbol("zod_brand"),rt=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},nt=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),ve(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},$e=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(ue(s)&&(s.value=Object.freeze(s.value)),s);return qe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};$e.create=(r,e)=>new $e({innerType:r,typeName:_.ZodReadonly,...v(e)});function Wr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Yr(r,e={},t){return r?de.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Wr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Wr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):de.create()}var aa={object:U.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var ia=(r,e={message:`Input not instance of ${r.name}`})=>Yr(t=>t instanceof r,e),Jr=le.create,Xr=we.create,oa=Be.create,ca=be.create,Qr=xe.create,ua=ke.create,la=De.create,da=Se.create,ma=Te.create,pa=de.create,fa=se.create,ha=z.create,ga=Ve.create,ya=ae.create,_a=U.create,va=U.strictCreate,wa=Ie.create,ba=St.create,xa=Re.create,ka=X.create,Sa=Tt.create,Ta=He.create,Ia=Fe.create,Ra=It.create,Ea=Ee.create,Aa=Ae.create,Oa=Oe.create,Ca=Ce.create,Pa=me.create,Na=B.create,$a=H.create,La=Q.create,Ma=B.createWithPreprocess,ja=nt.create,qa=()=>Jr().optional(),Ua=()=>Xr().optional(),Da=()=>Qr().optional(),Va={string:(r=>le.create({...r,coerce:!0})),number:(r=>we.create({...r,coerce:!0})),boolean:(r=>xe.create({...r,coerce:!0})),bigint:(r=>be.create({...r,coerce:!0})),date:(r=>ke.create({...r,coerce:!0}))};var Ha=g;var en="1.2.1-rc.0",tn=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),rn=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),nn=k.object({daily_remaining:k.number(),daily_limit:k.number()}),Fa=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),Ba=k.object({proactive:Fa,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),Wa=k.object({user:tn,usage:rn,budget:nn,suggestions:Ba}),za=k.object({user:tn,usage:rn,budget:nn});function Za(r){let e=Wa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=za.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Le(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 Ga=`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 Ps(r){return r.trim().toLowerCase()}function Hr(r,e){if(e<Es)return{};if(!r.referralCode||!r.referralLink)return{};let t=Ps(r.referralCode);if(!t)return{};let n=Os();return n.shownCodes.includes(t)?{}:(Cs({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var k={};or(k,{BRAND:()=>sa,DIRTY:()=>ve,EMPTY_PATH:()=>Ms,INVALID:()=>g,NEVER:()=>Ha,OK:()=>$,ParseStatus:()=>P,Schema:()=>b,ZodAny:()=>de,ZodArray:()=>ae,ZodBigInt:()=>be,ZodBoolean:()=>xe,ZodBranded:()=>rt,ZodCatch:()=>Ne,ZodDate:()=>ke,ZodDefault:()=>Pe,ZodDiscriminatedUnion:()=>St,ZodEffects:()=>B,ZodEnum:()=>Oe,ZodError:()=>q,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>It,ZodIntersection:()=>Re,ZodIssueCode:()=>d,ZodLazy:()=>Ee,ZodLiteral:()=>Ae,ZodMap:()=>He,ZodNaN:()=>Be,ZodNativeEnum:()=>Ce,ZodNever:()=>z,ZodNull:()=>Te,ZodNullable:()=>Q,ZodNumber:()=>we,ZodObject:()=>U,ZodOptional:()=>H,ZodParsedType:()=>f,ZodPipeline:()=>nt,ZodPromise:()=>me,ZodReadonly:()=>$e,ZodRecord:()=>Tt,ZodSchema:()=>b,ZodSet:()=>Fe,ZodString:()=>le,ZodSymbol:()=>De,ZodTransformer:()=>B,ZodTuple:()=>X,ZodType:()=>b,ZodUndefined:()=>Se,ZodUnion:()=>Ie,ZodUnknown:()=>se,ZodVoid:()=>Ve,addIssueToContext:()=>p,any:()=>pa,array:()=>ya,bigint:()=>ca,boolean:()=>Qr,coerce:()=>Va,custom:()=>Yr,date:()=>ua,datetimeRegex:()=>Gr,defaultErrorMap:()=>re,discriminatedUnion:()=>ba,effect:()=>Na,enum:()=>Oa,function:()=>Ra,getErrorMap:()=>je,getParsedType:()=>J,instanceof:()=>ia,intersection:()=>xa,isAborted:()=>xt,isAsync:()=>qe,isDirty:()=>kt,isValid:()=>ue,late:()=>aa,lazy:()=>Ea,literal:()=>Aa,makeIssue:()=>tt,map:()=>Ta,nan:()=>oa,nativeEnum:()=>Ca,never:()=>ha,null:()=>ma,nullable:()=>La,number:()=>Xr,object:()=>_a,objectUtil:()=>Xt,oboolean:()=>Da,onumber:()=>Ua,optional:()=>$a,ostring:()=>qa,pipeline:()=>ja,preprocess:()=>Ma,promise:()=>Pa,quotelessJson:()=>Ns,record:()=>Sa,set:()=>Ia,setErrorMap:()=>Ls,strictObject:()=>va,string:()=>Jr,symbol:()=>la,transformer:()=>Na,tuple:()=>ka,undefined:()=>da,union:()=>wa,unknown:()=>fa,util:()=>x,void:()=>ga});var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Xt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Xt||(Xt={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var d=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ns=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),q=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};q.create=r=>new q(r);var $s=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},re=$s;var Fr=re;function Ls(r){Fr=r}function je(){return Fr}var tt=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Ms=[];function p(r,e){let t=je(),n=tt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===re?void 0:re].filter(s=>!!s)});r.common.issues.push(n)}var P=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"}),ve=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),xt=r=>r.status==="aborted",kt=r=>r.status==="dirty",ue=r=>r.status==="valid",qe=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 F=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}},Br=(r,e)=>{if(ue(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 q(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var b=class{get description(){return this._def.description}_getType(e){return J(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:J(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Br(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ue(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=>ue(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:J(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(qe(s)?s:Promise.resolve(s));return Br(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 B({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return H.create(this,this._def)}nullable(){return Q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ae.create(this)}promise(){return me.create(this,this._def)}or(e){return Ie.create([this,e],this._def)}and(e){return Re.create(this,e,this._def)}transform(e){return new B({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Pe({...v(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new rt({typeName:_.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ne({...v(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return nt.create(this,e)}readonly(){return $e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},js=/^c[^\s-]{8,}$/i,qs=/^[0-9a-z]+$/,Us=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ds=/^[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,Vs=/^[a-z0-9_-]{21}$/i,Hs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fs=/^[-+]?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)?)??$/,Bs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ws="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qt,zs=/^(?:(?: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])$/,Zs=/^(?:(?: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])$/,Gs=/^(([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]))$/,Ks=/^(([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])$/,Ys=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Js=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zr="((\\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])))",Xs=new RegExp(`^${zr}$`);function Zr(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 Qs(r){return new RegExp(`^${Zr(r)}$`)}function Gr(r){let e=`${zr}T${Zr(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 ea(r,e){return!!((e==="v4"||!e)&&zs.test(r)||(e==="v6"||!e)&&Gs.test(r))}function ta(r,e){if(!Hs.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 ra(r,e){return!!((e==="v4"||!e)&&Zs.test(r)||(e==="v6"||!e)&&Ks.test(r))}var le=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new P,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")Bs.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")Qt||(Qt=new RegExp(Ws,"u")),Qt.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")Ds.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")Vs.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")js.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")qs.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")Us.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"?Gr(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"?Xs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Qs(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"?Fs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?ea(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"?ta(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"?ra(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"?Ys.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};le.create=r=>new le({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...v(r)});function na(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 we=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new P;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?na(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};we.create=r=>new we({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...v(r)});var be=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new P;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};be.create=r=>new be({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var xe=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.boolean,received:n.parsedType}),g}return $(e.data)}};xe.create=r=>new xe({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var ke=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),g}let n=new P,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):x.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};ke.create=r=>new ke({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...v(r)});var De=class extends b{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.symbol,received:n.parsedType}),g}return $(e.data)}};De.create=r=>new De({typeName:_.ZodSymbol,...v(r)});var Se=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.undefined,received:n.parsedType}),g}return $(e.data)}};Se.create=r=>new Se({typeName:_.ZodUndefined,...v(r)});var Te=class extends b{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.null,received:n.parsedType}),g}return $(e.data)}};Te.create=r=>new Te({typeName:_.ZodNull,...v(r)});var de=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};de.create=r=>new de({typeName:_.ZodAny,...v(r)});var se=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};se.create=r=>new se({typeName:_.ZodUnknown,...v(r)});var z=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};z.create=r=>new z({typeName:_.ZodNever,...v(r)});var Ve=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.void,received:n.parsedType}),g}return $(e.data)}};Ve.create=r=>new Ve({typeName:_.ZodVoid,...v(r)});var ae=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new F(t,i,t.path,o)))).then(i=>P.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new F(t,i,t.path,o)));return P.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)}};ae.create=(r,e)=>new ae({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...v(e)});function Ue(r){if(r instanceof U){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=H.create(Ue(n))}return new U({...r._def,shape:()=>e})}else return r instanceof ae?new ae({...r._def,type:Ue(r.element)}):r instanceof H?H.create(Ue(r.unwrap())):r instanceof Q?Q.create(Ue(r.unwrap())):r instanceof X?X.create(r.items.map(e=>Ue(e))):r}var U=class r extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof z&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let u=a[l],y=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new F(s,y,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof z){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")o.length>0&&(p(s,{code:d.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of o){let y=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new F(s,y,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let y=await u.key,R=await u.value;l.push({key:y,value:R,alwaysSet:u.alwaysSet})}return l}).then(l=>P.mergeObjectSync(n,l)):P.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ue(this)}partial(e){let t={};for(let n of x.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof H;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Kr(x.objectKeys(this.shape))}};U.create=(r,e)=>new U({shape:()=>r,unknownKeys:"strip",catchall:z.create(),typeName:_.ZodObject,...v(e)});U.strictCreate=(r,e)=>new U({shape:()=>r,unknownKeys:"strict",catchall:z.create(),typeName:_.ZodObject,...v(e)});U.lazycreate=(r,e)=>new U({shape:r,unknownKeys:"strip",catchall:z.create(),typeName:_.ZodObject,...v(e)});var Ie=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new q(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new q(c));return p(t,{code:d.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};Ie.create=(r,e)=>new Ie({options:r,typeName:_.ZodUnion,...v(e)});var ne=r=>r instanceof Ee?ne(r.schema):r instanceof B?ne(r.innerType()):r instanceof Ae?[r.value]:r instanceof Oe?r.options:r instanceof Ce?x.objectValues(r.enum):r instanceof Pe?ne(r._def.innerType):r instanceof Se?[void 0]:r instanceof Te?[null]:r instanceof H?[void 0,...ne(r.unwrap())]:r instanceof Q?[null,...ne(r.unwrap())]:r instanceof rt||r instanceof $e?ne(r.unwrap()):r instanceof Ne?ne(r._def.innerType):[],St=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=ne(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function er(r,e){let t=J(r),n=J(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=x.objectKeys(e),a=x.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=er(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=er(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 Re=class extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(xt(a)||xt(i))return g;let o=er(a.value,i.value);return o.valid?((kt(a)||kt(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}))}};Re.create=(r,e,t)=>new Re({left:r,right:e,typeName:_.ZodIntersection,...v(t)});var X=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:d.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return p(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new F(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>P.mergeArray(t,i)):P.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};X.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:r,typeName:_.ZodTuple,rest:null,...v(e)})};var Tt=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:d.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new F(n,o,n.path,o)),value:i._parse(new F(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?P.mergeObjectAsync(t,s):P.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...v(n)}):new r({keyType:le.create(),valueType:e,typeName:_.ZodRecord,...v(t)})}},He=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:d.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],l)=>({key:s._parse(new F(n,o,n.path,[l,"key"])),value:a._parse(new F(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return g;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(l.value,u.value)}return{status:t.value,value:o}}}};He.create=(r,e,t)=>new He({valueType:e,keyType:r,typeName:_.ZodMap,...v(t)});var Fe=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:d.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return g;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let o=[...n.data.values()].map((c,l)=>a._parse(new F(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Fe.create=(r,e)=>new Fe({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...v(e)});var It=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return tt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,je(),re].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(o,c){return tt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,je(),re].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof me){let o=this;return $(async function(...c){let l=new q([]),u=await o._def.args.parseAsync(c,a).catch(w=>{throw l.addIssue(n(c,w)),l}),y=await Reflect.apply(i,this,u);return await o._def.returns._def.type.parseAsync(y,a).catch(w=>{throw l.addIssue(s(y,w)),l})})}else{let o=this;return $(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new q([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),y=o._def.returns.safeParse(u,a);if(!y.success)throw new q([s(u,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:X.create(e).rest(se.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||X.create([]).rest(se.create()),returns:t||se.create(),typeName:_.ZodFunction,...v(n)})}},Ee=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ee.create=(r,e)=>new Ee({getter:r,typeName:_.ZodLazy,...v(e)});var Ae=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ae.create=(r,e)=>new Ae({value:r,typeName:_.ZodLiteral,...v(e)});function Kr(r,e){return new Oe({values:r,typeName:_.ZodEnum,...v(e)})}var Oe=class r extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:x.joinValues(n),received:t.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),g}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Oe.create=Kr;var Ce=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=x.objectValues(t);return p(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=x.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),g}return $(e.data)}get enum(){return this._def.values}};Ce.create=(r,e)=>new Ce({values:r,typeName:_.ZodNativeEnum,...v(e)});var me=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};me.create=(r,e)=>new me({type:r,typeName:_.ZodPromise,...v(e)});var B=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?ve(c.value):t.value==="dirty"?ve(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"?ve(o.value):t.value==="dirty"?ve(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(!ue(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=>ue(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);x.assertNever(s)}};B.create=(r,e,t)=>new B({schema:r,typeName:_.ZodEffects,effect:e,...v(t)});B.createWithPreprocess=(r,e,t)=>new B({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...v(t)});var H=class extends b{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};H.create=(r,e)=>new H({innerType:r,typeName:_.ZodOptional,...v(e)});var Q=class extends b{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:_.ZodNullable,...v(e)});var Pe=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Pe.create=(r,e)=>new Pe({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var Ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Be=class extends b{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Be.create=r=>new Be({typeName:_.ZodNaN,...v(r)});var sa=Symbol("zod_brand"),rt=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},nt=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),ve(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},$e=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=s=>(ue(s)&&(s.value=Object.freeze(s.value)),s);return qe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};$e.create=(r,e)=>new $e({innerType:r,typeName:_.ZodReadonly,...v(e)});function Wr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Yr(r,e={},t){return r?de.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Wr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Wr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):de.create()}var aa={object:U.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var ia=(r,e={message:`Input not instance of ${r.name}`})=>Yr(t=>t instanceof r,e),Jr=le.create,Xr=we.create,oa=Be.create,ca=be.create,Qr=xe.create,ua=ke.create,la=De.create,da=Se.create,ma=Te.create,pa=de.create,fa=se.create,ha=z.create,ga=Ve.create,ya=ae.create,_a=U.create,va=U.strictCreate,wa=Ie.create,ba=St.create,xa=Re.create,ka=X.create,Sa=Tt.create,Ta=He.create,Ia=Fe.create,Ra=It.create,Ea=Ee.create,Aa=Ae.create,Oa=Oe.create,Ca=Ce.create,Pa=me.create,Na=B.create,$a=H.create,La=Q.create,Ma=B.createWithPreprocess,ja=nt.create,qa=()=>Jr().optional(),Ua=()=>Xr().optional(),Da=()=>Qr().optional(),Va={string:(r=>le.create({...r,coerce:!0})),number:(r=>we.create({...r,coerce:!0})),boolean:(r=>xe.create({...r,coerce:!0})),bigint:(r=>be.create({...r,coerce:!0})),date:(r=>ke.create({...r,coerce:!0}))};var Ha=g;var en="1.2.1-rc.2",tn=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),rn=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),nn=k.object({daily_remaining:k.number(),daily_limit:k.number()}),Fa=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),Ba=k.object({proactive:Fa,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),Wa=k.object({user:tn,usage:rn,budget:nn,suggestions:Ba}),za=k.object({user:tn,usage:rn,budget:nn});function Za(r){let e=Wa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=za.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Le(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 Ga=`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.2.1-rc.0",
3
+ "version": "1.2.1-rc.2",
4
4
  "description": "AI-powered payments for Claude Code",
5
5
  "bin": {
6
6
  "visa-cli": "./bin/visa-cli.js"