@visa/cli 2.0.2-rc.1 → 2.1.0-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,4 +1,4 @@
1
- "use strict";var Pl=Object.create;var ms=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var Ol=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Ll=Object.prototype.hasOwnProperty;var Dl=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Qo=(e,t)=>{for(var n in t)ms(e,n,{get:t[n],enumerable:!0})},Ul=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ol(t))!Ll.call(e,s)&&s!==n&&ms(e,s,{get:()=>t[s],enumerable:!(r=Ml(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Pl(Nl(e)):{},Ul(t||!e||!e.__esModule?ms(n,"default",{value:e,enumerable:!0}):n,e));var ar=Xo((mh,Zl)=>{Zl.exports={name:"@visa/cli",version:"2.0.2-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",pretest:"pnpm build",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/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Br=Xo(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.micros=lp;ee.fromCents=up;ee.fromUsdc=dp;ee.fromUsd=mp;ee.toCents=pp;ee.toCentsForAcquirer=fp;ee.toUsdc=gp;ee.toWire=hp;ee.fromWire=yp;ee.toDisplay=_p;ee.toUsdRounded2dp=bp;ee.add=vp;ee.sub=Sp;ee.clampNonNegative=wp;ee.isNonNegative=xp;ee.max=Cp;ee.min=kp;var et=10000n,dc=1000000n;function lp(e){return e}function up(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*et}function dp(e){return e}function mp(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function pp(e){if(e>=0n)return Number(e/et);let t=e/et,n=e%et;return Number(n===0n?t:t-1n)}function fp(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/et)}function gp(e){return e}function hp(e){return e.toString()}function yp(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function _p(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/dc,a=o%dc,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function bp(e){let t=e<0n,n=t?-e:e,r=n/et,o=n%et*2n,i;o<et?i=r:o>et?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function vp(e,t){return e+t}function Sp(e,t){return e-t}function wp(e){return e<0n?0n:e}function xp(e){return e>=0n}function Cp(e,t){return e>t?e:t}function kp(e,t){return e<t?e:t}});var os={};Qo(os,{initSentry:()=>Cg,isSentryConfigured:()=>xg,reportFatal:()=>kg});function xg(){return!1}async function Cg(){return null}async function kg(e,t){process.exit(t?.exitCode??1)}var is=Dl(()=>{});var pl=require("commander"),er=R(require("crypto")),Oe=R(require("fs")),X=R(require("os")),st=R(require("path")),fl=require("child_process"),gl=R(require("node:readline/promises")),hl=require("util");var or=require("child_process"),li=require("util"),ut=R(require("fs")),ir=R(require("os")),_s=R(require("path"));var ri=R(require("crypto"));var Ke="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var si="VISA_ALLOW_INSECURE_MOCKS",ei,ti,ni;function ps(e){return`${e}-${ri.randomBytes(24).toString("base64url")}`}function oi(e=process.env){return e.NODE_ENV==="test"||e[si]==="true"}function ct(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&oi(e)}function En(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&oi(e)}function fs(){return`Set ${si}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function ii(){return ei??=ps("mock-session"),ei}function ai(e=process.env){return e.NODE_ENV==="test"?Ke:(ti??=ps("mock-rc"),ti)}function ci(){return ni??=ps("mock-signature"),ni}var Ne=(0,li.promisify)(or.execFile),bs=_s.join(ir.homedir(),".visa-mcp"),An=_s.join(bs,"session-token"),Se="visa-cli",lt="session-token",rr="rc-access",jl=5e3,sr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function ql(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
1
+ "use strict";var Pl=Object.create;var ms=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var Ol=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Ll=Object.prototype.hasOwnProperty;var Dl=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Qo=(e,t)=>{for(var n in t)ms(e,n,{get:t[n],enumerable:!0})},Ul=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ol(t))!Ll.call(e,s)&&s!==n&&ms(e,s,{get:()=>t[s],enumerable:!(r=Ml(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Pl(Nl(e)):{},Ul(t||!e||!e.__esModule?ms(n,"default",{value:e,enumerable:!0}):n,e));var ar=Xo((mh,Zl)=>{Zl.exports={name:"@visa/cli",version:"2.1.0-rc.2",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",pretest:"pnpm build",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/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Br=Xo(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.micros=lp;ee.fromCents=up;ee.fromUsdc=dp;ee.fromUsd=mp;ee.toCents=pp;ee.toCentsForAcquirer=fp;ee.toUsdc=gp;ee.toWire=hp;ee.fromWire=yp;ee.toDisplay=_p;ee.toUsdRounded2dp=bp;ee.add=vp;ee.sub=Sp;ee.clampNonNegative=wp;ee.isNonNegative=xp;ee.max=Cp;ee.min=kp;var et=10000n,dc=1000000n;function lp(e){return e}function up(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*et}function dp(e){return e}function mp(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function pp(e){if(e>=0n)return Number(e/et);let t=e/et,n=e%et;return Number(n===0n?t:t-1n)}function fp(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/et)}function gp(e){return e}function hp(e){return e.toString()}function yp(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function _p(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/dc,a=o%dc,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function bp(e){let t=e<0n,n=t?-e:e,r=n/et,o=n%et*2n,i;o<et?i=r:o>et?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function vp(e,t){return e+t}function Sp(e,t){return e-t}function wp(e){return e<0n?0n:e}function xp(e){return e>=0n}function Cp(e,t){return e>t?e:t}function kp(e,t){return e<t?e:t}});var os={};Qo(os,{initSentry:()=>Cg,isSentryConfigured:()=>xg,reportFatal:()=>kg});function xg(){return!1}async function Cg(){return null}async function kg(e,t){process.exit(t?.exitCode??1)}var is=Dl(()=>{});var pl=require("commander"),er=R(require("crypto")),Oe=R(require("fs")),X=R(require("os")),st=R(require("path")),fl=require("child_process"),gl=R(require("node:readline/promises")),hl=require("util");var or=require("child_process"),li=require("util"),ut=R(require("fs")),ir=R(require("os")),_s=R(require("path"));var ri=R(require("crypto"));var Ke="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var si="VISA_ALLOW_INSECURE_MOCKS",ei,ti,ni;function ps(e){return`${e}-${ri.randomBytes(24).toString("base64url")}`}function oi(e=process.env){return e.NODE_ENV==="test"||e[si]==="true"}function ct(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&oi(e)}function En(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&oi(e)}function fs(){return`Set ${si}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function ii(){return ei??=ps("mock-session"),ei}function ai(e=process.env){return e.NODE_ENV==="test"?Ke:(ti??=ps("mock-rc"),ti)}function ci(){return ni??=ps("mock-signature"),ni}var Ne=(0,li.promisify)(or.execFile),bs=_s.join(ir.homedir(),".visa-mcp"),An=_s.join(bs,"session-token"),Se="visa-cli",lt="session-token",rr="rc-access",jl=5e3,sr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function ql(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
2
  `)}function ui(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=ql(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Vl(){try{let{stdout:e}=await Ne("security",["find-generic-password","-s",Se,"-a",lt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ui(e))throw new sr("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function Fl(e){try{try{await Ne("security",["delete-generic-password","-s",Se,"-a",lt],{timeout:5e3})}catch{}return await Ne("security",["add-generic-password","-s",Se,"-a",lt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Bl(){try{await Ne("security",["delete-generic-password","-s",Se,"-a",lt],{timeout:5e3})}catch{}}async function Hl(){if(!vs())return null;try{let{stdout:e}=await Ne("secret-tool",["lookup","service",Se,"account",lt],{timeout:5e3});return e.trim()||null}catch{return null}}async function Kl(e){if(!vs())return!1;try{let t=(0,or.execFile)("secret-tool",["store","--label",`${Se} ${lt}`,"service",Se,"account",lt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},jl))]),!0):!1}catch{return!1}}async function Gl(){if(vs())try{await Ne("secret-tool",["clear","service",Se,"account",lt],{timeout:5e3})}catch{}}function vs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function zl(){try{let{stdout:e}=await Ne("security",["find-generic-password","-s",Se,"-a",rr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Wl(e){try{try{await Ne("security",["delete-generic-password","-s",Se,"-a",rr],{timeout:5e3})}catch{}await Ne("security",["add-generic-password","-s",Se,"-a",rr,"-w",e],{timeout:5e3})}catch{}}async function Jl(){try{await Ne("security",["delete-generic-password","-s",Se,"-a",rr],{timeout:5e3})}catch{}}function hs(){try{return ut.readFileSync(An,"utf-8").trim()||null}catch(e){if(ui(e))throw new sr(`Unable to read Visa CLI credentials from ${An}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function di(e){ut.mkdirSync(bs,{recursive:!0,mode:448}),ut.writeFileSync(An,e,{mode:384}),process.platform==="win32"&&Yl(An)}function ys(){try{ut.unlinkSync(An)}catch{}}function Yl(e){try{let t=ir.userInfo().username;(0,or.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 gs(){switch(process.platform){case"darwin":return{get:Vl,store:Fl,delete:Bl};case"linux":return{get:Hl,store:Kl,delete:Gl};default:return{get:async()=>hs(),store:async e=>{try{return di(e),!0}catch{return!1}},delete:async()=>ys(),storesInSessionFile:!0}}}var D=class{static async getSessionToken(){if(ct())return Promise.resolve(ii());let t=gs(),n=await t.get();if(n)return n;let r=hs();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(ct())return;let n=gs();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||ys();return}await n.delete()}if(di(t),hs()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${bs} is writable.`))}static async getRcAccessToken(){return ct()?ai():zl()}static async saveRcAccessToken(t){ct()||await Wl(t)}static async deleteSessionToken(){if(ct())return;await gs().delete(),ys()}static async clearAll(){await this.deleteSessionToken(),await Jl()}};var cr=R(require("crypto")),lr=R(require("tty")),ur=R(require("fs"));function Xl(e){return/-rc\.|-beta\./.test(e)}function Ss(e){return cr.createHash("sha256").update(e.trim()).digest("hex")}function mi(e){return Ke==="SKIP"?!0:cr.timingSafeEqual(Buffer.from(Ss(e)),Buffer.from(Ke))}function Ql(){try{let e=ur.openSync("/dev/tty","r+"),t=new lr.ReadStream(e),n=new lr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{ur.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function eu(e){return new Promise((t,n)=>{let r;try{r=Ql()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
3
  `?(o.write(`
4
4
  `),a(),t(l)):u===""?(o.write(`
@@ -33,8 +33,8 @@ ${a}`}function yu(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
33
33
  `))}}}return i}var xu=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function Cu(e){let t=Ri(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return xu.some(r=>n.includes(`"${r}"`))}async function Mi(e,t,n){let r=await Pi(e,t,n),s=r.join(`
34
34
  `),{isActive:o}=Ii(e,n,t?.transcript_path);return{schemaVersion:lu,client:t?Li(t):At.UNKNOWN,rendered:s,lines:r.map(As),visa:{spendLine:As(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?Ui(t):{}}}function J(e){return e?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 fr(e){if(typeof e=="string")return J(Le.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 J(t?Le.basename(t):e.name)}function Oi(e){return J(e.app_name??e.appName??e.app??e.client)}function pr(e){return J(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Ni(e){return J(e.cwd??e.current_dir??e.project_root)}function Ti(e){let t=J(e.project);if(t)return t;let n=Ni(e);if(n)return J(Le.basename(n));let r=fr(e.workspace);return r||""}function Ee(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Li(e){let t=Oi(e).toLowerCase();return t.includes("codex")?At.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?At.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Ee(e.context_used)!==void 0?At.CODEX:At.UNKNOWN}function Di(e){return Li(e)===At.CODEX}function Ui(e){let t=Oi(e),n=Ni(e),r=fr(e.workspace),s=Ee(e.context_used)??Ee(e.context_window?.used_percentage??void 0),o=Ee(e.context_remaining)??Ee(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...pr(e)?{model:pr(e)}:{},...Ti(e)?{project:Ti(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...J(e.git_branch??e.branch)?{gitBranch:J(e.git_branch??e.branch)}:{},...J(e.status??e.run_state??e.runState)?{status:J(e.status??e.run_state??e.runState)}:{},...J(e.thread_title??e.threadTitle)?{threadTitle:J(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...Ee(e.used_tokens)!==void 0?{usedTokens:Ee(e.used_tokens)}:{},...Ee(e.total_input_tokens)!==void 0?{totalInputTokens:Ee(e.total_input_tokens)}:{},...Ee(e.total_output_tokens)!==void 0?{totalOutputTokens:Ee(e.total_output_tokens)}:{}}}function As(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function Rt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var $t=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},en=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},It=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},re=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var ji={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function $s(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&ji[n]?ji[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var ku=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Vi(e,t){let n=qi(e),r=qi(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Tu(n.pre,r.pre)>0}function qi(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(ku);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Tu(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function De(){return!!(Fi(process.env.VISA_CLI_NO_UPDATE_CHECK)||Fi(process.env.CI)||process.env.NODE_ENV==="test")}function Fi(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var pt=R(require("fs")),Ds=require("node:net"),zi=R(require("os")),Wi=R(require("path"));var gr=R(require("fs")),Bi=R(require("path")),Hi=R(require("os"));var Is=Bi.join(Hi.homedir(),".visa-mcp"),In=class{static ensureConfigDir(){gr.existsSync(Is)||gr.mkdirSync(Is,{recursive:!0,mode:448})}static getConfigDir(){return Is}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,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:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};var me=R(require("fs")),Os=R(require("path")),Ki=R(require("os")),Ms=Os.join(Ki.homedir(),".visa-mcp"),Pn=Os.join(Ms,"mcp-server.log"),Eu=5*1024*1024,Ps=null;function Au(){me.existsSync(Ms)||me.mkdirSync(Ms,{recursive:!0,mode:448})}function Ru(){if(!Ps){if(Au(),me.existsSync(Pn)&&me.statSync(Pn).size>Eu){let t=Pn+".1";me.existsSync(t)&&me.unlinkSync(t),me.renameSync(Pn,t)}Ps=me.createWriteStream(Pn,{flags:"a"})}return Ps}function $u(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function hr(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
35
35
  `;$u(e)&&process.stderr.write(s),Ru().write(s)}var m={debug:(...e)=>hr("DEBUG",...e),info:(...e)=>hr("INFO",...e),warn:(...e)=>hr("WARN",...e),error:(...e)=>hr("ERROR",...e)};function Gi(e){let t=zi.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Iu="settings.json",Pu="must use https unless it points at localhost/loopback for local development";function Mn(){return Wi.join(In.getConfigDir(),Iu)}function Ji(e){if((0,Ds.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Mu(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Ji(s)}function Ou(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Ds.isIP)(t);return n===4?Ji(t):n===6?t==="::1"||Mu(t):!1}function Ns(e,t="auth.serverUrl"){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(n.username||n.password)throw new Error(`${t} must not include username or password credentials`);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&Ou(n.hostname)))throw new Error(`${t} ${Pu}`)}var ft={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");Ns(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Us=500,yr={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};function Pt(){let e=Mn();if(!pt.existsSync(e))return{};try{let t=pt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:Gi(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:Gi(e),error:t?.message||String(t)}),{}}}function Ls(e){In.ensureConfigDir();let t=Mn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
36
- `;pt.writeFileSync(n,r,{mode:384}),pt.renameSync(n,t)}function js(e){let t=Pt()[e];return typeof t=="string"?t:void 0}function _r(e){let t=Pt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function qs(e){let t=Pt()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}var ze=class extends Error{constructor(t){let n=Object.keys(ft).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},We=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},mt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+yr[t]),this.name="RetiredSettingKeyError"}},Yi=["biometric.","spending.","account.","cards.","biometric"];function br(e,t){if(Yi.some(o=>e.startsWith(o)))throw new We(e);if(e in yr)throw new mt(e);let n=ft[e];if(!n)throw new ze(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=Pt();return s[e]=r,Ls(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Mn()}}function vr(e){if(Yi.some(o=>e.startsWith(o)))throw new We(e);let t=ft[e];if(e in yr){let o=Pt(),i=e in o;return i&&(delete o[e],Ls(o)),{key:e,removed:i,requiresRestart:!1,path:Mn()}}if(!t)throw new ze(e);let r=Pt(),s=e in r;return s&&(delete r[e],Ls(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Mn()}}function Zi(){let e=Pt();return Object.entries(yr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Nu="https://auth.visacli.sh";function Lu(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Du(){try{let e=ar();return Lu(e.version)}catch{return!1}}function Uu(e){return e.envVar!==void 0&&e.envVar!==""?(Ns(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Ns(e.settingValue,"auth.serverUrl"),e.settingValue):Nu}function we(){return Uu({envVar:process.env.VISA_AUTH_URL,settingValue:js("auth.serverUrl"),isPrerelease:Du()})}function Xi(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":_r("ui.suppressBrowser")??!1}function Qi(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":_r("ui.suppressFeed")??!1}function ea(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=qs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Us}var On="2.0.2-rc.1",ju=/^vk_[A-Za-z0-9_-]{32,}$/;function qu(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var Vu="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function tn(e){return typeof e=="string"?e.trim():""}function ta(e){let t=e&&typeof e=="object"?e:{},n=tn(t.error)||tn(t.message);if(!n)return Vu;let r=tn(t.error_code),s=[["surface",tn(t.disabled_surface)],["flag",tn(t.flag)],["correlation_id",tn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function na(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r?ju.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
37
- `)}var pe=class{constructor(t){this.getSessionToken=t;this.baseUrl=we()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!De()){let r=t.headers.get("X-Latest-Version");r&&Vi(r,On)&&(this.lastSignals.updateAvailable={currentVersion:On,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return On}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new $t(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(ta(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(na());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Rt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":On,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error($s(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=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){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new re(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",g=typeof u?.error_code=="string"?u.error_code:"";throw g==="SPENDING_LIMIT_EXCEEDED"||g==="DAILY_LIMIT_EXCEEDED"||g==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(na());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":On,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Rt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(x){throw new Error($s(x))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let x=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${x}s. Tip: use the batch tool to combine multiple requests into one.`)}let g=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(d.headers.get("Retry-After"))||1;throw new It(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",y,d.status)}throw new Error(ta(f))}let x=qu(f?.error_code);if(x||d.status===410){let y=x??"BUDGET_CLOSED";throw new en(f?.message||f?.error||"Your session was invalidated by the server.",y,{budgetId:n.session_budget_id,status:d.status})}if(f?.declined){let y=Number(f.retryAfter??d.headers.get("Retry-After"));throw new re(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(y)&&y>0?y:void 0)}throw new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:g}}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Rt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await Rt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}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 startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};Qo(p,{BRAND:()=>pd,DIRTY:()=>Mt,EMPTY_PATH:()=>Ku,INVALID:()=>k,NEVER:()=>Zd,OK:()=>ae,ParseStatus:()=>se,Schema:()=>M,ZodAny:()=>yt,ZodArray:()=>Xe,ZodBigInt:()=>Nt,ZodBoolean:()=>Lt,ZodBranded:()=>Ln,ZodCatch:()=>zt,ZodDate:()=>Dt,ZodDefault:()=>Gt,ZodDiscriminatedUnion:()=>xr,ZodEffects:()=>ke,ZodEnum:()=>Ht,ZodError:()=>fe,ZodFirstPartyTypeKind:()=>E,ZodFunction:()=>kr,ZodIntersection:()=>Vt,ZodIssueCode:()=>h,ZodLazy:()=>Ft,ZodLiteral:()=>Bt,ZodMap:()=>cn,ZodNaN:()=>un,ZodNativeEnum:()=>Kt,ZodNever:()=>Ae,ZodNull:()=>jt,ZodNullable:()=>qe,ZodNumber:()=>Ot,ZodObject:()=>ge,ZodOptional:()=>xe,ZodParsedType:()=>b,ZodPipeline:()=>Dn,ZodPromise:()=>_t,ZodReadonly:()=>Wt,ZodRecord:()=>Cr,ZodSchema:()=>M,ZodSet:()=>ln,ZodString:()=>ht,ZodSymbol:()=>on,ZodTransformer:()=>ke,ZodTuple:()=>je,ZodType:()=>M,ZodUndefined:()=>Ut,ZodUnion:()=>qt,ZodUnknown:()=>Ze,ZodVoid:()=>an,addIssueToContext:()=>_,any:()=>wd,array:()=>Td,bigint:()=>yd,boolean:()=>pa,coerce:()=>Yd,custom:()=>ua,date:()=>_d,datetimeRegex:()=>ca,defaultErrorMap:()=>Je,discriminatedUnion:()=>$d,effect:()=>Fd,enum:()=>jd,function:()=>Ld,getErrorMap:()=>nn,getParsedType:()=>Ue,instanceof:()=>gd,intersection:()=>Id,isAborted:()=>Sr,isAsync:()=>rn,isDirty:()=>wr,isValid:()=>gt,late:()=>fd,lazy:()=>Dd,literal:()=>Ud,makeIssue:()=>Nn,map:()=>Od,nan:()=>hd,nativeEnum:()=>qd,never:()=>Cd,null:()=>Sd,nullable:()=>Hd,number:()=>ma,object:()=>Ed,objectUtil:()=>Vs,oboolean:()=>Jd,onumber:()=>Wd,optional:()=>Bd,ostring:()=>zd,pipeline:()=>Gd,preprocess:()=>Kd,promise:()=>Vd,quotelessJson:()=>Fu,record:()=>Md,set:()=>Nd,setErrorMap:()=>Hu,strictObject:()=>Ad,string:()=>da,symbol:()=>bd,transformer:()=>Fd,tuple:()=>Pd,undefined:()=>vd,union:()=>Rd,unknown:()=>xd,util:()=>O,void:()=>kd});var O;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(O||(O={}));var Vs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Vs||(Vs={}));var b=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ue=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var h=O.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"]),Fu=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),fe=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.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)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fe.create=e=>new fe(e);var Bu=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${O.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:O.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case h.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case h.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,O.assertNever(e)}return{message:n}},Je=Bu;var ra=Je;function Hu(e){ra=e}function nn(){return ra}var Nn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Ku=[];function _(e,t){let n=nn(),r=Nn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Je?void 0:Je].filter(s=>!!s)});e.common.issues.push(r)}var se=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return k;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return k;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},k=Object.freeze({status:"aborted"}),Mt=e=>({status:"dirty",value:e}),ae=e=>({status:"valid",value:e}),Sr=e=>e.status==="aborted",wr=e=>e.status==="dirty",gt=e=>e.status==="valid",rn=e=>typeof Promise<"u"&&e instanceof Promise;var v;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(v||(v={}));var Ce=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,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}},sa=(e,t)=>{if(gt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fe(e.common.issues);return this._error=n,this._error}}};function I(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var M=class{get description(){return this._def.description}_getType(t){return Ue(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ue(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new se,ctx:{common:t.parent.common,data:t.data,parsedType:Ue(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(rn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)},s=this._parseSync({data:t,path:r.path,parent:r});return sa(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return gt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>gt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(rn(s)?s:Promise.resolve(s));return sa(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:h.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ke({schema:this,typeName:E.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return xe.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return _t.create(this,this._def)}or(t){return qt.create([this,t],this._def)}and(t){return Vt.create(this,t,this._def)}transform(t){return new ke({...I(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Gt({...I(this._def),innerType:this,defaultValue:n,typeName:E.ZodDefault})}brand(){return new Ln({typeName:E.ZodBranded,type:this,...I(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new zt({...I(this._def),innerType:this,catchValue:n,typeName:E.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Dn.create(this,t)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Gu=/^c[^\s-]{8,}$/i,zu=/^[0-9a-z]+$/,Wu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ju=/^[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,Yu=/^[a-z0-9_-]{21}$/i,Zu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Xu=/^[-+]?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)?)??$/,Qu=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ed="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,td=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nd=/^(?:(?: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])$/,rd=/^(([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]))$/,sd=/^(([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])$/,od=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,id=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ia="((\\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])))",ad=new RegExp(`^${ia}$`);function aa(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function cd(e){return new RegExp(`^${aa(e)}$`)}function ca(e){let t=`${ia}T${aa(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function ld(e,t){return!!((t==="v4"||!t)&&td.test(e)||(t==="v6"||!t)&&rd.test(e))}function ud(e,t){if(!Zu.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function dd(e,t){return!!((t==="v4"||!t)&&nd.test(e)||(t==="v6"||!t)&&sd.test(e))}var ht=class e extends M{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.string,received:o.parsedType}),k}let r=new se,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Qu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"email",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Fs||(Fs=new RegExp(ed,"u")),Fs.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"emoji",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Ju.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"uuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Yu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"nanoid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Gu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")zu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid2",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Wu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ulid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),_(s,{validation:"url",code:h.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"regex",code:h.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?ca(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?ad.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?cd(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Xu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"duration",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?ld(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ip",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?ud(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"jwt",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?dd(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cidr",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?od.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?id.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64url",code:h.invalid_string,message:o.message}),r.dirty()):O.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:h.invalid_string,...v.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...v.errToObj(t)})}url(t){return this._addCheck({kind:"url",...v.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...v.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...v.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...v.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...v.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...v.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...v.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...v.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...v.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...v.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...v.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...v.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...v.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...v.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...v.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...v.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...v.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...v.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...v.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...v.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...v.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...v.errToObj(n)})}nonempty(t){return this.min(1,v.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ht.create=e=>new ht({checks:[],typeName:E.ZodString,coerce:e?.coerce??!1,...I(e)});function md(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var Ot=class e extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.number,received:o.parsedType}),k}let r,s=new se;for(let o of this._def.checks)o.kind==="int"?O.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?md(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_finite,message:o.message}),s.dirty()):O.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,v.toString(n))}gt(t,n){return this.setLimit("min",t,!1,v.toString(n))}lte(t,n){return this.setLimit("max",t,!0,v.toString(n))}lt(t,n){return this.setLimit("max",t,!1,v.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:v.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:v.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:v.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:v.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&O.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Ot.create=e=>new Ot({checks:[],typeName:E.ZodNumber,coerce:e?.coerce||!1,...I(e)});var Nt=class e extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let r,s=new se;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):O.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),k}gte(t,n){return this.setLimit("min",t,!0,v.toString(n))}gt(t,n){return this.setLimit("min",t,!1,v.toString(n))}lte(t,n){return this.setLimit("max",t,!0,v.toString(n))}lt(t,n){return this.setLimit("max",t,!1,v.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:v.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:v.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Nt.create=e=>new Nt({checks:[],typeName:E.ZodBigInt,coerce:e?.coerce??!1,...I(e)});var Lt=class extends M{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),k}return ae(t.data)}};Lt.create=e=>new Lt({typeName:E.ZodBoolean,coerce:e?.coerce||!1,...I(e)});var Dt=class e extends M{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.date,received:o.parsedType}),k}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_date}),k}let r=new se,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):O.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:v.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:v.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Dt.create=e=>new Dt({checks:[],coerce:e?.coerce||!1,typeName:E.ZodDate,...I(e)});var on=class extends M{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),k}return ae(t.data)}};on.create=e=>new on({typeName:E.ZodSymbol,...I(e)});var Ut=class extends M{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),k}return ae(t.data)}};Ut.create=e=>new Ut({typeName:E.ZodUndefined,...I(e)});var jt=class extends M{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),k}return ae(t.data)}};jt.create=e=>new jt({typeName:E.ZodNull,...I(e)});var yt=class extends M{constructor(){super(...arguments),this._any=!0}_parse(t){return ae(t.data)}};yt.create=e=>new yt({typeName:E.ZodAny,...I(e)});var Ze=class extends M{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ae(t.data)}};Ze.create=e=>new Ze({typeName:E.ZodUnknown,...I(e)});var Ae=class extends M{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),k}};Ae.create=e=>new Ae({typeName:E.ZodNever,...I(e)});var an=class extends M{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),k}return ae(t.data)}};an.create=e=>new an({typeName:E.ZodVoid,...I(e)});var Xe=class e extends M{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),k;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_(n,{code:i?h.too_big:h.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_(n,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_(n,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Ce(n,i,n.path,a)))).then(i=>se.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Ce(n,i,n.path,a)));return se.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:v.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:v.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:v.toString(n)}})}nonempty(t){return this.min(1,t)}};Xe.create=(e,t)=>new Xe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...I(t)});function sn(e){if(e instanceof ge){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=xe.create(sn(r))}return new ge({...e._def,shape:()=>t})}else return e instanceof Xe?new Xe({...e._def,type:sn(e.element)}):e instanceof xe?xe.create(sn(e.unwrap())):e instanceof qe?qe.create(sn(e.unwrap())):e instanceof je?je.create(e.items.map(t=>sn(t))):e}var ge=class e extends M{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=O.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),k}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ae&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],d=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ce(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ae){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(_(s,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ce(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>se.mergeObjectSync(r,c)):se.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return v.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:v.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:E.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of O.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of O.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return sn(this)}partial(t){let n={};for(let r of O.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of O.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof xe;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return la(O.objectKeys(this.shape))}};ge.create=(e,t)=>new ge({shape:()=>e,unknownKeys:"strip",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});ge.strictCreate=(e,t)=>new ge({shape:()=>e,unknownKeys:"strict",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});ge.lazycreate=(e,t)=>new ge({shape:e,unknownKeys:"strip",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});var qt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new fe(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),k}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new fe(l));return _(n,{code:h.invalid_union,unionErrors:a}),k}}get options(){return this._def.options}};qt.create=(e,t)=>new qt({options:e,typeName:E.ZodUnion,...I(t)});var Ye=e=>e instanceof Ft?Ye(e.schema):e instanceof ke?Ye(e.innerType()):e instanceof Bt?[e.value]:e instanceof Ht?e.options:e instanceof Kt?O.objectValues(e.enum):e instanceof Gt?Ye(e._def.innerType):e instanceof Ut?[void 0]:e instanceof jt?[null]:e instanceof xe?[void 0,...Ye(e.unwrap())]:e instanceof qe?[null,...Ye(e.unwrap())]:e instanceof Ln||e instanceof Wt?Ye(e.unwrap()):e instanceof zt?Ye(e._def.innerType):[],xr=class e extends M{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),k;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ye(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:E.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...I(r)})}};function Bs(e,t){let n=Ue(e),r=Ue(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let s=O.objectKeys(t),o=O.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=Bs(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=Bs(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Vt=class extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Sr(o)||Sr(i))return k;let a=Bs(o.value,i.value);return a.valid?((wr(o)||wr(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),k)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vt.create=(e,t,n)=>new Vt({left:e,right:t,typeName:E.ZodIntersection,...I(n)});var je=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),k;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ce(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>se.mergeArray(n,i)):se.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};je.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new je({items:e,typeName:E.ZodTuple,rest:null,...I(t)})};var Cr=class e extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.object)return _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),k;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Ce(r,a,r.path,a)),value:i._parse(new Ce(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?se.mergeObjectAsync(n,s):se.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:E.ZodRecord,...I(r)}):new e({keyType:ht.create(),valueType:t,typeName:E.ZodRecord,...I(n)})}},cn=class extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.map)return _(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),k;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Ce(r,a,r.path,[c,"key"])),value:o._parse(new Ce(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return k;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return k;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};cn.create=(e,t,n)=>new cn({valueType:t,keyType:e,typeName:E.ZodMap,...I(n)});var ln=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return _(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),k;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_(r,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_(r,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return k;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Ce(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:v.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:v.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ln.create=(e,t)=>new ln({valueType:e,minSize:null,maxSize:null,typeName:E.ZodSet,...I(t)});var kr=class e extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return _(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),k;function r(a,l){return Nn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Je].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(a,l){return Nn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Je].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof _t){let a=this;return ae(async function(...l){let c=new fe([]),u=await a._def.args.parseAsync(l,o).catch(f=>{throw c.addIssue(r(l,f)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw c.addIssue(s(d,f)),c})})}else{let a=this;return ae(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new fe([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new fe([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:je.create(t).rest(Ze.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||je.create([]).rest(Ze.create()),returns:n||Ze.create(),typeName:E.ZodFunction,...I(r)})}},Ft=class extends M{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ft.create=(e,t)=>new Ft({getter:e,typeName:E.ZodLazy,...I(t)});var Bt=class extends M{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:t.data}}get value(){return this._def.value}};Bt.create=(e,t)=>new Bt({value:e,typeName:E.ZodLiteral,...I(t)});function la(e,t){return new Ht({values:e,typeName:E.ZodEnum,...I(t)})}var Ht=class e extends M{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:O.joinValues(r),received:n.parsedType,code:h.invalid_type}),k}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{received:n.data,code:h.invalid_enum_value,options:r}),k}return ae(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Ht.create=la;var Kt=class extends M{_parse(t){let n=O.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let s=O.objectValues(n);return _(r,{expected:O.joinValues(s),received:r.parsedType,code:h.invalid_type}),k}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=O.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:s}),k}return ae(t.data)}get enum(){return this._def.values}};Kt.create=(e,t)=>new Kt({values:e,typeName:E.ZodNativeEnum,...I(t)});var _t=class extends M{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return _(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),k;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return ae(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};_t.create=(e,t)=>new _t({type:e,typeName:E.ZodPromise,...I(t)});var ke=class extends M{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{_(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return k;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?k:l.status==="dirty"?Mt(l.value):n.value==="dirty"?Mt(l.value):l});{if(n.value==="aborted")return k;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?k:a.status==="dirty"?Mt(a.value):n.value==="dirty"?Mt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?k:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?k:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!gt(i))return k;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>gt(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):k);O.assertNever(s)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:E.ZodEffects,effect:t,...I(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:E.ZodEffects,...I(n)});var xe=class extends M{_parse(t){return this._getType(t)===b.undefined?ae(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xe.create=(e,t)=>new xe({innerType:e,typeName:E.ZodOptional,...I(t)});var qe=class extends M{_parse(t){return this._getType(t)===b.null?ae(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};qe.create=(e,t)=>new qe({innerType:e,typeName:E.ZodNullable,...I(t)});var Gt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gt.create=(e,t)=>new Gt({innerType:e,typeName:E.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...I(t)});var zt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rn(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zt.create=(e,t)=>new zt({innerType:e,typeName:E.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...I(t)});var un=class extends M{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),k}return{status:"valid",value:t.data}}};un.create=e=>new un({typeName:E.ZodNaN,...I(e)});var pd=Symbol("zod_brand"),Ln=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Dn=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?k:o.status==="dirty"?(n.dirty(),Mt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?k:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:E.ZodPipeline})}},Wt=class extends M{_parse(t){let n=this._def.innerType._parse(t),r=s=>(gt(s)&&(s.value=Object.freeze(s.value)),s);return rn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Wt.create=(e,t)=>new Wt({innerType:e,typeName:E.ZodReadonly,...I(t)});function oa(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ua(e,t={},n){return e?yt.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=oa(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=oa(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):yt.create()}var fd={object:ge.lazycreate},E;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(E||(E={}));var gd=(e,t={message:`Input not instance of ${e.name}`})=>ua(n=>n instanceof e,t),da=ht.create,ma=Ot.create,hd=un.create,yd=Nt.create,pa=Lt.create,_d=Dt.create,bd=on.create,vd=Ut.create,Sd=jt.create,wd=yt.create,xd=Ze.create,Cd=Ae.create,kd=an.create,Td=Xe.create,Ed=ge.create,Ad=ge.strictCreate,Rd=qt.create,$d=xr.create,Id=Vt.create,Pd=je.create,Md=Cr.create,Od=cn.create,Nd=ln.create,Ld=kr.create,Dd=Ft.create,Ud=Bt.create,jd=Ht.create,qd=Kt.create,Vd=_t.create,Fd=ke.create,Bd=xe.create,Hd=qe.create,Kd=ke.createWithPreprocess,Gd=Dn.create,zd=()=>da().optional(),Wd=()=>ma().optional(),Jd=()=>pa().optional(),Yd={string:(e=>ht.create({...e,coerce:!0})),number:(e=>Ot.create({...e,coerce:!0})),boolean:(e=>Lt.create({...e,coerce:!0})),bigint:(e=>Nt.create({...e,coerce:!0})),date:(e=>Dt.create({...e,coerce:!0}))};var Zd=k;var fa=["tempo","mpp_self","merchant_self"];var Ks=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional(),perRequestFeeCents:p.number().nonnegative().optional()}),Xd=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:Ks.optional()}).passthrough(),Gs=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),zs=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),ga=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),ha=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),Qd=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),em=120,tm=120,nm=1200,rm=/^[^\u0000-\u001F\u007F]+$/;function Hs(e,t){return p.string().min(1).max(e).regex(rm,`${t} must not contain control characters`)}var Ws={id:p.string().min(1),name:Hs(em,"name"),description:Hs(nm,"description"),provider:p.string().min(1),model:p.string().min(1),category:Qd,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:Hs(tm,"merchantName"),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:Ks.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Xd.optional(),status:p.enum(["available","unavailable"]).optional(),handler:Gs.optional(),pricing:zs.optional(),security:ga.optional(),engagement:ha.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(fa).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},ya=p.object({...Ws,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),_a=p.object({...Ws,dispatch:p.literal("enveloped")}).strict(),ba=p.object({...Ws,handler:Gs,pricing:zs}).strict(),va=p.union([p.discriminatedUnion("dispatch",[ya,_a]),ba]);var Js=/^[a-z0-9][a-z0-9_-]*$/;var om="https://fal.run",Ca="https://openrouter.mpp.tempo.xyz";function im(e){let{attestation:t,tool_id:n,...r}=e;return r}var Sa={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function Tr(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Sa[r]&&(i.image_size=Sa[r]),i)}function wa(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function am(e,t,n,r,s,o,i,a,l){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function cm(e,t,n,r,s,o,i,a){return am(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function Y(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${om}/${r}`,merchantName:"fal.ai",buildBody:im,tags:[],...a}}function lm(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function um(e){return t=>{let{attestation:n,tool_id:r,prompt:s,image_url:o,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:s}];return typeof o=="string"&&o.length>0&&u.push({type:"image_url",image_url:{url:o}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function Q(e,t,n,r,s,o,i){let a=i?.perRequestFeeCents??0,l=500/1e6*s*100,c=500/1e6*o*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ca}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:lm(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...a>0?{perRequestFeeCents:a}:{}},...g}}function Ys(e,t,n,r,s,o){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ca}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:um(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...o}}var Zs=[Y("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{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"]},{tags:["image","flux","photorealistic","high-quality"]}),Y("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{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"]},{tags:["image","flux","fast"],buildBody:Tr}),Y("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Tr}),Y("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Tr}),Y("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),Ys("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),Ys("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),Ys("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),Y("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),Y("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),Y("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),Y("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),Y("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),Y("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),Y("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),Y("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),Y("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),cm("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),Y("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),Y("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),Y("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),Y("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),Q("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),Q("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),Q("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),Q("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),Q("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),Q("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),Q("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),Q("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),Q("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),Q("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),Q("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),Q("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),Q("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),Q("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),Q("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),Q("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),Q("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),Q("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),Q("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wa,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Tr({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},Y("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),Y("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wa,tags:["onchain","prices","allium","crypto","legacy"]}];function Un(e){return Zs.find(t=>t.id===e)}var ka=1,Ta=["pick_one","fan_out"],Ea=["concat","dedupe_by_url","top_k_by_score"],pm=8,fm=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),gm=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),hm=p.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),ym=p.object({providers:p.array(p.string().min(1)).min(1).max(pm),merge:p.enum(Ea),maxResults:p.number().int().positive().optional()}),Aa=p.object({mode:p.enum(Ta).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(hm,gm).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:ym.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),fm),required:p.array(p.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),_m=p.object({version:p.literal(ka),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(Js,"tool name must match MCP naming rules"),Aa).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Qs=require("child_process"),Ma=require("util"),Oa=R(require("crypto")),ce=R(require("fs")),Na=R(require("os")),Ve=R(require("path"));var dn=(0,Ma.promisify)(Qs.execFile),Rr=Ve.join(Na.homedir(),".visa-mcp","bin"),Jt=Ve.join(Rr,"Visa CLI"),Sm=Ve.join(__dirname,"..","native"),Ra="5",$a=Ve.join(Rr,"visa-keychain.version"),Ia=Ve.join(Rr,"visa-keychain.sha256");function Pa(e){let t=ce.readFileSync(e);return Oa.createHash("sha256").update(t).digest("hex")}async function La(){try{if(ce.readFileSync($a,"utf-8").trim()===Ra&&ce.existsSync(Jt)){let r=ce.readFileSync(Ia,"utf-8").trim();if(Pa(Jt)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ce.unlinkSync(Jt);else return Jt}}catch{}let e=Ve.join(Sm,"visa-keychain.m");if(ce.existsSync(e)||(e=Ve.resolve(__dirname,"..","..","native","visa-keychain.m")),ce.existsSync(e)||(e=Ve.resolve(__dirname,"..","native","visa-keychain.m")),!ce.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ce.mkdirSync(Rr,{recursive:!0,mode:448});try{await dn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Jt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Pa(Jt);return ce.writeFileSync(Ia,t,{mode:384}),ce.writeFileSync($a,Ra,{mode:384}),Jt}async function Da(e){let t=await La(),n;try{n=(await dn(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Xs=null;function Z(){return En()?!0:process.platform!=="darwin"?!1:Xs!==null?Xs:(Xs=!0,!0)}var Er="visa-cli",Ar="attestation-key";async function wm(e){try{await dn("security",["delete-generic-password","-s",Er,"-a",Ar],{timeout:5e3})}catch{}await dn("security",["add-generic-password","-s",Er,"-a",Ar,"-w",e],{timeout:5e3})}async function xm(){try{let{stdout:e}=await dn("security",["find-generic-password","-s",Er,"-a",Ar,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function jn(){let e=await Da(["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 wm(n),r}async function mn(e,t){if(En())return Promise.resolve(ci());let n=await xm();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await La(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Qs.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.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 $r(){try{await dn("security",["delete-generic-password","-s",Er,"-a",Ar],{timeout:5e3})}catch{}try{await Da(["delete-key"])}catch{}}var Cm=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],km=[...Cm.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function to(e,t=km){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=eo(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(eo(r.match.provider)))&&r.match.keywords.every(s=>n.includes(eo(s))))return r.targetToolId;return null}function eo(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Ua={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",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 a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',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 via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",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 or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",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 a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), 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 no(e,t,n){if(!qa(e))return Rm(e,n);let r=ja[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=$m(e,o,n);return i||Im(e,r,o,s)}function Rm(e,t){return to({requestedTool:e,intentText:t})??e}function $m(e,t,n){return to({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Im(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var ja=Ua;function qa(e){return e in ja}var qn=Object.keys(Ua);function ro(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Va(e=process.env){return ro(e)!==null}var oe=R(require("crypto")),$e=R(require("fs")),$o=R(require("os")),Qr=R(require("path"));var j=R(require("fs")),hn=R(require("os")),H=R(require("path")),Ka=require("child_process");var Fa=R(require("fs")),Pm=["npm","pnpm","yarn","bun"],Mm=/\s+/;function Om(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Mm)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return Pm.includes(s)?s:void 0}function so(e){if(!e)return;let t=e;try{t=Fa.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function Nm(e=process.argv[1]){return Om()??so(process.env.npm_execpath)??so(process.env.npm_node_execpath)??so(e)}function oo(e,t,n){let r=t??Nm(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function pn(e,t,n){return oo(e,t,n).display}var Lm=2,Vn="# >>> visa-cli shell hud v2 >>>",Pr="# <<< visa-cli shell hud v2 <<<",Ga="# >>> visa-cli shell hud >>>",Dm="# <<< visa-cli shell hud <<<",za=3e4,Um=6e4,jm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",qm={currentVersion:"0.0.0"},Vm=3e4;function co(){try{return H.join(po(),".visa-cli")}catch{return H.join(hn.tmpdir(),".visa-cli")}}function bt(){return H.join(co(),"shell-hud.json")}function Mr(){return H.join(co(),"shell-hud.line")}function Wa(){return H.join(co(),"shell-hud.lock")}function yn(e){let t=e??process.env.SHELL;if(!t)return null;let n=H.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 Bn(e){let t=po();if(e==="zsh")return H.join(t,".zshrc");if(e==="bash")return H.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return H.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Fm(e){let t=po(),n=[{shell:"zsh",rcPath:H.join(t,".zshrc")},{shell:"bash",rcPath:H.join(t,".bashrc")},{shell:"bash",rcPath:H.join(t,".bash_profile")},{shell:"powershell",rcPath:H.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function Bm(e){let t="$HOME/.visa-cli/shell-hud.line",n=np(e),r=rp(e);if(e==="zsh")return`${Vn}
36
+ `;pt.writeFileSync(n,r,{mode:384}),pt.renameSync(n,t)}function js(e){let t=Pt()[e];return typeof t=="string"?t:void 0}function _r(e){let t=Pt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function qs(e){let t=Pt()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}var ze=class extends Error{constructor(t){let n=Object.keys(ft).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},We=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},mt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+yr[t]),this.name="RetiredSettingKeyError"}},Yi=["biometric.","spending.","account.","cards.","biometric"];function br(e,t){if(Yi.some(o=>e.startsWith(o)))throw new We(e);if(e in yr)throw new mt(e);let n=ft[e];if(!n)throw new ze(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=Pt();return s[e]=r,Ls(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Mn()}}function vr(e){if(Yi.some(o=>e.startsWith(o)))throw new We(e);let t=ft[e];if(e in yr){let o=Pt(),i=e in o;return i&&(delete o[e],Ls(o)),{key:e,removed:i,requiresRestart:!1,path:Mn()}}if(!t)throw new ze(e);let r=Pt(),s=e in r;return s&&(delete r[e],Ls(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Mn()}}function Zi(){let e=Pt();return Object.entries(yr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Nu="https://auth.visacli.sh";function Lu(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Du(){try{let e=ar();return Lu(e.version)}catch{return!1}}function Uu(e){return e.envVar!==void 0&&e.envVar!==""?(Ns(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Ns(e.settingValue,"auth.serverUrl"),e.settingValue):Nu}function we(){return Uu({envVar:process.env.VISA_AUTH_URL,settingValue:js("auth.serverUrl"),isPrerelease:Du()})}function Xi(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":_r("ui.suppressBrowser")??!1}function Qi(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":_r("ui.suppressFeed")??!1}function ea(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=qs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Us}var On="2.1.0-rc.2",ju=/^vk_[A-Za-z0-9_-]{32,}$/;function qu(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var Vu="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function tn(e){return typeof e=="string"?e.trim():""}function ta(e){let t=e&&typeof e=="object"?e:{},n=tn(t.error)||tn(t.message);if(!n)return Vu;let r=tn(t.error_code),s=[["surface",tn(t.disabled_surface)],["flag",tn(t.flag)],["correlation_id",tn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function na(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r?ju.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
37
+ `)}var pe=class{constructor(t){this.getSessionToken=t;this.baseUrl=we()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!De()){let r=t.headers.get("X-Latest-Version");r&&Vi(r,On)&&(this.lastSignals.updateAvailable={currentVersion:On,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return On}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new $t(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(ta(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(na());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Rt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":On,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error($s(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=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){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new re(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",g=typeof u?.error_code=="string"?u.error_code:"";throw g==="SPENDING_LIMIT_EXCEEDED"||g==="DAILY_LIMIT_EXCEEDED"||g==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(na());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":On,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Rt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(x){throw new Error($s(x))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let x=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${x}s. Tip: use the batch tool to combine multiple requests into one.`)}let g=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(d.headers.get("Retry-After"))||1;throw new It(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",y,d.status)}throw new Error(ta(f))}let x=qu(f?.error_code);if(x||d.status===410){let y=x??"BUDGET_CLOSED";throw new en(f?.message||f?.error||"Your session was invalidated by the server.",y,{budgetId:n.session_budget_id,status:d.status})}if(f?.declined){let y=Number(f.retryAfter??d.headers.get("Retry-After"));throw new re(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(y)&&y>0?y:void 0)}throw new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:g}}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Rt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await Rt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}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 startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};Qo(p,{BRAND:()=>pd,DIRTY:()=>Mt,EMPTY_PATH:()=>Ku,INVALID:()=>k,NEVER:()=>Zd,OK:()=>ae,ParseStatus:()=>se,Schema:()=>M,ZodAny:()=>yt,ZodArray:()=>Xe,ZodBigInt:()=>Nt,ZodBoolean:()=>Lt,ZodBranded:()=>Ln,ZodCatch:()=>zt,ZodDate:()=>Dt,ZodDefault:()=>Gt,ZodDiscriminatedUnion:()=>xr,ZodEffects:()=>ke,ZodEnum:()=>Ht,ZodError:()=>fe,ZodFirstPartyTypeKind:()=>E,ZodFunction:()=>kr,ZodIntersection:()=>Vt,ZodIssueCode:()=>h,ZodLazy:()=>Ft,ZodLiteral:()=>Bt,ZodMap:()=>cn,ZodNaN:()=>un,ZodNativeEnum:()=>Kt,ZodNever:()=>Ae,ZodNull:()=>jt,ZodNullable:()=>qe,ZodNumber:()=>Ot,ZodObject:()=>ge,ZodOptional:()=>xe,ZodParsedType:()=>b,ZodPipeline:()=>Dn,ZodPromise:()=>_t,ZodReadonly:()=>Wt,ZodRecord:()=>Cr,ZodSchema:()=>M,ZodSet:()=>ln,ZodString:()=>ht,ZodSymbol:()=>on,ZodTransformer:()=>ke,ZodTuple:()=>je,ZodType:()=>M,ZodUndefined:()=>Ut,ZodUnion:()=>qt,ZodUnknown:()=>Ze,ZodVoid:()=>an,addIssueToContext:()=>_,any:()=>wd,array:()=>Td,bigint:()=>yd,boolean:()=>pa,coerce:()=>Yd,custom:()=>ua,date:()=>_d,datetimeRegex:()=>ca,defaultErrorMap:()=>Je,discriminatedUnion:()=>$d,effect:()=>Fd,enum:()=>jd,function:()=>Ld,getErrorMap:()=>nn,getParsedType:()=>Ue,instanceof:()=>gd,intersection:()=>Id,isAborted:()=>Sr,isAsync:()=>rn,isDirty:()=>wr,isValid:()=>gt,late:()=>fd,lazy:()=>Dd,literal:()=>Ud,makeIssue:()=>Nn,map:()=>Od,nan:()=>hd,nativeEnum:()=>qd,never:()=>Cd,null:()=>Sd,nullable:()=>Hd,number:()=>ma,object:()=>Ed,objectUtil:()=>Vs,oboolean:()=>Jd,onumber:()=>Wd,optional:()=>Bd,ostring:()=>zd,pipeline:()=>Gd,preprocess:()=>Kd,promise:()=>Vd,quotelessJson:()=>Fu,record:()=>Md,set:()=>Nd,setErrorMap:()=>Hu,strictObject:()=>Ad,string:()=>da,symbol:()=>bd,transformer:()=>Fd,tuple:()=>Pd,undefined:()=>vd,union:()=>Rd,unknown:()=>xd,util:()=>O,void:()=>kd});var O;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(O||(O={}));var Vs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Vs||(Vs={}));var b=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ue=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var h=O.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"]),Fu=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),fe=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.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)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fe.create=e=>new fe(e);var Bu=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${O.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:O.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case h.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case h.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,O.assertNever(e)}return{message:n}},Je=Bu;var ra=Je;function Hu(e){ra=e}function nn(){return ra}var Nn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Ku=[];function _(e,t){let n=nn(),r=Nn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Je?void 0:Je].filter(s=>!!s)});e.common.issues.push(r)}var se=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return k;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return k;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},k=Object.freeze({status:"aborted"}),Mt=e=>({status:"dirty",value:e}),ae=e=>({status:"valid",value:e}),Sr=e=>e.status==="aborted",wr=e=>e.status==="dirty",gt=e=>e.status==="valid",rn=e=>typeof Promise<"u"&&e instanceof Promise;var v;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(v||(v={}));var Ce=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,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}},sa=(e,t)=>{if(gt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fe(e.common.issues);return this._error=n,this._error}}};function I(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var M=class{get description(){return this._def.description}_getType(t){return Ue(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ue(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new se,ctx:{common:t.parent.common,data:t.data,parsedType:Ue(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(rn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)},s=this._parseSync({data:t,path:r.path,parent:r});return sa(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return gt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>gt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ue(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(rn(s)?s:Promise.resolve(s));return sa(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:h.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ke({schema:this,typeName:E.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return xe.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return _t.create(this,this._def)}or(t){return qt.create([this,t],this._def)}and(t){return Vt.create(this,t,this._def)}transform(t){return new ke({...I(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Gt({...I(this._def),innerType:this,defaultValue:n,typeName:E.ZodDefault})}brand(){return new Ln({typeName:E.ZodBranded,type:this,...I(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new zt({...I(this._def),innerType:this,catchValue:n,typeName:E.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Dn.create(this,t)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Gu=/^c[^\s-]{8,}$/i,zu=/^[0-9a-z]+$/,Wu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ju=/^[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,Yu=/^[a-z0-9_-]{21}$/i,Zu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Xu=/^[-+]?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)?)??$/,Qu=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ed="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,td=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,nd=/^(?:(?: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])$/,rd=/^(([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]))$/,sd=/^(([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])$/,od=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,id=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ia="((\\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])))",ad=new RegExp(`^${ia}$`);function aa(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function cd(e){return new RegExp(`^${aa(e)}$`)}function ca(e){let t=`${ia}T${aa(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function ld(e,t){return!!((t==="v4"||!t)&&td.test(e)||(t==="v6"||!t)&&rd.test(e))}function ud(e,t){if(!Zu.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function dd(e,t){return!!((t==="v4"||!t)&&nd.test(e)||(t==="v6"||!t)&&sd.test(e))}var ht=class e extends M{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.string,received:o.parsedType}),k}let r=new se,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Qu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"email",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Fs||(Fs=new RegExp(ed,"u")),Fs.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"emoji",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Ju.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"uuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Yu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"nanoid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Gu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")zu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid2",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Wu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ulid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),_(s,{validation:"url",code:h.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"regex",code:h.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?ca(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?ad.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?cd(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Xu.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"duration",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?ld(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ip",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?ud(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"jwt",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?dd(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cidr",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?od.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?id.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64url",code:h.invalid_string,message:o.message}),r.dirty()):O.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:h.invalid_string,...v.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...v.errToObj(t)})}url(t){return this._addCheck({kind:"url",...v.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...v.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...v.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...v.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...v.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...v.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...v.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...v.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...v.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...v.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...v.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...v.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...v.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...v.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...v.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...v.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...v.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...v.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...v.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...v.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...v.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...v.errToObj(n)})}nonempty(t){return this.min(1,v.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ht.create=e=>new ht({checks:[],typeName:E.ZodString,coerce:e?.coerce??!1,...I(e)});function md(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var Ot=class e extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.number,received:o.parsedType}),k}let r,s=new se;for(let o of this._def.checks)o.kind==="int"?O.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?md(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_finite,message:o.message}),s.dirty()):O.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,v.toString(n))}gt(t,n){return this.setLimit("min",t,!1,v.toString(n))}lte(t,n){return this.setLimit("max",t,!0,v.toString(n))}lt(t,n){return this.setLimit("max",t,!1,v.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:v.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:v.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:v.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:v.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&O.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Ot.create=e=>new Ot({checks:[],typeName:E.ZodNumber,coerce:e?.coerce||!1,...I(e)});var Nt=class e extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let r,s=new se;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):O.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),k}gte(t,n){return this.setLimit("min",t,!0,v.toString(n))}gt(t,n){return this.setLimit("min",t,!1,v.toString(n))}lte(t,n){return this.setLimit("max",t,!0,v.toString(n))}lt(t,n){return this.setLimit("max",t,!1,v.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:v.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:v.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Nt.create=e=>new Nt({checks:[],typeName:E.ZodBigInt,coerce:e?.coerce??!1,...I(e)});var Lt=class extends M{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),k}return ae(t.data)}};Lt.create=e=>new Lt({typeName:E.ZodBoolean,coerce:e?.coerce||!1,...I(e)});var Dt=class e extends M{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:b.date,received:o.parsedType}),k}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_date}),k}let r=new se,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):O.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:v.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:v.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Dt.create=e=>new Dt({checks:[],coerce:e?.coerce||!1,typeName:E.ZodDate,...I(e)});var on=class extends M{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),k}return ae(t.data)}};on.create=e=>new on({typeName:E.ZodSymbol,...I(e)});var Ut=class extends M{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),k}return ae(t.data)}};Ut.create=e=>new Ut({typeName:E.ZodUndefined,...I(e)});var jt=class extends M{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),k}return ae(t.data)}};jt.create=e=>new jt({typeName:E.ZodNull,...I(e)});var yt=class extends M{constructor(){super(...arguments),this._any=!0}_parse(t){return ae(t.data)}};yt.create=e=>new yt({typeName:E.ZodAny,...I(e)});var Ze=class extends M{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ae(t.data)}};Ze.create=e=>new Ze({typeName:E.ZodUnknown,...I(e)});var Ae=class extends M{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),k}};Ae.create=e=>new Ae({typeName:E.ZodNever,...I(e)});var an=class extends M{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),k}return ae(t.data)}};an.create=e=>new an({typeName:E.ZodVoid,...I(e)});var Xe=class e extends M{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),k;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_(n,{code:i?h.too_big:h.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_(n,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_(n,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Ce(n,i,n.path,a)))).then(i=>se.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Ce(n,i,n.path,a)));return se.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:v.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:v.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:v.toString(n)}})}nonempty(t){return this.min(1,t)}};Xe.create=(e,t)=>new Xe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...I(t)});function sn(e){if(e instanceof ge){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=xe.create(sn(r))}return new ge({...e._def,shape:()=>t})}else return e instanceof Xe?new Xe({...e._def,type:sn(e.element)}):e instanceof xe?xe.create(sn(e.unwrap())):e instanceof qe?qe.create(sn(e.unwrap())):e instanceof je?je.create(e.items.map(t=>sn(t))):e}var ge=class e extends M{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=O.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),k}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ae&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],d=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ce(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ae){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(_(s,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ce(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>se.mergeObjectSync(r,c)):se.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return v.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:v.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:E.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of O.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of O.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return sn(this)}partial(t){let n={};for(let r of O.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of O.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof xe;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return la(O.objectKeys(this.shape))}};ge.create=(e,t)=>new ge({shape:()=>e,unknownKeys:"strip",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});ge.strictCreate=(e,t)=>new ge({shape:()=>e,unknownKeys:"strict",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});ge.lazycreate=(e,t)=>new ge({shape:e,unknownKeys:"strip",catchall:Ae.create(),typeName:E.ZodObject,...I(t)});var qt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new fe(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),k}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new fe(l));return _(n,{code:h.invalid_union,unionErrors:a}),k}}get options(){return this._def.options}};qt.create=(e,t)=>new qt({options:e,typeName:E.ZodUnion,...I(t)});var Ye=e=>e instanceof Ft?Ye(e.schema):e instanceof ke?Ye(e.innerType()):e instanceof Bt?[e.value]:e instanceof Ht?e.options:e instanceof Kt?O.objectValues(e.enum):e instanceof Gt?Ye(e._def.innerType):e instanceof Ut?[void 0]:e instanceof jt?[null]:e instanceof xe?[void 0,...Ye(e.unwrap())]:e instanceof qe?[null,...Ye(e.unwrap())]:e instanceof Ln||e instanceof Wt?Ye(e.unwrap()):e instanceof zt?Ye(e._def.innerType):[],xr=class e extends M{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),k;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ye(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:E.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...I(r)})}};function Bs(e,t){let n=Ue(e),r=Ue(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let s=O.objectKeys(t),o=O.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=Bs(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=Bs(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Vt=class extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Sr(o)||Sr(i))return k;let a=Bs(o.value,i.value);return a.valid?((wr(o)||wr(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),k)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vt.create=(e,t,n)=>new Vt({left:e,right:t,typeName:E.ZodIntersection,...I(n)});var je=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),k;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ce(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>se.mergeArray(n,i)):se.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};je.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new je({items:e,typeName:E.ZodTuple,rest:null,...I(t)})};var Cr=class e extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.object)return _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),k;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Ce(r,a,r.path,a)),value:i._parse(new Ce(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?se.mergeObjectAsync(n,s):se.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:E.ZodRecord,...I(r)}):new e({keyType:ht.create(),valueType:t,typeName:E.ZodRecord,...I(n)})}},cn=class extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.map)return _(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),k;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Ce(r,a,r.path,[c,"key"])),value:o._parse(new Ce(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return k;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return k;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};cn.create=(e,t,n)=>new cn({valueType:t,keyType:e,typeName:E.ZodMap,...I(n)});var ln=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return _(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),k;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_(r,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_(r,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return k;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Ce(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:v.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:v.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ln.create=(e,t)=>new ln({valueType:e,minSize:null,maxSize:null,typeName:E.ZodSet,...I(t)});var kr=class e extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return _(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),k;function r(a,l){return Nn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Je].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(a,l){return Nn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nn(),Je].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof _t){let a=this;return ae(async function(...l){let c=new fe([]),u=await a._def.args.parseAsync(l,o).catch(f=>{throw c.addIssue(r(l,f)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw c.addIssue(s(d,f)),c})})}else{let a=this;return ae(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new fe([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new fe([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:je.create(t).rest(Ze.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||je.create([]).rest(Ze.create()),returns:n||Ze.create(),typeName:E.ZodFunction,...I(r)})}},Ft=class extends M{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ft.create=(e,t)=>new Ft({getter:e,typeName:E.ZodLazy,...I(t)});var Bt=class extends M{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:t.data}}get value(){return this._def.value}};Bt.create=(e,t)=>new Bt({value:e,typeName:E.ZodLiteral,...I(t)});function la(e,t){return new Ht({values:e,typeName:E.ZodEnum,...I(t)})}var Ht=class e extends M{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:O.joinValues(r),received:n.parsedType,code:h.invalid_type}),k}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{received:n.data,code:h.invalid_enum_value,options:r}),k}return ae(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Ht.create=la;var Kt=class extends M{_parse(t){let n=O.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let s=O.objectValues(n);return _(r,{expected:O.joinValues(s),received:r.parsedType,code:h.invalid_type}),k}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=O.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:s}),k}return ae(t.data)}get enum(){return this._def.values}};Kt.create=(e,t)=>new Kt({values:e,typeName:E.ZodNativeEnum,...I(t)});var _t=class extends M{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return _(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),k;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return ae(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};_t.create=(e,t)=>new _t({type:e,typeName:E.ZodPromise,...I(t)});var ke=class extends M{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{_(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return k;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?k:l.status==="dirty"?Mt(l.value):n.value==="dirty"?Mt(l.value):l});{if(n.value==="aborted")return k;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?k:a.status==="dirty"?Mt(a.value):n.value==="dirty"?Mt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?k:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?k:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!gt(i))return k;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>gt(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):k);O.assertNever(s)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:E.ZodEffects,effect:t,...I(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:E.ZodEffects,...I(n)});var xe=class extends M{_parse(t){return this._getType(t)===b.undefined?ae(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xe.create=(e,t)=>new xe({innerType:e,typeName:E.ZodOptional,...I(t)});var qe=class extends M{_parse(t){return this._getType(t)===b.null?ae(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};qe.create=(e,t)=>new qe({innerType:e,typeName:E.ZodNullable,...I(t)});var Gt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gt.create=(e,t)=>new Gt({innerType:e,typeName:E.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...I(t)});var zt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rn(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zt.create=(e,t)=>new zt({innerType:e,typeName:E.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...I(t)});var un=class extends M{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),k}return{status:"valid",value:t.data}}};un.create=e=>new un({typeName:E.ZodNaN,...I(e)});var pd=Symbol("zod_brand"),Ln=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Dn=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?k:o.status==="dirty"?(n.dirty(),Mt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?k:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:E.ZodPipeline})}},Wt=class extends M{_parse(t){let n=this._def.innerType._parse(t),r=s=>(gt(s)&&(s.value=Object.freeze(s.value)),s);return rn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Wt.create=(e,t)=>new Wt({innerType:e,typeName:E.ZodReadonly,...I(t)});function oa(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ua(e,t={},n){return e?yt.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=oa(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=oa(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):yt.create()}var fd={object:ge.lazycreate},E;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(E||(E={}));var gd=(e,t={message:`Input not instance of ${e.name}`})=>ua(n=>n instanceof e,t),da=ht.create,ma=Ot.create,hd=un.create,yd=Nt.create,pa=Lt.create,_d=Dt.create,bd=on.create,vd=Ut.create,Sd=jt.create,wd=yt.create,xd=Ze.create,Cd=Ae.create,kd=an.create,Td=Xe.create,Ed=ge.create,Ad=ge.strictCreate,Rd=qt.create,$d=xr.create,Id=Vt.create,Pd=je.create,Md=Cr.create,Od=cn.create,Nd=ln.create,Ld=kr.create,Dd=Ft.create,Ud=Bt.create,jd=Ht.create,qd=Kt.create,Vd=_t.create,Fd=ke.create,Bd=xe.create,Hd=qe.create,Kd=ke.createWithPreprocess,Gd=Dn.create,zd=()=>da().optional(),Wd=()=>ma().optional(),Jd=()=>pa().optional(),Yd={string:(e=>ht.create({...e,coerce:!0})),number:(e=>Ot.create({...e,coerce:!0})),boolean:(e=>Lt.create({...e,coerce:!0})),bigint:(e=>Nt.create({...e,coerce:!0})),date:(e=>Dt.create({...e,coerce:!0}))};var Zd=k;var fa=["tempo","mpp_self","merchant_self"];var Ks=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional(),perRequestFeeCents:p.number().nonnegative().optional()}),Xd=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:Ks.optional()}).passthrough(),Gs=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),zs=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),ga=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),ha=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),Qd=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),em=120,tm=120,nm=1200,rm=/^[^\u0000-\u001F\u007F]+$/;function Hs(e,t){return p.string().min(1).max(e).regex(rm,`${t} must not contain control characters`)}var Ws={id:p.string().min(1),name:Hs(em,"name"),description:Hs(nm,"description"),provider:p.string().min(1),model:p.string().min(1),category:Qd,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:Hs(tm,"merchantName"),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:Ks.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Xd.optional(),status:p.enum(["available","unavailable"]).optional(),handler:Gs.optional(),pricing:zs.optional(),security:ga.optional(),engagement:ha.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(fa).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},ya=p.object({...Ws,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),_a=p.object({...Ws,dispatch:p.literal("enveloped")}).strict(),ba=p.object({...Ws,handler:Gs,pricing:zs}).strict(),va=p.union([p.discriminatedUnion("dispatch",[ya,_a]),ba]);var Js=/^[a-z0-9][a-z0-9_-]*$/;var om="https://fal.run",Ca="https://openrouter.mpp.tempo.xyz";function im(e){let{attestation:t,tool_id:n,...r}=e;return r}var Sa={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function Tr(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Sa[r]&&(i.image_size=Sa[r]),i)}function wa(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function am(e,t,n,r,s,o,i,a,l){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function cm(e,t,n,r,s,o,i,a){return am(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function Y(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${om}/${r}`,merchantName:"fal.ai",buildBody:im,tags:[],...a}}function lm(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function um(e){return t=>{let{attestation:n,tool_id:r,prompt:s,image_url:o,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:s}];return typeof o=="string"&&o.length>0&&u.push({type:"image_url",image_url:{url:o}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function Q(e,t,n,r,s,o,i){let a=i?.perRequestFeeCents??0,l=500/1e6*s*100,c=500/1e6*o*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ca}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:lm(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...a>0?{perRequestFeeCents:a}:{}},...g}}function Ys(e,t,n,r,s,o){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ca}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:um(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...o}}var Zs=[Y("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{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"]},{tags:["image","flux","photorealistic","high-quality"]}),Y("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{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"]},{tags:["image","flux","fast"],buildBody:Tr}),Y("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Tr}),Y("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Tr}),Y("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),Ys("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),Ys("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),Ys("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),Y("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),Y("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),Y("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),Y("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),Y("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),Y("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),Y("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),Y("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),Y("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),cm("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),Y("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),Y("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),Y("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),Y("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),Q("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),Q("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),Q("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),Q("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),Q("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),Q("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),Q("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),Q("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),Q("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),Q("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),Q("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),Q("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),Q("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),Q("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),Q("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),Q("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),Q("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),Q("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),Q("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wa,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Tr({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},Y("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),Y("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wa,tags:["onchain","prices","allium","crypto","legacy"]}];function Un(e){return Zs.find(t=>t.id===e)}var ka=1,Ta=["pick_one","fan_out"],Ea=["concat","dedupe_by_url","top_k_by_score"],pm=8,fm=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),gm=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),hm=p.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),ym=p.object({providers:p.array(p.string().min(1)).min(1).max(pm),merge:p.enum(Ea),maxResults:p.number().int().positive().optional()}),Aa=p.object({mode:p.enum(Ta).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(hm,gm).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:ym.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),fm),required:p.array(p.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),_m=p.object({version:p.literal(ka),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(Js,"tool name must match MCP naming rules"),Aa).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Qs=require("child_process"),Ma=require("util"),Oa=R(require("crypto")),ce=R(require("fs")),Na=R(require("os")),Ve=R(require("path"));var dn=(0,Ma.promisify)(Qs.execFile),Rr=Ve.join(Na.homedir(),".visa-mcp","bin"),Jt=Ve.join(Rr,"Visa CLI"),Sm=Ve.join(__dirname,"..","native"),Ra="5",$a=Ve.join(Rr,"visa-keychain.version"),Ia=Ve.join(Rr,"visa-keychain.sha256");function Pa(e){let t=ce.readFileSync(e);return Oa.createHash("sha256").update(t).digest("hex")}async function La(){try{if(ce.readFileSync($a,"utf-8").trim()===Ra&&ce.existsSync(Jt)){let r=ce.readFileSync(Ia,"utf-8").trim();if(Pa(Jt)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ce.unlinkSync(Jt);else return Jt}}catch{}let e=Ve.join(Sm,"visa-keychain.m");if(ce.existsSync(e)||(e=Ve.resolve(__dirname,"..","..","native","visa-keychain.m")),ce.existsSync(e)||(e=Ve.resolve(__dirname,"..","native","visa-keychain.m")),!ce.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ce.mkdirSync(Rr,{recursive:!0,mode:448});try{await dn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Jt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Pa(Jt);return ce.writeFileSync(Ia,t,{mode:384}),ce.writeFileSync($a,Ra,{mode:384}),Jt}async function Da(e){let t=await La(),n;try{n=(await dn(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Xs=null;function Z(){return En()?!0:process.platform!=="darwin"?!1:Xs!==null?Xs:(Xs=!0,!0)}var Er="visa-cli",Ar="attestation-key";async function wm(e){try{await dn("security",["delete-generic-password","-s",Er,"-a",Ar],{timeout:5e3})}catch{}await dn("security",["add-generic-password","-s",Er,"-a",Ar,"-w",e],{timeout:5e3})}async function xm(){try{let{stdout:e}=await dn("security",["find-generic-password","-s",Er,"-a",Ar,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function jn(){let e=await Da(["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 wm(n),r}async function mn(e,t){if(En())return Promise.resolve(ci());let n=await xm();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await La(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Qs.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.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 $r(){try{await dn("security",["delete-generic-password","-s",Er,"-a",Ar],{timeout:5e3})}catch{}try{await Da(["delete-key"])}catch{}}var Cm=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],km=[...Cm.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function to(e,t=km){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=eo(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(eo(r.match.provider)))&&r.match.keywords.every(s=>n.includes(eo(s))))return r.targetToolId;return null}function eo(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Ua={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",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 a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',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 via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",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 or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",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 a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), 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 no(e,t,n){if(!qa(e))return Rm(e,n);let r=ja[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=$m(e,o,n);return i||Im(e,r,o,s)}function Rm(e,t){return to({requestedTool:e,intentText:t})??e}function $m(e,t,n){return to({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Im(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var ja=Ua;function qa(e){return e in ja}var qn=Object.keys(Ua);function ro(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Va(e=process.env){return ro(e)!==null}var oe=R(require("crypto")),$e=R(require("fs")),$o=R(require("os")),Qr=R(require("path"));var j=R(require("fs")),hn=R(require("os")),H=R(require("path")),Ka=require("child_process");var Fa=R(require("fs")),Pm=["npm","pnpm","yarn","bun"],Mm=/\s+/;function Om(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Mm)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return Pm.includes(s)?s:void 0}function so(e){if(!e)return;let t=e;try{t=Fa.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function Nm(e=process.argv[1]){return Om()??so(process.env.npm_execpath)??so(process.env.npm_node_execpath)??so(e)}function oo(e,t,n){let r=t??Nm(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function pn(e,t,n){return oo(e,t,n).display}var Lm=2,Vn="# >>> visa-cli shell hud v2 >>>",Pr="# <<< visa-cli shell hud v2 <<<",Ga="# >>> visa-cli shell hud >>>",Dm="# <<< visa-cli shell hud <<<",za=3e4,Um=6e4,jm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",qm={currentVersion:"0.0.0"},Vm=3e4;function co(){try{return H.join(po(),".visa-cli")}catch{return H.join(hn.tmpdir(),".visa-cli")}}function bt(){return H.join(co(),"shell-hud.json")}function Mr(){return H.join(co(),"shell-hud.line")}function Wa(){return H.join(co(),"shell-hud.lock")}function yn(e){let t=e??process.env.SHELL;if(!t)return null;let n=H.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 Bn(e){let t=po();if(e==="zsh")return H.join(t,".zshrc");if(e==="bash")return H.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return H.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Fm(e){let t=po(),n=[{shell:"zsh",rcPath:H.join(t,".zshrc")},{shell:"bash",rcPath:H.join(t,".bashrc")},{shell:"bash",rcPath:H.join(t,".bash_profile")},{shell:"powershell",rcPath:H.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function Bm(e){let t="$HOME/.visa-cli/shell-hud.line",n=np(e),r=rp(e);if(e==="zsh")return`${Vn}
38
38
  _visa_cli_shell_hud_precmd() {
39
39
  setopt localoptions no_bg_nice
40
40
  if [[ -f "${t}" ]]; then
@@ -101,9 +101,9 @@ ${y}`:f}function Km(e){let t=` ${B("\u2502",q.dim)} `,n=[];if(typeof e.dailySpen
101
101
  `),gn(Mr(),r+`
102
102
  `)}catch{}}function Xa(e){try{let t=Hn();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Qe(e).slice(0,200)};gn(bt(),JSON.stringify(r)+`
103
103
  `)}catch{}}function mo(){try{let e=Hn();if(!e)return;let t={...e,renderedAt:0};gn(bt(),JSON.stringify(t)+`
104
- `)}catch{}}function Fn(){try{j.unlinkSync(Wa())}catch{}}function Hn(){let e=bt();if(!j.existsSync(e))return null;try{return JSON.parse(j.readFileSync(e,"utf-8"))}catch{return null}}function Qa(){return Hn()?.status??null}function Xm(){if(process.env.JEST_WORKER_ID)return;let e=Wa();try{if(j.mkdirSync(H.dirname(e),{recursive:!0}),!sp(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){Fn();return}let n=(0,Ka.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Fn),n.unref()}catch{Fn()}}function Qe(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 Qm(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${B(r||"",q.green)}${B(s||"",q.dim)}`}function fn(e){return`$${e.toFixed(2)}`}function ep(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Qe(n.toUpperCase()),o=Qe(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function tp(){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 io=tp(),q={reset:"\x1B[0m",visaBlue:io?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:io?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:io?"\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}${q.reset}`}function Ha(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function po(){let e=hn.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function np(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function rp(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function sp(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=j.statSync(e);if(Date.now()-s.mtimeMs<=Vm)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function ao(e){return e instanceof Error?e.message:"unknown file system error"}function gn(e,t){j.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;j.writeFileSync(n,t),j.renameSync(n,e)}async function _n(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!Z())throw r;m.warn("attestation:key-mismatch",{action:"reregistering"});try{let o=await jn();return await e.registerAttestationKey(o),m.info("attestation:key-reregistered"),await t()}catch(o){m.warn("attestation:fast-reregister-blocked",{error:o.message})}if(n){m.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw m.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await jn();return await e.registerAttestationKey(i),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw m.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}var ec="2.0.2-rc.1";function fo(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ur(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=_r(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function be(e){return e==null?"\u2014":e?"yes":"no"}function jr(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function op(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function ip(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=qs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Us,source:{kind:"default"}}}async function qr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(F){n=F?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=js("auth.serverUrl"),i=we(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:be(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:be(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:be(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:Z(),formatted:be(Z()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:jr(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:jr(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:jr(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:jr(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let g=t?.cards?.find(F=>F.isDefault)??t?.cards?.[0];g&&r.push({key:"cards.default",value:{brand:g.brand??null,last4:g.last4},formatted:`${g.brand||"card"} \u2022\u2022\u2022\u2022 ${g.last4}`,source:{kind:"server"}});let f=ip();r.push({key:"credit.sessionCapCents",value:f.value,formatted:op(f.value),source:f.source});let x=Zi();x.length>0&&r.push({key:"settings.retired",value:x.map(F=>F.key),formatted:x.map(F=>F.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${x.map(F=>`visa-cli config unset ${F.key}`).join(" && ")}`});let y=Ur("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:be(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let A=Ur("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:A.value,formatted:be(A.value),source:A.source});let N=De(),L;process.env.VISA_CLI_NO_UPDATE_CHECK?L={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?L={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?L={kind:"env",var:"NODE_ENV"}:L={kind:"default"},r.push({key:"ui.updateCheck",value:!N,formatted:be(!N),source:L});let T=Ur("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:T.value,formatted:be(T.value),source:T.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let C=Ur("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:C.value,formatted:be(C.value),source:C.source});let V=process.env.VISA_DRY_RUN,G=Va();if(r.push({key:"tools.dryRun",value:G,formatted:be(G),source:V===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:ec,formatted:ec,source:{kind:"default"}}),e.includeDev){let F=process.env.VISA_MOCK_KEYCHAIN,it=ct();r.push({key:"dev.mockKeychain",value:it,formatted:be(it),source:fo("VISA_MOCK_KEYCHAIN",!!F),hint:fs()});let te=process.env.VISA_MOCK_TOUCHID,ue=En();r.push({key:"dev.mockTouchid",value:ue,formatted:be(ue),source:fo("VISA_MOCK_TOUCHID",!!te),hint:fs()});let at=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!at,formatted:be(!!at),source:fo("VISA_CLI_DEBUG",!!at)})}return{entries:r,statusError:n}}function ap(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function tc(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${ap(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
104
+ `)}catch{}}function Fn(){try{j.unlinkSync(Wa())}catch{}}function Hn(){let e=bt();if(!j.existsSync(e))return null;try{return JSON.parse(j.readFileSync(e,"utf-8"))}catch{return null}}function Qa(){return Hn()?.status??null}function Xm(){if(process.env.JEST_WORKER_ID)return;let e=Wa();try{if(j.mkdirSync(H.dirname(e),{recursive:!0}),!sp(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){Fn();return}let n=(0,Ka.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Fn),n.unref()}catch{Fn()}}function Qe(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 Qm(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${B(r||"",q.green)}${B(s||"",q.dim)}`}function fn(e){return`$${e.toFixed(2)}`}function ep(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Qe(n.toUpperCase()),o=Qe(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function tp(){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 io=tp(),q={reset:"\x1B[0m",visaBlue:io?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:io?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:io?"\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}${q.reset}`}function Ha(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function po(){let e=hn.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function np(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function rp(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function sp(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=j.statSync(e);if(Date.now()-s.mtimeMs<=Vm)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function ao(e){return e instanceof Error?e.message:"unknown file system error"}function gn(e,t){j.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;j.writeFileSync(n,t),j.renameSync(n,e)}async function _n(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!Z())throw r;m.warn("attestation:key-mismatch",{action:"reregistering"});try{let o=await jn();return await e.registerAttestationKey(o),m.info("attestation:key-reregistered"),await t()}catch(o){m.warn("attestation:fast-reregister-blocked",{error:o.message})}if(n){m.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw m.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await jn();return await e.registerAttestationKey(i),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw m.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}var ec="2.1.0-rc.2";function fo(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ur(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=_r(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function be(e){return e==null?"\u2014":e?"yes":"no"}function jr(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function op(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function ip(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=qs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Us,source:{kind:"default"}}}async function qr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(F){n=F?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=js("auth.serverUrl"),i=we(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:be(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:be(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:be(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:Z(),formatted:be(Z()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:jr(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:jr(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:jr(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:jr(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let g=t?.cards?.find(F=>F.isDefault)??t?.cards?.[0];g&&r.push({key:"cards.default",value:{brand:g.brand??null,last4:g.last4},formatted:`${g.brand||"card"} \u2022\u2022\u2022\u2022 ${g.last4}`,source:{kind:"server"}});let f=ip();r.push({key:"credit.sessionCapCents",value:f.value,formatted:op(f.value),source:f.source});let x=Zi();x.length>0&&r.push({key:"settings.retired",value:x.map(F=>F.key),formatted:x.map(F=>F.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${x.map(F=>`visa-cli config unset ${F.key}`).join(" && ")}`});let y=Ur("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:be(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let A=Ur("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:A.value,formatted:be(A.value),source:A.source});let N=De(),L;process.env.VISA_CLI_NO_UPDATE_CHECK?L={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?L={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?L={kind:"env",var:"NODE_ENV"}:L={kind:"default"},r.push({key:"ui.updateCheck",value:!N,formatted:be(!N),source:L});let T=Ur("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:T.value,formatted:be(T.value),source:T.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let C=Ur("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:C.value,formatted:be(C.value),source:C.source});let V=process.env.VISA_DRY_RUN,G=Va();if(r.push({key:"tools.dryRun",value:G,formatted:be(G),source:V===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:ec,formatted:ec,source:{kind:"default"}}),e.includeDev){let F=process.env.VISA_MOCK_KEYCHAIN,it=ct();r.push({key:"dev.mockKeychain",value:it,formatted:be(it),source:fo("VISA_MOCK_KEYCHAIN",!!F),hint:fs()});let te=process.env.VISA_MOCK_TOUCHID,ue=En();r.push({key:"dev.mockTouchid",value:ue,formatted:be(ue),source:fo("VISA_MOCK_TOUCHID",!!te),hint:fs()});let at=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!at,formatted:be(!!at),source:fo("VISA_CLI_DEBUG",!!at)})}return{entries:r,statusError:n}}function ap(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function tc(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${ap(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
105
105
  `)}function nc(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}function rc(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}var he=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},sc=["GET","POST"];function oc(e){let t;try{t=new URL(e)}catch{throw new he(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new he(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function ic(e){let t=(e??"GET").toUpperCase();if(!sc.includes(t))throw new he(`Unsupported HTTP method "${e}". Supported: ${sc.join(", ")}.`);return t}function ac(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new he(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function Vr(e){let t;if(typeof e=="string")try{t=new URL(e)}catch{t=void 0}else t=e;let n=t?.host.trim();return n?`merchant at ${n}`:"payment URL"}function cc(e){if(!e||typeof e!="object")throw new he("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new he("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new he("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new he(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new he("Merchant returned an empty currency.");if(t.currency.length>10)throw new he(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var vt=require("fs"),uc=require("os"),go=require("path"),cp=(0,go.join)((0,uc.homedir)(),".visa-mcp"),lc=(0,go.join)(cp,"mcp-session-budget.json");function Fr(){try{(0,vt.existsSync)(lc)&&(0,vt.unlinkSync)(lc)}catch{}}var yo=require("crypto"),Re=R(Br()),Yt=null,ve=0,bn=0,ye=0,St=null,_o=null,bo=null,Kr=Promise.resolve();function Tp(e){return Number((0,Re.fromCents)(e))}function pc(e){return(0,Re.toCents)((0,Re.micros)(BigInt(e)))}function mc(e){return(0,Re.toWire)((0,Re.fromCents)(e))}function ho(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Hr(e){return typeof e=="string"&&/^\d+$/.test(e)}var Ep=43,Ap=new RegExp(`^[A-Za-z0-9_-]{${Ep}}$`);function Rp(e){return typeof e=="string"&&Ap.test(e)}function $p(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Yt&&e.session_id!==Yt||typeof e.nonce!="string"||e.nonce.length===0||!Rp(e.server_signature)||!ho(e.cumulative)||!ho(e.remaining)||!ho(e.delta)||e.cumulative<ve||ye>0&&e.cumulative>ye||ye>0&&e.remaining>ye||e.cumulative_micros!==void 0&&!Hr(e.cumulative_micros)||e.remaining_micros!==void 0&&!Hr(e.remaining_micros)||e.delta_micros!==void 0&&!Hr(e.delta_micros)||e.reserved_micros!==void 0&&!Hr(e.reserved_micros))}function tt(e){Yt=e,ve=0,bn=0,ye=0,St=null,_o=null,bo=null,Kr=Promise.resolve()}function Kn(e){ye=Math.max(0,Math.floor(e))}function vo(){return Yt}function So(e){if(!Yt)return null;let t=ve+bn;return ye>0&&t>ye&&(t=ye),{session_budget_id:Yt,cumulative_micros:Tp(t),nonce:(0,yo.randomUUID)(),idempotency_key:e||(0,yo.randomUUID)()}}function wo(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return $p(r)?(ve=Math.max(ve,r.cumulative),bn=0,St=r,r):null}function fc(){return St}function xo(e){let t=pc(e.cumulative_micros);ve=Math.max(ve,t),bn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:ve,remaining:Math.max(0,ye-ve),delta:0,cumulative_micros:mc(ve),remaining_micros:mc(Math.max(0,ye-ve)),delta_micros:"0",nonce:e.nonce};return St=n,n}function Co(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let n;try{n=BigInt(t)}catch{return}if(n<0n)return;let r=(0,Re.toCents)((0,Re.micros)(n));if(!Number.isFinite(r)||r<0)return;_o=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Yt??"";St?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(St.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(St.delta_micros=s.charged_micros)):St={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function gc(e){let t=e.receipt??null;bo={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:pc(e.voucher.cumulative_micros),estimatedCumulativeCents:Gr(),receiptDeltaCents:typeof t?.delta=="number"?t.delta:null,receiptCumulativeCents:typeof t?.cumulative=="number"?t.cumulative:null,receiptRemainingCents:typeof t?.remaining=="number"?t.remaining:null,receiptDeltaMicros:typeof t?.delta_micros=="string"?t.delta_micros:null,receiptCumulativeMicros:typeof t?.cumulative_micros=="string"?t.cumulative_micros:null,receiptRemainingMicros:typeof t?.remaining_micros=="string"?t.remaining_micros:null,recordedAt:new Date().toISOString()}}function hc(){return bo}function yc(){return ve}function _c(){return _o}function Gr(){let e=ve+bn;return ye>0&&e>ye&&(e=ye),e}function bc(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Kr=Kr.then(()=>{bn+=t}),Kr}var Ip=10,Pp=1,z=null,vc=Promise.resolve();function ko(e){let t=vc.catch(()=>{}).then(e);return vc=t.then(()=>{},()=>{}),t}var le=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function To(e,t,n){return ko(()=>Sc(e,t,n))}async function Sc(e,t,n){if(Fr(),z&&new Date(z.expiresAt).getTime()>Date.now())return vo()!==z.budgetId&&(tt(z.budgetId),Kn(z.totalCents)),m.info("mcp-session:active-hit",{budgetId:z.budgetId,tool:n.toolName,remainingEstimatedCents:z.totalCents-Gr()}),{budgetId:z.budgetId,isFresh:!1,totalCents:z.totalCents,requestedCapCents:z.totalCents,appliedCapCents:z.totalCents,clampedReason:null};z&&(z=null,tt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?Pp:Ip,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new le(r.balanceCents,i);let a=n.capCentsOverride??ea(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let f=d.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let g={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return z=g,tt(g.budgetId),Kn(g.totalCents),m.info("mcp-session:opened",{budgetId:g.budgetId,capCents:g.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:s,expiresAt:g.expiresAt,tool:n.toolName}),{budgetId:g.budgetId,isFresh:!0,totalCents:g.totalCents,requestedCapCents:a,appliedCapCents:g.totalCents,clampedReason:c}}async function wc(e,t,n){return ko(async()=>{let s=wt()?await xc(e):null,o=await Sc(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function xc(e){let n=wt()?.budgetId??vo(),r=!1;if(n)try{r=!!(await e.closeSession(n))?.success}catch(s){m.warn("mcp-session:close-server-failed",{budgetId:n,error:s?.message||String(s)})}return Fr(),z=null,tt(null),{closedServerSide:r,budgetId:n}}async function zr(e){return ko(()=>xc(e))}function wt(){return Fr(),z?new Date(z.expiresAt).getTime()<=Date.now()?(z=null,tt(null),null):{budgetId:z.budgetId,totalCents:z.totalCents,lastReceiptCumulative:yc(),lastReceiptCumulativeMicros:fc()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:_c(),estimatedCumulative:Gr(),lastToolSpend:hc(),expiresAt:z.expiresAt}:null}var kc=R(Br()),Cc=10000n;function Mp(e){return e<=0n?0:Number((e+Cc-1n)/Cc)}function Tc(e){return Mp((0,kc.fromUsd)(e))}var Wr="Buying credits currently requires local biometric attestation from a macOS Touch ID-capable CLI/MCP process. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive Touch ID-capable CLI, then use the balance from this remote server. For unattended workloads, scoped API keys with daily caps are also supported.",Ec="Tell the user that buying credits requires a local Touch ID-capable CLI/MCP process today. Credits are account-level: suggest topping up the same account from any interactive Touch ID-capable CLI, then continuing on this remote server. For unattended workloads, scoped API keys with daily caps are also supported. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var Ac=Promise.resolve(),Rc=!1;function es(e){let t=Ac.catch(()=>{}).then(e);return Ac=t.then(()=>{},()=>{}),t}async function qc(e){let t=await To($,Pe,{toolName:e.toolId,userContext:e.userContext}),n=So(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await qp(),s,o,i=async()=>$.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof It){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(g=>setTimeout(g,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(u instanceof en){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await zr($),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return Rc||(Rc=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
106
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Vc(e)}throw u instanceof It?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=wo(o)??(n?xo(n):null);if(Co(s?.receipt_v2),await bc(e.estimatedAmountCents),gc({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Bc(s))return s;let l=await Fc();if(e.idempotencyKey&&Hc(s,l,e.idempotencyKey))return s;let c=l?Zr(l):null;return Kc(s,r,c)}function Be(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ro(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(Ro).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ro(r)}`).join(",")}}`}function Op(e,t,n,r){let s=oe.createHash("sha256").update(`${n}:${Ro(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function Np(e,t){return`${e}:${t}`}function Lp(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function $c(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=nt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=Lp(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:Np(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function Vc(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new le(n.balanceCents,t);let r=t,s=Zr(n),o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Pe("session_create",r,"Visa CLI Session",o,e.userContext),a=await $.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;tt(l),Kn(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=So(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await $.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(wo(d)||xo(c),Co(u?.receipt_v2),Bc(u))return u;let g=await Fc();if(e.idempotencyKey&&Hc(u,g,e.idempotencyKey))return u;let f=g?Zr(g):null;return Kc(u,s,f)}finally{try{await $.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}tt(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Ct(e){return es(async()=>wt()?qc(e):Vc(e))}function Io(){return we()}var $=new pe(()=>D.getSessionToken());function nt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Zr(e){return nt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Dp(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function Up(e){let t=nt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=nt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=nt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Jr(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function jp(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function qp(){try{let e=await $.getBalance();return e.success?Zr(e):null}catch{return null}}async function Fc(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function Bc(e){if(!e||e.success===!1)return!1;let t=nt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=nt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Hc(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=nt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Kc(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var Vp="2.0.2-rc.1",sb=["","","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 paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
106
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Vc(e)}throw u instanceof It?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=wo(o)??(n?xo(n):null);if(Co(s?.receipt_v2),await bc(e.estimatedAmountCents),gc({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Bc(s))return s;let l=await Fc();if(e.idempotencyKey&&Hc(s,l,e.idempotencyKey))return s;let c=l?Zr(l):null;return Kc(s,r,c)}function Be(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ro(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(Ro).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ro(r)}`).join(",")}}`}function Op(e,t,n,r){let s=oe.createHash("sha256").update(`${n}:${Ro(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function Np(e,t){return`${e}:${t}`}function Lp(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function $c(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=nt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=Lp(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:Np(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function Vc(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new le(n.balanceCents,t);let r=t,s=Zr(n),o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Pe("session_create",r,"Visa CLI Session",o,e.userContext),a=await $.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;tt(l),Kn(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=So(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await $.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(wo(d)||xo(c),Co(u?.receipt_v2),Bc(u))return u;let g=await Fc();if(e.idempotencyKey&&Hc(u,g,e.idempotencyKey))return u;let f=g?Zr(g):null;return Kc(u,s,f)}finally{try{await $.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}tt(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Ct(e){return es(async()=>wt()?qc(e):Vc(e))}function Io(){return we()}var $=new pe(()=>D.getSessionToken());function nt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Zr(e){return nt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Dp(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function Up(e){let t=nt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=nt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=nt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Jr(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function jp(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function qp(){try{let e=await $.getBalance();return e.success?Zr(e):null}catch{return null}}async function Fc(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function Bc(e){if(!e||e.success===!1)return!1;let t=nt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=nt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Hc(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=nt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Kc(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var Vp="2.1.0-rc.2",sb=["","","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 paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
107
107
  `);function Te(e){if(!e||typeof e!="string"||Xi())return;let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.toString(),r=ws();if(r.headless){m.info(`Browser auto-open skipped (${r.reason}). URL: ${n}`);return}m.info(`Browser auto-open disabled for security. Open manually: ${n}`)}async function _e(e){return _n($,e,Xc)}var Gc="get_cards",zc="set_default_card";function Fp(e,t=60){return`The processor returned a transient decline (code ${e??"unknown"}). This is not a permanent failure \u2014 it usually clears within ~${t} seconds and is most often triggered by rapid successive charges on the same card. Tell the user the call was temporarily declined and that you will retry shortly, then wait at least ${t} seconds before retrying the SAME call exactly once. Do not retry more than once. Do not assume the user has run out of funds. IMPORTANT: If the retry also fails, do NOT retry again \u2014 instead tell the user their default card may be temporarily locked by the processor and suggest switching to a different card. They can run '${Gc}' to see enrolled cards and '${zc}' to switch, then retry the original request.`}function Bp(e,t){return`The processor returned a non-retryable decline (code ${e??"unknown"}). Stop the current task and tell the user their card was declined for ${t||"the merchant"}. Suggest they check their card status or available balance. If they want to try a different default card, they can run '${Gc}' to see enrolled cards and '${zc}' to switch. Do not retry automatically.`}function Ie(e,t){let n=e.retryable?Fp(e.code,e.retryAfter):Bp(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}var vn=null,Hp=3e4;function Wc(){vn=null}var xt=class extends Error{constructor(n){super(`${Xr()} attestation is required for this action, but it is not available in this MCP process. `+Po());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function ts(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+Po()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Kp(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Wr,agent_guidance:Ec}}function Xr(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Po(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function ns(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function Gp(e){let t=Date.now();if(vn&&vn.expiresAt>t)return{required:vn.required,hasRegisteredKey:vn.hasRegisteredKey};try{let n=await $.getStatus(e),r=n.attestationRequired!==!1,s=ns(n);return vn={required:r,hasRegisteredKey:s,expiresAt:t+Hp},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Pe(e,t,n,r,s,o){if(!o?.forceRequired){let i=await Gp(s);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!Z())throw m.warn("attestation:unavailable",{context:e}),new xt(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await $.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await mn(a,r);return m.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw m.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Ic="[dry-run] https://placeholder.visa-cli.dev/image.png",zp=new Set(["generate_image_card","generate_image_fast_card","generate_image_schnell_card","generate_image_recraft_card","generate_image_ideogram_card","edit_image_seed_card","fal-flux-pro-ultra","fal-flux-pro","fal-flux-dev","fal-flux-schnell","fal-ideogram-v2","fal-ideogram-v2-turbo","fal-recraft-v3","fal-fast-sdxl"]),Wp=new Set(["generate_video_tempo_card","generate_video_kling_card","generate_video_wan_card","generate_video_minimax_card","fal-kling-video","fal-wan-video","fal-kling-i2v","fal-minimax-video"]);function Jp(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||zp.has(e)?"image":t==="generate_video"||Wp.has(e)?"video":null}function Yp(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Zp(e){return e==="llm"?"OpenRouter":"fal.ai"}function Sn(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Zp(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Yp(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Ic],data:{[e==="video"?"videoUrl":"imageUrl"]:Ic,metadata:{dry_run:!0}}}}async function Eo(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await $.emitTelemetry([{id:oe.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var Xp="https://openrouter.ai/api/v1/chat/completions",Qp="openrouter/free",ef=50,tf=15e3;function nf(e){let t=[e.prompt,e.user_prompt,e.input,e.text];for(let n of t)if(typeof n=="string"&&n.trim().length>0)return n;return"preflight"}async function rf(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return m.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Sn("llm",e,t,n),degraded:!0,resolvedModel:null};let s=nf(t),o;try{o=await Rt(Xp,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","HTTP-Referer":"https://visacli.sh/preflight","X-Title":"Visa CLI Preflight"},body:JSON.stringify({model:Qp,messages:[{role:"user",content:s}],max_tokens:ef}),timeoutMs:tf})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Sn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:Sn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Sn("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function rs(e,t,n,r){let s=ro();if(!s)return null;let o=Jp(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=Sn(o,e,t,r);return await Eo({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=Sn(o,e,t,r);return await Eo({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await rf(e,t,r);return await Eo({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function He(e,t,n){let r=await $.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function rt(e){return Tc(e.amount)}function sf(e){if(e.pricingMode==="max-cap"){let t=typeof e.estimatedAmount=="number"&&e.estimatedAmount>0?` (estimated $${e.estimatedAmount.toFixed(2)})`:"";return`pay up to $${e.amount.toFixed(2)} to ${e.merchantName}${t}`}return`pay $${e.amount.toFixed(2)} to ${e.merchantName}`}function of(){return Qr.join($o.homedir(),".visa-mcp","allium-results")}var ob=16*1024,ib=50*1024*1024;function af(){let e=of();try{if(!$e.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=$e.readdirSync(e),n=0,r=0;for(let s of t)try{let o=$e.statSync(Qr.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Pc=3600*1e3,Ao=0;function cf(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Gn(e){if(!Qi()&&!(Date.now()<Ao))try{if(!await D.getSessionToken())return;await $.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(cf(t)){let n=Ao===0;Ao=Date.now()+Pc,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Pc});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function lf(e,t){if(!e.url||!e.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let n=await He(void 0,e.url,t),r=Vr(e.url);m.info("payment:attempt",{tool:"pay",amount:n.amount,merchant:n.merchantName,url:e.url});try{return await _e(async()=>{let s=await Pe(e.url||"pay",n.amount,r,sf({...n,merchantName:r})),o=await $.pay({url:e.url||"",merchantName:e.merchantName||"Unknown",description:e.description||"",method:e.method,body:e.body,attestation:s,idempotencyKey:oe.randomUUID()},t);return o.success?(m.info("payment:success",{tool:"pay",amount:n.amount,merchant:n.merchantName,rail:o.receipt?.rail}),o.receipt&&Wf(o.receipt)):m.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,message:o.message}),o})}catch(s){if(s instanceof re)return m.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ie(s,n);throw m.error("payment:failure",{tool:"pay",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function uf(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await _e(async()=>{let c=await Pe("get_visa_smi",a,i,l),u=await $.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:oe.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof re)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ie(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw m.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function df(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await rs("generate_image_card",e,t);if(n)return n;let r=await He("generate_image_card",void 0,t),s=oe.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let o;try{o=await Ct({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Te(i)),Gn({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof re)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ie(o,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function mf(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await rs("generate_image_fast_card",e,t);if(n)return n;let r=await He("generate_image_fast_card",void 0,t),s=oe.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let o;try{o=await Ct({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Te(i)),Gn({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof re)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ie(o,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function pf(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await rs("generate_video_tempo_card",e,t);if(n)return n;let r=await He("generate_video_tempo_card",void 0,t),s=oe.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let o;try{o=await Ct({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Be(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Te(i)),Gn({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof re)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ie(o,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function ff(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await He("generate_music_tempo_card",void 0,t),r=oe.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let s;try{s=await Ct({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Be(o);throw o}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>Te(o)),Gn({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof re)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ie(s,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function gf(e,t){let n=await He("check_music_status_tempo_card",void 0,t),r=oe.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let s;try{s=await Ct({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Be(o);throw o}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>Te(o)),s})}catch(s){if(s instanceof re)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ie(s,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function hf(e,t){if(!e.chain||!e.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!e.token_address||!e.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let n=await He("query_onchain_prices",void 0,t),r=oe.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let s;try{s=await Ct({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Be(o);throw o}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof re)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ie(s,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var yf=["generate_music_tempo_card"],Mc=10,Oc=5,Nc=new Map;function Lc(e){let t=Nc.get(e);if(t!==void 0)return t;let r=Un(e)?.isAsync===!0||yf.includes(e);return Nc.set(e,r),r}var _f=36e4,bf=18e4,vf=15e3,Sf=12e4,wf=2e3;function Dc(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function xf(e,t){let n;if(e.requests?.some(T=>T.tool||T.tool_id)&&e.requests)n=e.requests.map(T=>{let C=T.tool||T.tool_id||e.tool;if(!C)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let V=no(C,T.tier||e.tier,T.prompt??t),{tool:G,tool_id:F,tier:it,params:te,...ue}=T,at=te&&typeof te=="object"?{...te,...ue}:ue;return{resolvedTool:V,params:at}});else if(e.tool){let T=no(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(V=>({resolvedTool:T,params:V}))}else return Dc("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Dc("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Mc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Mc} items. Please split into smaller batches.`};if([...new Set(n.map(T=>T.resolvedTool))].some(Lc)&&n.length>Oc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Oc} items. Please use multiple batches for more.`};let i=[...new Set(n.map(T=>T.resolvedTool))],a=i.length===1,l={};for(let T of i)l[T]=await He(T,void 0,t);let c=0;for(let T of n)c+=l[T.resolvedTool].amount;let u=[...new Set(Object.values(l).map(T=>T.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let g=n.some(T=>Lc(T.resolvedTool)),f=n.some(T=>T.resolvedTool.startsWith("or-")||T.resolvedTool==="run_llm"||T.resolvedTool==="execute_tool"),x=g?_f:f?bf+n.length*vf:Sf+n.length*wf,y=oe.randomUUID(),A=[],N=0,L=0n;return es(async()=>{let T=!wt();if(T)try{let C=Math.max(1,Math.ceil(c*100));await To($,Pe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:C,capCentsOverride:C})}catch(C){return C instanceof le?Be(C):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:C?.message||String(C)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:C?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let te=0;te<n.length;te+=1){let ue=n[te],at=l[ue.resolvedTool];try{let ne=await qc({toolId:ue.resolvedTool,toolParams:ue.params,estimatedAmountCents:rt(at),userContext:t,metaTool:"batch",timeoutMs:x,idempotencyKey:Op(y,te,ue.resolvedTool,ue.params)});if(A.push({success:ne?.success!==!1,tool:ue.resolvedTool,...ne,...$c(y,te,ne)}),ne?.success!==!1){let Tn=nt(ne?.amountMicros??ne?.amount_micros),Zo=typeof ne?.amount=="number"?ne.amount:at.amount;Tn!==null&&Tn>0n?L+=Tn:L+=BigInt(Math.round(Zo*1e6)),N+=Zo}ne?.urls&&ne.urls.forEach(Tn=>Te(Tn))}catch(ne){if(ne instanceof le&&A.length===0)return Be(ne);m.warn("payment:batch-item-failed",{tool:ue.resolvedTool,index:te,error:ne?.message||String(ne)}),A.push({success:!1,tool:ue.resolvedTool,...$c(y,te),error:ne?.message||String(ne)})}}let C=A.filter(te=>te?.success===!1).length,V=A.length-C,G=A.flatMap(te=>Array.isArray(te?.urls)?te.urls:[]),F=L>0n?Number(L)/1e6:Math.round((N+Number.EPSILON)*100)/100,it=V===0?"failure":C===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:F,merchant:u,successCount:V,failedCount:C,outcome:it,mode:"session",batchId:y}),{success:V>0,outcome:it,batch_id:y,tool:a?i[0]:d,count:n.length,successCount:V,failedCount:C,totalCharged:F,...L>0n?{totalChargedMicros:L.toString(),amountMicros:L.toString(),amount_micros:L.toString()}:{},merchantName:u,results:A,...G.length?{urls:G}:{}}}catch(C){if(C instanceof re)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:C.code,retryable:C.retryable}),Ie(C,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:C.message}),C}finally{if(T){let C=await zr($);m.info("batch-session:closed",{budgetId:C.budgetId,closedServerSide:C.closedServerSide})}}})}function Cf(){let e=!1,t;try{let r=Qr.join($o.homedir(),".claude","settings.json");if($e.existsSync(r)){let s=JSON.parse($e.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=Et(o)}}catch{}let n=Or();return n||(t="visa-cli config shell-hud install"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function kf(e){let[t,n]=await Promise.all([$.getStatus(e),$.getBalance().catch(o=>(m.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=af();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Cf(),t.version=Vp,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:Mo(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=wt();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function Mo(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function Jc(e,t){try{let r=((await $.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return Mo(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Tf(e){let n=(await $.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:Mo(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Ef(e,t){return await $.getTransactions({limit:e.limit,offset:e.offset},t)}async function Af(e,t){return await $.feedback(e.message,e.transaction_id,t)}var Rf=100;async function $f(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Zt("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<Rf)return{success:!1,error:"Minimum top-up is $1.00"};let r=oe.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await _e(async()=>{let s=await Pe("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),o=await $.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){m.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof xt)return Kp();throw m.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function Zt(e,t){return{success:!1,error:t,code:e,message:t}}async function If(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Zt("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>100))return Zt("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return Zt("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Zt("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await _e(async()=>{let n=await Pe("spending-controls",0,"","update spending controls"),r=await $.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof xt)return ts(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Zt("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Pf(e){let t=await qr({api:$,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function Mf(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};m.info("config:set",{key:e.key});try{let t=br(e.key,e.value);return m.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof ze?"UNKNOWN_KEY":t instanceof We?"SERVER_CONTROLLED":t instanceof mt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ft).sort()}}}async function Of(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};m.info("config:unset",{key:e.key});try{let t=vr(e.key);return m.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof ze?"UNKNOWN_KEY":t instanceof We?"SERVER_CONTROLLED":t instanceof mt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ft).sort()}}}async function Nf(e){let t=await $.getStatus(e),n=t.attestationRequired!==!1,r=ns(t),s=Z(),o=n?r?s?`${Xr()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Xr()} is not available in this process. ${Po()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function Lf(e){m.info("biometric:on");let t=await $.setBiometricPreference({required:!0},e);return t.success?(Wc(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function Df(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Zt("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await _e(async()=>{let n=await $.getStatus(t),r;if(ns(n)&&(r=await Pe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Xr()} confirmation required to disable \u2014 not available on this device.`);let s=await $.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Wc(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(m.error("biometric:off:failure",{error:n.message}),n instanceof xt)return ts(n,"biometric_off");throw n}}var Uc=3e4,Uf=3e5;async function Yc(e,t,n="login"){let r=oe.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Te(s),Zc(r,t,n)}async function Zc(e,t,n="login"){let r=Date.now()+Uf;for(;Date.now()<r;)try{let o=await fetch(`${Io()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Uc,...t&&{user_context:t}}),signal:AbortSignal.timeout(Uc+5e3)});if(!o.ok){await dt(o,a=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=rc(a);if(i.sessionToken){await D.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await dt(void 0,o=>{m.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Xc(e){let t=oe.randomUUID(),n;try{n=await $.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(Te(n.recoveryUrl),Zc(t,e,"attestation-recovery"))}async function jf(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await Jc(n,t)}`;try{return await _e(async()=>{let o=await Pe(r,0,"",s,t,{forceRequired:!0}),i=await $.removeCard(n,{attestation:o},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(m.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof xt)return ts(o,"remove_card");throw o}}async function qf(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await Jc(n,t)} as default`;try{return await _e(async()=>{let o=await Pe(r,0,"",s,t,{forceRequired:!0}),i=await $.setDefaultCard(n,{attestation:o},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(m.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof xt)return ts(o,"set_default_card");throw o}}async function Vf(e){return m.info("auth:login_attempt"),Yc(`${Io()}/login`,e)}function Ff(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<10||t>1e4)throw new Error("capCents must be between 10 ($0.10) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<.1||t>100)throw new Error("capUsd must be between 0.10 and 100");return Math.floor(t*100)}}async function Bf(e={},t){let n;try{n=Ff(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return es(async()=>{let r=await wc($,Pe,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function Hf(){let e=wt();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function Kf(){return es(async()=>{let e=wt();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await zr($);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Up(e),r=n.micros,s=Number(r/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:r.toString(),finalSpendCents:s,finalSpendSource:n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:r.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${Dp(r)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function Gf(e){return m.info("auth:add_card_attempt"),await D.getSessionToken()?Yc(`${Io()}/enroll`,e,"enrollment"):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function zf(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await $.getStatus(t);if(r&&ns(r)){let s=await Xc(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};m.warn("reset:server_attestation_status_unavailable",{error:s})}try{await $.logout(void 0,t)}catch{}if(await D.clearAll(),Z())try{await $r()}catch{}return m.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}function Wf(e){let t=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let n of t){let r=e[n];r&&typeof r=="string"&&r.startsWith("http")&&Te(r)}Array.isArray(e.urls)&&e.urls.forEach(n=>{n&&typeof n=="string"&&n.startsWith("http")&&Te(n)})}async function Jf(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await $.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((g,f)=>`${f+1}. **${g.name}** (${g.id})
108
108
  ${g.description}
109
109
  Provider: ${g.provider} | Price: ${jc(g)}
@@ -250,7 +250,7 @@ ${n.id}
250
250
  Price`),console.log(` ${Go(n.priceCents,n.priceDisplay)}`),console.log(`
251
251
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
252
252
  Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set;for(let[i,a]of Object.entries(r)){let l=o.has(i)?"required":"optional",c=a?.description?` - ${a.description}`:"";console.log(` ${i.padEnd(12)} ${l}${c}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
253
- Examples`);let s=el(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function sh(e){return["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"].includes(e)}async function Il(e,t,n){return sh(e)?Fe.shortcut(e,t,n):Fe.executeTool({tool_id:e,params:t},n,"execute_tool")}kn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(e,t)=>{try{let n=Lg(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await Il(e,n,`visa-cli merchants run ${e}`);vl(r),wl(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});kn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
253
+ Examples`);let s=el(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function sh(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","check_fal_status_card","query_onchain_prices"].includes(e)}async function Il(e,t,n){return sh(e)?Fe.shortcut(e,t,n):Fe.executeTool({tool_id:e,params:t},n,"execute_tool")}kn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(e,t)=>{try{let n=Lg(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await Il(e,n,`visa-cli merchants run ${e}`);vl(r),wl(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});kn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
254
254
  Platform-merchant tool discovery is cached in-process by the MCP server.`),console.log(" Cache TTL: VISA_MERCHANT_DISCOVER_TTL_MS (default 300000ms = 5min)."),console.log(` To force-refresh now, restart Claude / Cursor \u2014 the next tools/list will re-fetch.
255
255
  `)});var tr=K.command("generate").description("Generate media with merchant tools").addHelpCommand(!1);async function nr(e){console.log(`
256
256
  ${e.kind}