@visa/cli 1.0.6 → 1.0.7-rc.1
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/README.md +122 -79
- package/dist/cli.js +2 -2
- package/dist/mcp-server/index.js +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @visa/cli
|
|
2
2
|
|
|
3
|
-
AI-powered payments
|
|
3
|
+
AI-powered payments over MCP. Exposes Visa card payment tools as MCP (Model Context Protocol) tools so your AI assistant can pay for image generation, video, music, onchain data queries, and more — charged to a Visa card with Touch ID confirmation at the point of invocation.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -8,26 +8,9 @@ AI-powered payments for Claude Code. Exposes Visa card payment tools as MCP (Mod
|
|
|
8
8
|
npm install -g @visa/cli
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## MCP setup
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
# Start MCP server (used by Claude Code)
|
|
15
|
-
visa-cli mcp
|
|
16
|
-
|
|
17
|
-
# Login with GitHub
|
|
18
|
-
visa-cli login
|
|
19
|
-
|
|
20
|
-
# Add a Visa card
|
|
21
|
-
visa-cli add-card
|
|
22
|
-
|
|
23
|
-
# Check status
|
|
24
|
-
visa-cli status
|
|
25
|
-
|
|
26
|
-
# View transaction history
|
|
27
|
-
visa-cli history
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
### Claude Code integration
|
|
13
|
+
Add to your MCP client config:
|
|
31
14
|
|
|
32
15
|
```json
|
|
33
16
|
{
|
|
@@ -40,92 +23,152 @@ visa-cli history
|
|
|
40
23
|
}
|
|
41
24
|
```
|
|
42
25
|
|
|
26
|
+
Once connected, your assistant will have access to all payment tools. The first time you use a paid tool, you'll be prompted to log in and enroll a card.
|
|
27
|
+
|
|
43
28
|
---
|
|
44
29
|
|
|
45
|
-
##
|
|
30
|
+
## CLI commands
|
|
46
31
|
|
|
47
|
-
|
|
32
|
+
```bash
|
|
33
|
+
visa-cli login # GitHub OAuth — opens browser, stores session token
|
|
34
|
+
visa-cli add-card # Enroll a Visa card via VGS secure form
|
|
35
|
+
visa-cli status # Show auth state, enrolled cards, daily spend remaining
|
|
36
|
+
visa-cli history # Recent transactions with amounts and any generated media URLs
|
|
37
|
+
visa-cli mcp # Start the MCP server
|
|
38
|
+
```
|
|
48
39
|
|
|
49
|
-
|
|
50
|
-
|------|-------------|
|
|
51
|
-
| `login` | GitHub OAuth login flow |
|
|
52
|
-
| `add_card` | Enroll a Visa card via VGS tokenization |
|
|
53
|
-
| `reset` | Reset auth state |
|
|
54
|
-
| `pay` | Generic payment endpoint |
|
|
55
|
-
| `get_status` | Auth + card + account status |
|
|
56
|
-
| `get_cards` | List enrolled cards |
|
|
57
|
-
| `transaction_history` | Recent transactions with amounts |
|
|
58
|
-
| `update_spending_controls` | Set daily/per-transaction limits |
|
|
59
|
-
| `send_feedback` | Submit feedback on a tool result |
|
|
60
|
-
| `get_feedback` | Retrieve feedback history |
|
|
61
|
-
| `batch` | Batch multiple tool calls |
|
|
62
|
-
| `discover` | List all available tools with pricing |
|
|
40
|
+
---
|
|
63
41
|
|
|
64
|
-
|
|
42
|
+
## Authentication
|
|
65
43
|
|
|
66
|
-
|
|
44
|
+
Login is GitHub OAuth. Your session token is stored at `~/.visa-mcp/config.json`.
|
|
67
45
|
|
|
68
|
-
|
|
46
|
+
```bash
|
|
47
|
+
visa-cli login # opens github.com/login/oauth/authorize in your browser
|
|
48
|
+
visa-cli status # verify you're logged in
|
|
49
|
+
```
|
|
69
50
|
|
|
70
51
|
---
|
|
71
52
|
|
|
72
|
-
##
|
|
53
|
+
## Card enrollment
|
|
73
54
|
|
|
55
|
+
Cards are tokenized via VGS — your raw card number never touches Visa servers. `add_card` opens a hosted VGS Collect form in your browser.
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
visa-cli add-card
|
|
74
59
|
```
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
3. Baseline: CATALOG from @visa/tools (compiled-in fallback)
|
|
78
|
-
```
|
|
60
|
+
|
|
61
|
+
Multiple cards can be enrolled. The first becomes the default; you can switch defaults with `set_default_card` from within your assistant. To remove a card: `remove_card` (requires Touch ID).
|
|
79
62
|
|
|
80
63
|
---
|
|
81
64
|
|
|
82
|
-
##
|
|
65
|
+
## Payments & Touch ID
|
|
83
66
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
│ ├── tools.ts Core tool handler implementations
|
|
91
|
-
│ └── suggestions.ts Dynamic catalog polling
|
|
92
|
-
├── touchid.ts macOS Touch ID / Secure Enclave attestation
|
|
93
|
-
├── rc-gate.ts RC version gate (checks RC_CODE_HASH)
|
|
94
|
-
└── config/
|
|
95
|
-
└── manager.ts ~/.visa-mcp/config.json read/write
|
|
67
|
+
Every paid tool call requires Touch ID (or device password on macOS). Your assistant will show you the amount and merchant before prompting. If you cancel Touch ID, the payment is aborted — nothing is charged.
|
|
68
|
+
|
|
69
|
+
You can set hard limits via the `update_spending_controls` tool, or check your current limits any time:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
visa-cli status
|
|
96
73
|
```
|
|
97
74
|
|
|
98
75
|
---
|
|
99
76
|
|
|
100
|
-
##
|
|
77
|
+
## MCP tools
|
|
101
78
|
|
|
102
|
-
|
|
103
|
-
# From monorepo root
|
|
104
|
-
pnpm --filter @visa/cli build
|
|
105
|
-
pnpm --filter @visa/cli test
|
|
106
|
-
pnpm --filter @visa/cli test:unit:coverage
|
|
79
|
+
### Account
|
|
107
80
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
81
|
+
| Tool | Description |
|
|
82
|
+
|------|-------------|
|
|
83
|
+
| `login` | GitHub OAuth login — opens browser |
|
|
84
|
+
| `add_card` | Enroll a card via VGS tokenization |
|
|
85
|
+
| `get_cards` | List enrolled cards (masked) |
|
|
86
|
+
| `remove_card` | Remove an enrolled card (Touch ID required) |
|
|
87
|
+
| `set_default_card` | Change the default card (Touch ID required) |
|
|
88
|
+
| `get_status` | Auth, card, spend limits, and budget summary |
|
|
89
|
+
| `update_spending_controls` | Set daily and per-transaction limits (Touch ID required) |
|
|
90
|
+
| `transaction_history` | Recent transactions with amounts and media URLs |
|
|
91
|
+
| `feedback` | Submit feedback on a tool result |
|
|
92
|
+
| `reset` | Clear auth state and credentials |
|
|
93
|
+
|
|
94
|
+
### Generation
|
|
95
|
+
|
|
96
|
+
| Tool | Price | Description |
|
|
97
|
+
|------|-------|-------------|
|
|
98
|
+
| `generate_image_card` | ~$0.06 | FLUX1.1 Ultra — 2K resolution, ~30s |
|
|
99
|
+
| `generate_image_fast_card` | ~$0.04 | FLUX1.1 Pro — 1K resolution, ~10s |
|
|
100
|
+
| `generate_video` | $0.10–$0.30 | Text-to-video (Wan / MiniMax / Kling) |
|
|
101
|
+
| `generate_music_tempo_card` | ~$0.10 | Suno AI music generation, ~2 min |
|
|
102
|
+
| `check_music_status_tempo_card` | ~$0.01 | Poll Suno task for audio URL |
|
|
103
|
+
| `generate_audio` | ~$0.03–$0.04 | TTS (MetaVoice) or SFX (Stable Audio) |
|
|
104
|
+
| `generate_3d` | ~$0.08 | Text-to-3D mesh (Trellis), returns GLB URL |
|
|
105
|
+
| `upscale_image` | ~$0.03 | Image upscaling (Aura SR) |
|
|
106
|
+
| `transcribe_audio` | ~$0.02 | Speech-to-text (Whisper) |
|
|
107
|
+
|
|
108
|
+
### Data
|
|
109
|
+
|
|
110
|
+
| Tool | Price | Description |
|
|
111
|
+
|------|-------|-------------|
|
|
112
|
+
| `query_onchain_prices_card` | ~$0.02 | Real-time or historical token prices (150+ chains via Allium) |
|
|
113
|
+
| `allium_explorer_card` | ~$0.10 | Natural language → SQL blockchain query (step 1) |
|
|
114
|
+
| `allium_explorer_results_card` | up to $3.00 | Fetch results for a submitted query (step 2) |
|
|
115
|
+
| `run_llm` | $0.01–$0.09 | Run a prompt through GPT-4o Mini, Claude, DeepSeek, Perplexity, or Llama |
|
|
116
|
+
|
|
117
|
+
### Utility
|
|
111
118
|
|
|
112
|
-
|
|
119
|
+
| Tool | Description |
|
|
120
|
+
|------|-------------|
|
|
121
|
+
| `pay` | Generic HTTP 402 payment endpoint |
|
|
122
|
+
| `batch` | Execute multiple paid tools in one Touch ID approval |
|
|
123
|
+
| `discover_tools` | Search the dynamic tool catalog |
|
|
124
|
+
| `execute_tool` | Run a tool from the dynamic catalog by ID |
|
|
113
125
|
|
|
114
|
-
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Dynamic catalog
|
|
129
|
+
|
|
130
|
+
The tool catalog is fetched live from the auth server at startup (5-minute TTL). If the server is unreachable, it falls back to the compiled-in baseline from `@visa/tools`.
|
|
131
|
+
|
|
132
|
+
To see all available tools with current pricing, ask your assistant:
|
|
133
|
+
|
|
134
|
+
> "What tools do you have available?"
|
|
115
135
|
|
|
116
136
|
---
|
|
117
137
|
|
|
118
|
-
##
|
|
138
|
+
## Spending controls
|
|
119
139
|
|
|
120
140
|
```
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
→ CI passes on dev
|
|
124
|
-
→ cli-release-rc.yml (bumps RC version, pushes v*-rc.* tag)
|
|
125
|
-
→ cli-publish.yml (injects hash, builds, publishes @visa/cli@rc)
|
|
126
|
-
|
|
127
|
-
Merge dev → main
|
|
128
|
-
→ CI passes on main
|
|
129
|
-
→ cli-release-stable.yml (exits pre mode, bumps stable, pushes v* tag)
|
|
130
|
-
→ cli-publish.yml (publishes @visa/cli@latest)
|
|
141
|
+
Daily limit — hard cap on total spend per day
|
|
142
|
+
Max per-transaction — hard cap per single tool call
|
|
131
143
|
```
|
|
144
|
+
|
|
145
|
+
Both limits are enforced server-side. Touch ID is always required per payment regardless of limits — this cannot be disabled.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## Config & data locations
|
|
150
|
+
|
|
151
|
+
| Path | Contents |
|
|
152
|
+
|------|----------|
|
|
153
|
+
| `~/.visa-mcp/config.json` | Session token, device key |
|
|
154
|
+
| `~/.visa-mcp/catalog-cache.json` | Cached tool catalog (24h TTL) |
|
|
155
|
+
| `~/.visa-mcp/allium-results/` | Large query result CSVs |
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Troubleshooting
|
|
160
|
+
|
|
161
|
+
**Touch ID prompt doesn't appear**
|
|
162
|
+
Make sure `visa-cli mcp` is running as a foreground process that has access to the macOS security framework. Running inside some sandboxed environments may prevent Touch ID.
|
|
163
|
+
|
|
164
|
+
**"Not logged in" after `visa-cli login`**
|
|
165
|
+
Restart the MCP server after logging in — your MCP client needs to reconnect to pick up the new session.
|
|
166
|
+
|
|
167
|
+
**Card not showing in `get_cards`**
|
|
168
|
+
Enrollment is only confirmed after you complete the VGS form in the browser. Call `get_cards` after finishing the form to verify.
|
|
169
|
+
|
|
170
|
+
**Tool returns an error about daily limit**
|
|
171
|
+
Check your remaining budget with `visa-cli status` or ask your assistant: "What's my remaining budget today?"
|
|
172
|
+
|
|
173
|
+
**Catalog shows stale tools**
|
|
174
|
+
Delete `~/.visa-mcp/catalog-cache.json` and restart the MCP server to force a fresh fetch.
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var rt=Object.create;var ge=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var ct=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ot(e))!at.call(t,s)&&s!==n&&ge(t,s,{get:()=>e[s],enumerable:!(r=st(e,s))||r.enumerable});return t};var g=(t,e,n)=>(n=t!=null?rt(it(t)):{},lt(e||!t||!t.__esModule?ge(n,"default",{value:t,enumerable:!0}):n,t));var ee=ct((Ut,mt)=>{mt.exports={name:"@visa/cli",version:"1.0.
|
|
1
|
+
"use strict";var rt=Object.create;var ge=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var ct=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ot(e))!at.call(t,s)&&s!==n&&ge(t,s,{get:()=>e[s],enumerable:!(r=st(e,s))||r.enumerable});return t};var g=(t,e,n)=>(n=t!=null?rt(it(t)):{},lt(e||!t||!t.__esModule?ge(n,"default",{value:t,enumerable:!0}):n,t));var ee=ct((Ut,mt)=>{mt.exports={name:"@visa/cli",version:"1.0.7-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^22.10.0","@typescript-eslint/eslint-plugin":"^8.56.1","@typescript-eslint/parser":"^8.56.1","@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.1","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});var Xe=require("commander"),z=g(require("crypto")),N=g(require("os")),Ze=require("child_process"),Qe=require("util");var ye=require("child_process"),Se=require("util"),E=g(require("fs")),ve=g(require("os")),Z=g(require("path")),P=(0,Se.promisify)(ye.execFile),Q=Z.join(ve.homedir(),".visa-mcp"),U=Z.join(Q,"session-token"),k="visa-cli",V="session-token",K="rc-access";async function fe(){try{let{stdout:t}=await P("security",["find-generic-password","-s",k,"-a",V,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function me(t){try{try{await P("security",["delete-generic-password","-s",k,"-a",V],{timeout:5e3})}catch{}return await P("security",["add-generic-password","-s",k,"-a",V,"-w",t],{timeout:5e3}),!0}catch{return!1}}async function he(){try{await P("security",["delete-generic-password","-s",k,"-a",V],{timeout:5e3})}catch{}}async function ut(){try{let{stdout:t}=await P("security",["find-generic-password","-s",k,"-a",K,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function dt(t){try{try{await P("security",["delete-generic-password","-s",k,"-a",K],{timeout:5e3})}catch{}await P("security",["add-generic-password","-s",k,"-a",K,"-w",t],{timeout:5e3})}catch{}}async function pt(){try{await P("security",["delete-generic-password","-s",k,"-a",K],{timeout:5e3})}catch{}}function gt(t){E.mkdirSync(Q,{recursive:!0,mode:448}),E.writeFileSync(U,t,{mode:384})}function ft(){try{return E.readFileSync(U,"utf-8").trim()||null}catch{return null}}var h=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=await fe();if(e)return e;let n=ft();return n?(await me(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;if(await me(e)){if(await fe()===e){try{E.unlinkSync(U)}catch{}return}await he()}if(gt(e),await this.getSessionToken()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Q} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":ut()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await dt(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN!=="true"){await he();try{E.unlinkSync(U)}catch{}}}static async clearAll(){await this.deleteSessionToken(),await pt()}};var D=g(require("crypto")),H=g(require("tty")),F=g(require("fs"));var R="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function ht(t){return/-rc\.|-beta\./.test(t)}function te(t){return D.createHash("sha256").update(t.trim()).digest("hex")}function we(t){return R==="SKIP"?!0:D.timingSafeEqual(Buffer.from(te(t)),Buffer.from(R))}function yt(t){return new Promise((e,n)=>{let r=F.openSync("/dev/tty","r+"),s=new H.ReadStream(r),o=new H.WriteStream(r),a=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{F.closeSync(r)}catch{}};o.write(t),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let i="";s.on("data",c=>{c==="\r"||c===`
|
|
2
2
|
`?(o.write(`
|
|
3
3
|
`),a(),e(i)):c===""?(o.write(`
|
|
4
4
|
`),a(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?i.length>0&&(i=i.slice(0,-1),o.write("\b \b")):(i+=c,o.write("\u2022"))})})}var St=`
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
Invalid code. Contact your team lead.
|
|
20
20
|
`),process.exit(1)}var Ce=require("child_process");function vt(t=process.env,e=process.platform){return t.VISA_CLI_NO_BROWSER==="1"||t.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:t.CI==="true"||t.CI==="1"?{headless:!0,reason:"CI environment detected"}:t.SSH_CONNECTION||t.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function wt(t){let n=t.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${t}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
|
|
21
21
|
`)}function bt(t,e=process.platform){return e==="darwin"?{cmd:"open",args:[t]}:e==="win32"?{cmd:"cmd",args:["/c","start","",t]}:e==="linux"?{cmd:"xdg-open",args:[t]}:null}async function Ee(t,e={}){let n=e.log??(c=>console.log(c)),r=e.env??process.env,s=e.platform??process.platform,o=e.spawn??((c,l,d)=>{(0,Ce.execFile)(c,l,b=>d(b))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of wt(t).split(`
|
|
22
|
-
`))n(` ${c}`);n("");let a=vt(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let i=bt(t,s);if(!i){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(i.cmd,i.args,l=>{l?(n(` Could not open browser automatically (${l.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}async function Pe(t,e){let n=e?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...a}=e??{};return await fetch(t,{...a,signal:r.signal})}finally{clearTimeout(s)}}var Ct=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Re(t,e){let n=ke(t),r=ke(e);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:Et(n.pre,r.pre)>0}function ke(t){if(typeof t!="string")return null;let n=t.trim().replace(/^v/,"").match(Ct);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Et(t,e){let n=t.split("."),r=e.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 a=n[o],i=r[o],c=/^\d+$/.test(a),l=/^\d+$/.test(i);if(c&&l){let d=Number(a)-Number(i);if(d!==0)return d}else{if(c)return-1;if(l)return 1;if(a<i)return-1;if(a>i)return 1}}return 0}function q(){return!!($e(process.env.VISA_CLI_NO_UPDATE_CHECK)||$e(process.env.CI)||process.env.NODE_ENV==="test")}function $e(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var ne="1.0.
|
|
22
|
+
`))n(` ${c}`);n("");let a=vt(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let i=bt(t,s);if(!i){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{o(i.cmd,i.args,l=>{l?(n(` Could not open browser automatically (${l.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()})})}async function Pe(t,e){let n=e?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...a}=e??{};return await fetch(t,{...a,signal:r.signal})}finally{clearTimeout(s)}}var Ct=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Re(t,e){let n=ke(t),r=ke(e);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:Et(n.pre,r.pre)>0}function ke(t){if(typeof t!="string")return null;let n=t.trim().replace(/^v/,"").match(Ct);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Et(t,e){let n=t.split("."),r=e.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 a=n[o],i=r[o],c=/^\d+$/.test(a),l=/^\d+$/.test(i);if(c&&l){let d=Number(a)-Number(i);if(d!==0)return d}else{if(c)return-1;if(l)return 1;if(a<i)return-1;if(a>i)return 1}}return 0}function q(){return!!($e(process.env.VISA_CLI_NO_UPDATE_CHECK)||$e(process.env.CI)||process.env.NODE_ENV==="test")}function $e(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var ne="1.0.7-rc.1",A=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!q()){let r=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");r&&Re(r,ne)&&(this.lastSignals.updateAvailable={version:r,message:s||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=e.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return ne}async request(e,n,r,s,o){let a=await this.getSessionToken();if(!a)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let i={Authorization:`Bearer ${a}`};o&&(e==="GET"?i["X-User-Context"]=o.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:o}),r&&(i["Content-Type"]="application/json");let c;try{c=await Pe(`${this.baseUrl}${n}`,{method:e,headers:{...i,"X-Visa-CLI-Version":ne},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw d.name==="AbortError"||d.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let 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.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(e,n){return this.request("POST","/v1/pay",e,void 0,n)}async shortcut(e,n,r,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,n,r,s)}async batch(e,n,r){return this.request("POST","/v1/batch",e,n,r)}async catalogSearch(e,n){let r=new URLSearchParams;e&&r.set("q",e),n&&r.set("category",n);let s=r.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,n){return this.request("POST","/v1/payment-preview",e,void 0,n)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,n){return this.request("POST","/v1/spending-controls",e,void 0,n)}async removeCard(e,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,n,void 0,r)}async setDefaultCard(e,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,n){return this.request("POST","/v1/logout",e,void 0,n)}async feedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let n=new URLSearchParams;e?.tab&&n.set("tab",e.tab),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(e,n){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:n})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,n,r){return this.request("POST","/v1/feedback",{message:e,...n&&{transaction_id:n}},void 0,r)}async getFeedback(e,n){let r=new URLSearchParams;e&&r.set("limit",String(e));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var ae=require("child_process"),_e=require("util"),je=g(require("crypto")),f=g(require("fs")),Me=g(require("os")),C=g(require("path"));var y=g(require("fs")),oe=g(require("path")),xe=g(require("os")),se=oe.join(xe.homedir(),".visa-mcp"),O=oe.join(se,"mcp-server.log"),Pt=5*1024*1024,re=null;function kt(){y.existsSync(se)||y.mkdirSync(se,{recursive:!0,mode:448})}function Rt(){if(!re){if(kt(),y.existsSync(O)&&y.statSync(O).size>Pt){let e=O+".1";y.existsSync(e)&&y.unlinkSync(e),y.renameSync(O,e)}re=y.createWriteStream(O,{flags:"a"})}return re}function B(t,...e){let n=new Date().toISOString(),r=e.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${t}] ${r}
|
|
23
23
|
`;process.stderr.write(s),Rt().write(s)}var Ie={debug:(...t)=>B("DEBUG",...t),info:(...t)=>B("INFO",...t),warn:(...t)=>B("WARN",...t),error:(...t)=>B("ERROR",...t)};var I=(0,_e.promisify)(ae.execFile),Y=C.join(Me.homedir(),".visa-mcp","bin"),$=C.join(Y,"Visa CLI"),$t=C.join(__dirname,"..","native"),Ne="5",Te=C.join(Y,"visa-keychain.version"),Ae=C.join(Y,"visa-keychain.sha256");function Oe(t){let e=f.readFileSync(t);return je.createHash("sha256").update(e).digest("hex")}async function Le(){try{if(f.readFileSync(Te,"utf-8").trim()===Ne&&f.existsSync($)){let r=f.readFileSync(Ae,"utf-8").trim();if(Oe($)!==r)Ie.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),f.unlinkSync($);else return $}}catch{}let t=C.join($t,"visa-keychain.m");if(f.existsSync(t)||(t=C.resolve(__dirname,"..","..","native","visa-keychain.m")),f.existsSync(t)||(t=C.resolve(__dirname,"..","native","visa-keychain.m")),!f.existsSync(t))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");f.mkdirSync(Y,{recursive:!0,mode:448});try{await I("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",$,t],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let e=Oe($);return f.writeFileSync(Ae,e,{mode:384}),f.writeFileSync(Te,Ne,{mode:384}),$}async function Ue(t){let e=await Le(),n;try{n=(await I(e,t,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let a=n.trim();throw a.startsWith("ERROR:")?new Error(a.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 ie=null;function _(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:ie!==null?ie:(ie=!0,!0)}var G="visa-cli",W="attestation-key";async function xt(t){try{await I("security",["delete-generic-password","-s",G,"-a",W],{timeout:5e3})}catch{}await I("security",["add-generic-password","-s",G,"-a",W,"-w",t],{timeout:5e3})}async function It(){try{let{stdout:t}=await I("security",["find-generic-password","-s",G,"-a",W,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function Ve(){let t=await Ue(["generate-key"]);if(!t)throw new Error("Key generation returned no output");let e=t.indexOf(":");if(e<0)throw new Error("Unexpected generate-key output format");let n=t.slice(0,e),r=t.slice(e+1);return await xt(n),r}async function Ke(t,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await It();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Le(),s=["sign",t];return e&&s.push(e),new Promise((o,a)=>{let i=(0,ae.execFile)(r,s,{timeout:6e4},(c,l)=>{let d=(l||"").trim();if(c){d.startsWith("ERROR:")?a(new Error(d.slice(6))):a(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}d.startsWith("OK:")?o(d.slice(3)):a(new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error"))});i.stdin.write(n),i.stdin.end()})}async function De(){try{await I("security",["delete-generic-password","-s",G,"-a",W],{timeout:5e3})}catch{}try{await Ue(["delete-key"])}catch{}}function He(t,e=process.stderr){if(q()||!t?.updateAvailable)return!1;let{message:n}=t.updateAvailable;return n?(e.write(`
|
|
24
24
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
25
25
|
`),!0):!1}var S=class extends Error{constructor(e){super(e),this.name="PayValidationError"}},Fe=["GET","POST"];function qe(t){let e;try{e=new URL(t)}catch{throw new S(`Invalid URL: ${t}. Expected a fully-qualified http(s) URL.`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new S(`Unsupported URL scheme "${e.protocol}". Only http and https are allowed.`);return e}function Be(t){let e=(t??"GET").toUpperCase();if(!Fe.includes(e))throw new S(`Unsupported HTTP method "${t}". Supported: ${Fe.join(", ")}.`);return e}function Ge(t){if(t!==void 0){try{JSON.parse(t)}catch(e){throw new S(`--body is not valid JSON: ${e?.message??"parse error"}`)}return t}}function We(t){if(!t||typeof t!="object")throw new S("Merchant returned no payment preview.");let e=t;if(typeof e.amount!="number"||!Number.isFinite(e.amount)||e.amount<=0)throw new S("Could not determine payment amount from merchant.");if(typeof e.merchantName!="string"||e.merchantName.trim().length===0)throw new S("Merchant returned an empty merchant name.");if(e.merchantName.length>200)throw new S(`Merchant name too long (${e.merchantName.length} chars).`);if(typeof e.currency!="string"||e.currency.trim().length===0)throw new S("Merchant returned an empty currency.");if(e.currency.length>10)throw new S(`Currency code too long (${e.currency.length} chars).`);return{amount:e.amount,currency:e.currency,merchantName:e.merchantName}}var p=g(require("fs")),u=g(require("path")),Ye=g(require("os")),m=Ye.homedir(),v=[{id:"claude",displayName:"Claude Code",globalConfigPath:u.join(m,".claude.json"),configKey:"mcpServers",detectPaths:[u.join(m,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:u.join(m,"Library","Application Support","Claude","claude_desktop_config.json"),configKey:"mcpServers",detectPaths:[u.join(m,"Library","Application Support","Claude")],postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:u.join(m,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[u.join(m,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:u.join(m,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[u.join(m,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:u.join(m,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[u.join(m,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:u.join(m,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[u.join(m,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:u.join(m,".vscode","mcp.json"),configKey:"servers",detectPaths:[u.join(m,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:u.join(m,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[u.join(m,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:t=>({source:"custom",...t})}];function ce(t){return v.find(e=>e.id===t)}function j(t){return t.detectPaths.some(e=>{if(e.includes("*")){let n=u.dirname(e),r=u.basename(e).replaceAll("*","");if(!p.existsSync(n))return!1;try{return p.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return p.existsSync(e)})}function Je(){return{command:"node",args:[u.resolve(__dirname,"mcp-server/index.js")]}}function M(t,e="global"){let n=e==="project"?u.join(process.cwd(),".mcp.json"):t.globalConfigPath,r=u.dirname(n);p.existsSync(r)||p.mkdirSync(r,{recursive:!0});let s={};if(p.existsSync(n))try{s=JSON.parse(p.readFileSync(n,"utf-8"))}catch{s={}}s[t.configKey]=s[t.configKey]||{};let o=Je();return s[t.configKey]["visa-cli"]=t.buildEntry?t.buildEntry(o):o,p.writeFileSync(n,JSON.stringify(s,null,2)+`
|
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Qr=Object.create;var kt=Object.defineProperty;var en=Object.getOwnPropertyDescriptor;var tn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var sn=(r,e)=>()=>(r&&(e=r(r=0)),e);var an=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Yt=(r,e)=>{for(var t in e)kt(r,t,{get:e[t],enumerable:!0})},on=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tn(e))!nn.call(r,s)&&s!==t&&kt(r,s,{get:()=>e[s],enumerable:!(n=en(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?Qr(rn(r)):{},on(e||!r||!r.__esModule?kt(t,"default",{value:r,enumerable:!0}):t,r));var Xt={};Yt(Xt,{fetchWithTimeout:()=>St});async function St(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Tt=sn(()=>{"use strict"});var Zr=an((qi,Ra)=>{Ra.exports={name:"@visa/cli",version:"1.0.
|
|
2
|
+
"use strict";var Qr=Object.create;var kt=Object.defineProperty;var en=Object.getOwnPropertyDescriptor;var tn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var sn=(r,e)=>()=>(r&&(e=r(r=0)),e);var an=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Yt=(r,e)=>{for(var t in e)kt(r,t,{get:e[t],enumerable:!0})},on=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tn(e))!nn.call(r,s)&&s!==t&&kt(r,s,{get:()=>e[s],enumerable:!(n=en(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?Qr(rn(r)):{},on(e||!r||!r.__esModule?kt(t,"default",{value:r,enumerable:!0}):t,r));var Xt={};Yt(Xt,{fetchWithTimeout:()=>St});async function St(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Tt=sn(()=>{"use strict"});var Zr=an((qi,Ra)=>{Ra.exports={name:"@visa/cli",version:"1.0.7-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^22.10.0","@typescript-eslint/eslint-plugin":"^8.56.1","@typescript-eslint/parser":"^8.56.1","@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.1","ts-jest":"^29.2.0",typescript:"^5.7.0"},engines:{node:">=18.0.0"},files:["bin/visa-cli.js","dist/","native/visa-keychain.m","README.md","LICENSE"]}});var Yr=require("@modelcontextprotocol/sdk/server/index.js"),Xr=require("@modelcontextprotocol/sdk/server/stdio.js"),Q=require("@modelcontextprotocol/sdk/types.js");Tt();var cn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function et(r,e){let t=Jt(r),n=Jt(e);if(!t||!n)return!1;for(let s=0;s<3;s++)if(t.main[s]!==n.main[s])return t.main[s]>n.main[s];return t.pre&&!n.pre?!1:!t.pre&&n.pre?!0:!t.pre&&!n.pre?!1:un(t.pre,n.pre)>0}function Jt(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(cn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function un(r,e){let t=r.split("."),n=e.split("."),s=Math.max(t.length,n.length);for(let a=0;a<s;a++){if(a>=t.length)return-1;if(a>=n.length)return 1;let i=t[a],o=n[a],c=/^\d+$/.test(i),u=/^\d+$/.test(o);if(c&&u){let p=Number(i)-Number(o);if(p!==0)return p}else{if(c)return-1;if(u)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function tt(){return!!(Qt(process.env.VISA_CLI_NO_UPDATE_CHECK)||Qt(process.env.CI)||process.env.NODE_ENV==="test")}function Qt(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var It="1.0.7-rc.1",rt=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!tt()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&et(n,It)&&(this.lastSignals.updateAvailable={version:n,message:s||`Update available: v${n}. Run: npm install -g @visa/cli && visa-cli setup`})}let t=e.headers.get("X-Feedback-Prompt");if(t)try{this.lastSignals.feedbackPrompt=JSON.parse(t)}catch{}}getClientVersion(){return It}async request(e,t,n,s,a){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let o={Authorization:`Bearer ${i}`};a&&(e==="GET"?o["X-User-Context"]=a.replace(/[\r\n\0]/g," ").slice(0,1e3):n={...n||{},user_context:a}),n&&(o["Content-Type"]="application/json");let c;try{c=await St(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":It},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(p){throw p.name==="AbortError"||p.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let p=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${t}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(u?.error||`Request failed (${c.status}). Try again.`);return u}async pay(e,t){return this.request("POST","/v1/pay",e,void 0,t)}async shortcut(e,t,n,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,t,n,s)}async batch(e,t,n){return this.request("POST","/v1/batch",e,t,n)}async catalogSearch(e,t){let n=new URLSearchParams;e&&n.set("q",e),t&&n.set("category",t);let s=n.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,t){return this.request("POST","/v1/payment-preview",e,void 0,t)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,t){return this.request("POST","/v1/spending-controls",e,void 0,t)}async removeCard(e,t,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,t,void 0,n)}async setDefaultCard(e,t,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,t,void 0,n)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async logout(e,t){return this.request("POST","/v1/logout",e,void 0,t)}async feedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let t=new URLSearchParams;e?.tab&&t.set("tab",e.tab),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let n=t.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(e,t){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:t})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async getFeedback(e,t){let n=new URLSearchParams;e&&n.set("limit",String(e));let s=n.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,t)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var Ct=require("child_process"),ar=require("util"),ir=I(require("crypto")),N=I(require("fs")),or=I(require("os")),Z=I(require("path"));var j=I(require("fs")),Rt=I(require("path")),er=I(require("os")),At=Rt.join(er.homedir(),".visa-mcp"),Ve=Rt.join(At,"mcp-server.log"),ln=5*1024*1024,Et=null;function dn(){j.existsSync(At)||j.mkdirSync(At,{recursive:!0,mode:448})}function pn(){if(!Et){if(dn(),j.existsSync(Ve)&&j.statSync(Ve).size>ln){let e=Ve+".1";j.existsSync(e)&&j.unlinkSync(e),j.renameSync(Ve,e)}Et=j.createWriteStream(Ve,{flags:"a"})}return Et}function nt(r,...e){let t=new Date().toISOString(),n=e.map(a=>typeof a=="string"?a:JSON.stringify(a,null,2)).join(" "),s=`[${t}] [${r}] ${n}
|
|
3
3
|
`;process.stderr.write(s),pn().write(s)}var d={debug:(...r)=>nt("DEBUG",...r),info:(...r)=>nt("INFO",...r),warn:(...r)=>nt("WARN",...r),error:(...r)=>nt("ERROR",...r)};var st=(0,ar.promisify)(Ct.execFile),at=Z.join(or.homedir(),".visa-mcp","bin"),de=Z.join(at,"Visa CLI"),mn=Z.join(__dirname,"..","native"),tr="5",rr=Z.join(at,"visa-keychain.version"),nr=Z.join(at,"visa-keychain.sha256");function sr(r){let e=N.readFileSync(r);return ir.createHash("sha256").update(e).digest("hex")}async function cr(){try{if(N.readFileSync(rr,"utf-8").trim()===tr&&N.existsSync(de)){let n=N.readFileSync(nr,"utf-8").trim();if(sr(de)!==n)d.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),N.unlinkSync(de);else return de}}catch{}let r=Z.join(mn,"visa-keychain.m");if(N.existsSync(r)||(r=Z.resolve(__dirname,"..","..","native","visa-keychain.m")),N.existsSync(r)||(r=Z.resolve(__dirname,"..","native","visa-keychain.m")),!N.existsSync(r))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");N.mkdirSync(at,{recursive:!0,mode:448});try{await st("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",de,r],{timeout:3e4})}catch(t){throw t.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):t}let e=sr(de);return N.writeFileSync(nr,e,{mode:384}),N.writeFileSync(rr,tr,{mode:384}),de}async function fn(r){let e=await cr(),t;try{t=(await st(e,r,{timeout:6e4})).stdout}catch(a){t=a.stdout||"";let i=t.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(a.stderr?.trim()||a.message||"Unknown error")}let n=t.trim();if(n.startsWith("OK:"))return n.slice(3);if(n==="OK")return;let s=n.startsWith("ERROR:")?n.slice(6):"Unknown error";throw new Error(s)}var Ot=null;function Nt(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ot!==null?Ot:(Ot=!0,!0)}var ur="visa-cli",lr="attestation-key";async function hn(){try{let{stdout:r}=await st("security",["find-generic-password","-s",ur,"-a",lr,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function dr(r,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let t=await hn();if(!t)throw new Error("Attestation key not found. Run setup to generate a new key.");let n=await cr(),s=["sign",r];return e&&s.push(e),new Promise((a,i)=>{let o=(0,Ct.execFile)(n,s,{timeout:6e4},(c,u)=>{let p=(u||"").trim();if(c){p.startsWith("ERROR:")?i(new Error(p.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):i(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});o.stdin.write(t),o.stdin.end()})}async function pr(){try{await st("security",["delete-generic-password","-s",ur,"-a",lr],{timeout:5e3})}catch{}try{await fn(["delete-key"])}catch{}}var gr=require("child_process"),yr=require("util"),ee=I(require("fs")),_r=I(require("os")),Pt=I(require("path")),ae=(0,yr.promisify)(gr.execFile),$t=Pt.join(_r.homedir(),".visa-mcp"),it=Pt.join($t,"session-token"),ie="visa-cli",ot="session-token",ct="rc-access";async function mr(){try{let{stdout:r}=await ae("security",["find-generic-password","-s",ie,"-a",ot,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function fr(r){try{try{await ae("security",["delete-generic-password","-s",ie,"-a",ot],{timeout:5e3})}catch{}return await ae("security",["add-generic-password","-s",ie,"-a",ot,"-w",r],{timeout:5e3}),!0}catch{return!1}}async function hr(){try{await ae("security",["delete-generic-password","-s",ie,"-a",ot],{timeout:5e3})}catch{}}async function yn(){try{let{stdout:r}=await ae("security",["find-generic-password","-s",ie,"-a",ct,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function _n(r){try{try{await ae("security",["delete-generic-password","-s",ie,"-a",ct],{timeout:5e3})}catch{}await ae("security",["add-generic-password","-s",ie,"-a",ct,"-w",r],{timeout:5e3})}catch{}}async function vn(){try{await ae("security",["delete-generic-password","-s",ie,"-a",ct],{timeout:5e3})}catch{}}function wn(r){ee.mkdirSync($t,{recursive:!0,mode:448}),ee.writeFileSync(it,r,{mode:384})}function bn(){try{return ee.readFileSync(it,"utf-8").trim()||null}catch{return null}}var $=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=await mr();if(e)return e;let t=bn();return t?(await fr(t),t):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;if(await fr(e)){if(await mr()===e){try{ee.unlinkSync(it)}catch{}return}await hr()}if(wn(e),await this.getSessionToken()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${$t} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":yn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await _n(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN!=="true"){await hr();try{ee.unlinkSync(it)}catch{}}}static async clearAll(){await this.deleteSessionToken(),await vn()}};var He=I(require("crypto")),ut=require("child_process"),B=I(require("fs")),lt=I(require("os")),dt=I(require("path")),pt=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",S=new rt(()=>$.getSessionToken()),xn=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],vr=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my recent transactions" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Pay https://example.com/checkout" \u2192 pay','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Fast shortcuts:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image_card (~$0.06)','\u2022 "Make a fast thumbnail: minimalist cat logo" \u2192 generate_image_fast_card (~$0.04)','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video_tempo_card (~$0.30)','\u2022 "Make a song about coding late at night" \u2192 generate_music_tempo_card (~$0.10)','\u2022 "Check the status of my music job" \u2192 check_music_status_tempo_card','\u2022 "What is ETH on Base trading at?" \u2192 query_onchain_prices_card (~$0.02)','\u2022 "Explore stablecoin inflows on Base" \u2192 allium_explorer_card','\u2022 "Open the latest Allium result set" \u2192 allium_explorer_results_card','\u2022 "Show pxlwall campaign insights" \u2192 pxlwall_card',"","Category tools:",...xn.map(r=>`\u2022 "${r.replace(/_/g," ")}" \u2192 ${r}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
4
4
|
`);function U(r){if(!r||typeof r!="string"||process.env.VISA_SUPPRESS_BROWSER==="true")return;let e;try{e=new URL(r)}catch{return}if(e.protocol!=="https:"&&e.protocol!=="http:")return;let t=e.toString(),n=lt.platform();n==="darwin"?(0,ut.execFile)("open",[t]):n==="win32"?(0,ut.execFile)("cmd",["/c","start","",t]):(0,ut.execFile)("xdg-open",[t])}async function A(r,e,t,n){if(!Nt()){d.warn("attestation:unavailable",{context:r});return}d.info("attestation:attempt",{context:r,amount:e,merchant:t});try{let{nonce:s}=await S.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:s,amount:e,merchant:t,context:r})).toString("base64");d.info("touchid:prompt",{context:r,amount:e,merchant:t});let i=await dr(a,n);return d.info("attestation:success",{context:r,amount:e,merchant:t}),{signature:i,nonce:s,amount:e,merchant:t}}catch(s){throw d.error("attestation:failure",{context:r,amount:e,merchant:t,error:s.message}),s}}async function z(r,e,t){let n=await S.paymentPreview({tool:r,url:e},t);if(!n||!n.merchantName||!n.amount||n.amount<=0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(n.amount)||n.amount<0||n.amount>999999)throw new Error(`Invalid payment amount: ${n.amount}. Payment rejected for safety.`);return n}function G(r){if(r.pricingMode==="max-cap"){let e=typeof r.estimatedAmount=="number"&&r.estimatedAmount>0?` (estimated $${r.estimatedAmount.toFixed(2)})`:"";return`pay up to $${r.amount.toFixed(2)} to ${r.merchantName}${e}`}return`pay $${r.amount.toFixed(2)} to ${r.merchantName}`}function br(){return dt.join(lt.homedir(),".visa-mcp","allium-results")}var kn=16*1024,Sn=50*1024*1024,Tn=10;function In(r){return r.replace(/[^A-Za-z0-9_\-]/g,"_").slice(0,128)}function En(r,e){let t=br();B.mkdirSync(t,{recursive:!0});let n=In(r),s=dt.join(t,`${n}.csv`);B.writeFileSync(s,e);let a=Buffer.byteLength(e),i=e.split(`
|
|
5
5
|
`),o=i[0]??"",c=i.slice(1).filter(_=>_.length>0),u=[o,...c.slice(0,Tn)].join(`
|
|
6
|
-
`),p={file_path:s,row_count:c.length,size_bytes:a,columns:o,preview:u,truncated:!0};if(a>Sn){let _=(a/1048576).toFixed(1);d.warn("allium:large_csv_written",{sessionId:r,size_bytes:a,file_path:s}),p.warning=`Wrote ${_} MB to ${s}. Delete ~/.visa-mcp/allium-results/ files you no longer need \u2014 they are never auto-cleaned.`}return p}function An(){let r=br();try{if(!B.existsSync(r))return{file_count:0,size_bytes:0,path:r};let e=B.readdirSync(r),t=0,n=0;for(let s of e)try{let a=B.statSync(dt.join(r,s));a.isFile()&&(t+=a.size,n++)}catch{}return{file_count:n,size_bytes:t,path:r}}catch(e){return d.warn("allium:disk_usage_error",{error:e.message}),{file_count:0,size_bytes:0,path:r}}}async function ze(r){if(process.env.VISA_SUPPRESS_FEED!=="true")try{let e=await $.getSessionToken();if(!e)return;await fetch(`${pt}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({prompt:r.prompt,tool:r.tool,media_url:r.mediaUrl,media_type:r.mediaType,cost:r.cost,transaction_id:r.transactionId,auto:!0,...r.userContext&&{user_context:r.userContext}}),signal:AbortSignal.timeout(5e3)}),d.info("feed:submitted",{tool:r.tool,mediaType:r.mediaType})}catch{}}async function Rn(r,e){if(!r.url||!r.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let t=await z(void 0,r.url,e);d.info("payment:attempt",{tool:"pay",amount:t.amount,merchant:t.merchantName,url:r.url});try{let n=await A(r.url||"pay",t.amount,t.merchantName,G(t)),s=await S.pay({url:r.url||"",merchantName:r.merchantName||"Unknown",description:r.description||"",method:r.method,body:r.body,attestation:n,idempotencyKey:He.randomUUID()},e);return s.success?(d.info("payment:success",{tool:"pay",amount:t.amount,merchant:t.merchantName,rail:s.receipt?.rail}),s.receipt&&rs(s.receipt)):d.warn("payment:declined",{tool:"pay",amount:t.amount,merchant:t.merchantName,message:s.message}),s}catch(n){throw d.error("payment:failure",{tool:"pay",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function On(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_image_card",void 0,e);d.info("payment:attempt",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_image_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_image_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Cn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_image_fast_card",void 0,e);d.info("payment:attempt",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_image_fast_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_image_fast_card",{...r,attestation:n},6e4,e);return d.info("payment:success",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Nn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_video_tempo_card",void 0,e);d.info("payment:attempt",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_video_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_video_tempo_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Pn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_music_tempo_card",void 0,e);d.info("payment:attempt",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_music_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_music_tempo_card",{...r,attestation:n},36e4,e);return d.info("payment:success",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,d.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):d.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function $n(r,e){let t=await z("check_music_status_tempo_card",void 0,e);d.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("check_music_status_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("check_music_status_tempo_card",{...r,attestation:n},void 0,e);return d.info("payment:success",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.urls.forEach(a=>U(a)),s}catch(n){throw d.error("payment:failure",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Mn(r,e){if(!r.chain||!r.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!r.token_address||!r.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let t=await z("query_onchain_prices_card",void 0,e);d.info("payment:attempt",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("query_onchain_prices_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("query_onchain_prices_card",{...r,attestation:n},void 0,e);if(d.info("payment:success",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName}),Array.isArray(s?.data))s.data=s.data.map(a=>{if("mint"in a&&!("address"in a)){let{mint:i,...o}=a;return{address:i,...o}}return a});else if(s&&"mint"in s&&!("address"in s)){let{mint:a,...i}=s;return{address:a,...i}}return s}catch(n){throw d.error("payment:failure",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function jn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a natural language question about blockchain data.");let t=await z("allium_explorer_card",void 0,e);d.info("payment:attempt",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("allium_explorer_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("allium_explorer_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName}),s}catch(n){throw d.error("payment:failure",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Ln(r,e){if(!r.session_id||!r.session_id.trim())throw new Error("A session_id is required. Use the session_id returned from allium_explorer_card.");let t=await z("allium_explorer_results_card",void 0,e);d.info("payment:attempt",{tool:"allium_explorer_results_card",amount:t.amount,pricingMode:t.pricingMode,estimatedAmount:t.estimatedAmount,merchant:t.merchantName});try{let n=await A("allium_explorer_results_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("allium_explorer_results_card",{...r,attestation:n},6e4,e);d.info("payment:success",{tool:"allium_explorer_results_card",amount:t.amount,actualCost:s?.actualCost,merchant:t.merchantName});let a=typeof s?.data?.results=="string"?s.data.results:void 0;if(a&&Buffer.byteLength(a)>kn){let i=En(r.session_id,a),{results:o,...c}=s.data;return{...s,data:{...c,...i}}}return s}catch(n){throw d.error("payment:failure",{tool:"allium_explorer_results_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}var Fe="https://pxlwall.com";async function qn(r){if([r.shape,r.text,r.pixels].filter(Boolean).length>1)throw new Error("Provide only one of: shape, text, or pixels. Cannot combine modes.");let t,n,s=r.position||"cheapest";if(typeof s=="string"&&s.startsWith("{"))try{s=JSON.parse(s)}catch{}if(r.shape)t=`${Fe}/api/agent/draw-shape`,n={shape:r.shape,color:r.color||"#ffffff",owner:r.owner,position:s},r.shape==="circle"?n.radius=r.size||10:r.shape==="rectangle"?(n.width=r.width||20,n.height=r.height||10):n.size=r.size||10;else if(r.text)t=`${Fe}/api/agent/draw-text`,n={text:r.text,color:r.color||"#ffffff",owner:r.owner,position:s};else if(r.pixels){if(r.pixels.length<100)throw new Error(`Minimum 100 pixels per purchase. You requested ${r.pixels.length}.`);for(let i of r.pixels)if(i.x<0||i.x>499||i.y<0||i.y>499)throw new Error(`Pixel (${i.x},${i.y}) is out of bounds. Grid is 500x500 (coordinates 0-499).`);t=`${Fe}/api/create-purchase-spec`,n={pixels:r.pixels,color:r.color||"#ffffff",owner:r.owner},r.colors&&(n.colors=r.colors)}else throw new Error("Provide one of: shape, text, or pixels.");let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`pxlwall spec creation failed (${a.status}): ${i}`)}return a.json()}async function Un(r,e){let t=await qn(r),n=t.pixels?.length??r.pixels?.length??0,s="pxlwall";d.info("payment:attempt",{tool:"pxlwall_card",amount:t.totalUSD,pixelCount:n,merchant:s});try{let a=await A("pxlwall_card",t.totalUSD,s,`pay $${t.totalUSD.toFixed(2)} to ${s} for ${n} pixels`),i=await S.shortcut("pxlwall_card",{specId:t.specId,attestation:a},6e4,e);return d.info("payment:success",{tool:"pxlwall_card",merchant:s}),U(Fe),i.urls?.length&&i.urls.forEach(o=>U(o)),{...i,specId:t.specId,pixelCount:n,totalUSD:t.totalUSD,canvasUrl:Fe}}catch(a){throw d.error("payment:failure",{tool:"pxlwall_card",merchant:s,error:a.message}),a}}var Dn=["generate_music_tempo_card"],Vn=36e4,Fn=12e4,Hn=2e3;async function zn(r,e){let t=r.requests?.length||r.count||0;if(t===0)throw new Error("Batch requires at least one item. Please specify what to generate.");let n=await z(r.tool,void 0,e),s=n.amount*t;d.info("payment:attempt",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName});try{let a=`pay $${s.toFixed(2)} to ${n.merchantName} (${t} items, $${n.amount.toFixed(2)} each)`,i=await A(`batch:${r.tool}`,s,n.merchantName,a),o=r.requests||(r.count&&r.params?Array.from({length:r.count},()=>({...r.params})):[]),c=Dn.includes(r.tool)?Vn:Fn+t*Hn,u=await S.batch({tool:r.tool,requests:o,attestation:i,idempotencyKey:He.randomUUID()},c,e);return d.info("payment:success",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName}),u.results&&u.results.forEach(p=>{p.urls&&p.urls.forEach(_=>U(_))}),u}catch(a){throw d.error("payment:failure",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName,error:a.message}),a}}async function Wn(r){let e=await S.getStatus(r);typeof e?.dailyRemaining=="number"&&(e.dailyRemaining=Math.round(e.dailyRemaining*100)/100);let t=An();return t.file_count>0&&(e.alliumResultsOnDisk=t),e}async function Zn(r){let t=(await S.getStatus(r)).cards||[];return t.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:{cards:t}}async function Bn(r){let e=await S.getTransactions(r);return Array.isArray(e?.transactions)&&(e.transactions=e.transactions.filter(t=>!(t.tool_name==null||t.amount===0&&t.status==="failed"))),e}async function Gn(r,e){return await S.feedback(r.message,r.transaction_id,e)}async function Kn(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to update spending controls."};d.info("spending_controls:update",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit});try{let t=await A("spending-controls",0,"","update spending controls"),n=await S.updateSpendingControls({maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit,confirm:!0,attestation:t},e);return d.info("spending_controls:success",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit}),n}catch(t){throw d.error("spending_controls:failure",{error:t.message}),t}}var wr=3e4,Yn=3e5;async function xr(r,e){let t=He.randomBytes(16).toString("hex"),n=`${r}${r.includes("?")?"&":"?"}state=${t}`;U(n);let s=Date.now()+Yn;for(;Date.now()<s;)try{let a=await fetch(`${pt}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:t,timeout:wr,...e&&{user_context:e}}),signal:AbortSignal.timeout(wr+5e3)});if(!a.ok)continue;let i=await a.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(i.sessionToken){await $.saveSessionToken(i.sessionToken);let c=i.user||"",u=i.last4||"****";return d.info("auth:login_complete",{user:c,last4:u}),{success:!0,message:`Signed in as ${c}. Card ending in ${u} added.${vr}`}}let o=i.last4||"****";return d.info("auth:card_added",{last4:o}),{success:!0,message:`Card ending in ${o} enrolled.${vr}`}}}catch{}return{success:!1,message:"Login timed out. Please try again."}}async function Xn(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};d.info("cards:remove_attempt",{cardId:t});let n=`remove-card:${t}`,s=`remove enrolled card #${t}`,a=await A(n,0,"",s);try{let i=await S.removeCard(t,{attestation:a},e);return d.info("cards:remove_success",{cardId:t,promotedId:i?.promotedId??null}),i}catch(i){throw d.error("cards:remove_failure",{cardId:t,error:i.message}),i}}async function Jn(r,e){let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};d.info("cards:set_default_attempt",{cardId:t});let n=`set-default-card:${t}`,s=`set card #${t} as default`,a=await A(n,0,"",s);try{let i=await S.setDefaultCard(t,{attestation:a},e);return d.info("cards:set_default_success",{cardId:t}),i}catch(i){throw d.error("cards:set_default_failure",{cardId:t,error:i.message}),i}}async function Qn(r){return d.info("auth:login_attempt"),xr(`${pt}/login`,r)}async function es(r){return d.info("auth:add_card_attempt"),await $.getSessionToken()?xr(`${pt}/enroll`,r):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function ts(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};d.info("reset:attempt");let t=await A("reset",0,"","reset device and remove all credentials");try{await S.logout({attestation:t},e)}catch{}if(await $.clearAll(),Nt())try{await pr()}catch{}return d.info("reset:success"),{success:!0,message:"Device reset. All credentials, cards, and keys have been removed. Use the login tool to re-enroll."}}function rs(r){let e=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let t of e){let n=r[t];n&&typeof n=="string"&&n.startsWith("http")&&U(n)}Array.isArray(r.urls)&&r.urls.forEach(t=>{t&&typeof t=="string"&&t.startsWith("http")&&U(t)})}async function ns(r){if(!r.query&&!r.category)throw new Error("Provide a query (what you want to do) or category (image, video, audio, 3d, llm) to search the tool catalog.");d.info("catalog:discover",{query:r.query,category:r.category});try{let t=(await S.catalogSearch(r.query,r.category)).tools||[];if(t.length===0)return{content:[{type:"text",text:`No tools found for "${r.query||r.category}". Try a different search term.`}]};let n=t.map((s,a)=>`${a+1}. **${s.name}** (${s.id})
|
|
6
|
+
`),p={file_path:s,row_count:c.length,size_bytes:a,columns:o,preview:u,truncated:!0};if(a>Sn){let _=(a/1048576).toFixed(1);d.warn("allium:large_csv_written",{sessionId:r,size_bytes:a,file_path:s}),p.warning=`Wrote ${_} MB to ${s}. Delete ~/.visa-mcp/allium-results/ files you no longer need \u2014 they are never auto-cleaned.`}return p}function An(){let r=br();try{if(!B.existsSync(r))return{file_count:0,size_bytes:0,path:r};let e=B.readdirSync(r),t=0,n=0;for(let s of e)try{let a=B.statSync(dt.join(r,s));a.isFile()&&(t+=a.size,n++)}catch{}return{file_count:n,size_bytes:t,path:r}}catch(e){return d.warn("allium:disk_usage_error",{error:e.message}),{file_count:0,size_bytes:0,path:r}}}async function ze(r){if(process.env.VISA_SUPPRESS_FEED!=="true")try{let e=await $.getSessionToken();if(!e)return;await fetch(`${pt}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({prompt:r.prompt,tool:r.tool,media_url:r.mediaUrl,media_type:r.mediaType,cost:r.cost,transaction_id:r.transactionId,auto:!0,...r.userContext&&{user_context:r.userContext}}),signal:AbortSignal.timeout(5e3)}),d.info("feed:submitted",{tool:r.tool,mediaType:r.mediaType})}catch{}}async function Rn(r,e){if(!r.url||!r.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let t=await z(void 0,r.url,e);d.info("payment:attempt",{tool:"pay",amount:t.amount,merchant:t.merchantName,url:r.url});try{let n=await A(r.url||"pay",t.amount,t.merchantName,G(t)),s=await S.pay({url:r.url||"",merchantName:r.merchantName||"Unknown",description:r.description||"",method:r.method,body:r.body,attestation:n,idempotencyKey:He.randomUUID()},e);return s.success?(d.info("payment:success",{tool:"pay",amount:t.amount,merchant:t.merchantName,rail:s.receipt?.rail}),s.receipt&&rs(s.receipt)):d.warn("payment:declined",{tool:"pay",amount:t.amount,merchant:t.merchantName,message:s.message}),s}catch(n){throw d.error("payment:failure",{tool:"pay",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function On(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_image_card",void 0,e);d.info("payment:attempt",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_image_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_image_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Cn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_image_fast_card",void 0,e);d.info("payment:attempt",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_image_fast_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_image_fast_card",{...r,attestation:n},6e4,e);return d.info("payment:success",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Nn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_video_tempo_card",void 0,e);d.info("payment:attempt",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_video_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_video_tempo_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):d.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Pn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await z("generate_music_tempo_card",void 0,e);d.info("payment:attempt",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("generate_music_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("generate_music_tempo_card",{...r,attestation:n},36e4,e);return d.info("payment:success",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(a=>U(a)),ze({prompt:r.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,d.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):d.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s}catch(n){throw d.error("payment:failure",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function $n(r,e){let t=await z("check_music_status_tempo_card",void 0,e);d.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("check_music_status_tempo_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("check_music_status_tempo_card",{...r,attestation:n},void 0,e);return d.info("payment:success",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.urls.forEach(a=>U(a)),s}catch(n){throw d.error("payment:failure",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Mn(r,e){if(!r.chain||!r.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!r.token_address||!r.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let t=await z("query_onchain_prices_card",void 0,e);d.info("payment:attempt",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("query_onchain_prices_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("query_onchain_prices_card",{...r,attestation:n},void 0,e);if(d.info("payment:success",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName}),Array.isArray(s?.data))s.data=s.data.map(a=>{if("mint"in a&&!("address"in a)){let{mint:i,...o}=a;return{address:i,...o}}return a});else if(s&&"mint"in s&&!("address"in s)){let{mint:a,...i}=s;return{address:a,...i}}return s}catch(n){throw d.error("payment:failure",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function jn(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a natural language question about blockchain data.");let t=await z("allium_explorer_card",void 0,e);d.info("payment:attempt",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName});try{let n=await A("allium_explorer_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("allium_explorer_card",{...r,attestation:n},12e4,e);return d.info("payment:success",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName}),s}catch(n){throw d.error("payment:failure",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function Ln(r,e){if(!r.session_id||!r.session_id.trim())throw new Error("A session_id is required. Use the session_id returned from allium_explorer_card.");let t=await z("allium_explorer_results_card",void 0,e);d.info("payment:attempt",{tool:"allium_explorer_results_card",amount:t.amount,pricingMode:t.pricingMode,estimatedAmount:t.estimatedAmount,merchant:t.merchantName});try{let n=await A("allium_explorer_results_card",t.amount,t.merchantName,G(t)),s=await S.shortcut("allium_explorer_results_card",{...r,attestation:n},6e4,e);d.info("payment:success",{tool:"allium_explorer_results_card",amount:t.amount,actualCost:s?.actualCost,merchant:t.merchantName});let a=typeof s?.data?.results=="string"?s.data.results:void 0;if(a&&Buffer.byteLength(a)>kn){let i=En(r.session_id,a),{results:o,...c}=s.data;return{...s,data:{...c,...i}}}return s}catch(n){throw d.error("payment:failure",{tool:"allium_explorer_results_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}var Fe="https://pxlwall.com";async function qn(r){if([r.shape,r.text,r.pixels].filter(Boolean).length>1)throw new Error("Provide only one of: shape, text, or pixels. Cannot combine modes.");let t,n,s=r.position||"cheapest";if(typeof s=="string"&&s.startsWith("{"))try{s=JSON.parse(s)}catch{}if(r.shape)t=`${Fe}/api/agent/draw-shape`,n={shape:r.shape,color:r.color||"#ffffff",owner:r.owner,position:s},r.shape==="circle"?n.radius=r.size||10:r.shape==="rectangle"?(n.width=r.width||20,n.height=r.height||10):n.size=r.size||10;else if(r.text)t=`${Fe}/api/agent/draw-text`,n={text:r.text,color:r.color||"#ffffff",owner:r.owner,position:s};else if(r.pixels){if(r.pixels.length<100)throw new Error(`Minimum 100 pixels per purchase. You requested ${r.pixels.length}.`);for(let i of r.pixels)if(i.x<0||i.x>499||i.y<0||i.y>499)throw new Error(`Pixel (${i.x},${i.y}) is out of bounds. Grid is 500x500 (coordinates 0-499).`);t=`${Fe}/api/create-purchase-spec`,n={pixels:r.pixels,color:r.color||"#ffffff",owner:r.owner},r.colors&&(n.colors=r.colors)}else throw new Error("Provide one of: shape, text, or pixels.");let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`pxlwall spec creation failed (${a.status}): ${i}`)}return a.json()}async function Un(r,e){let t=await qn(r),n=t.pixels?.length??r.pixels?.length??0,s="pxlwall";d.info("payment:attempt",{tool:"pxlwall_card",amount:t.totalUSD,pixelCount:n,merchant:s});try{let a=await A("pxlwall_card",t.totalUSD,s,`pay $${t.totalUSD.toFixed(2)} to ${s} for ${n} pixels`),i=await S.shortcut("pxlwall_card",{specId:t.specId,attestation:a},6e4,e);return d.info("payment:success",{tool:"pxlwall_card",merchant:s}),U(Fe),i.urls?.length&&i.urls.forEach(o=>U(o)),{...i,specId:t.specId,pixelCount:n,totalUSD:t.totalUSD,canvasUrl:Fe}}catch(a){throw d.error("payment:failure",{tool:"pxlwall_card",merchant:s,error:a.message}),a}}var Dn=["generate_music_tempo_card"],Vn=36e4,Fn=12e4,Hn=2e3;async function zn(r,e){let t=r.requests?.length||r.count||0;if(t===0)throw new Error("Batch requires at least one item. Please specify what to generate.");let n=await z(r.tool,void 0,e),s=n.amount*t;d.info("payment:attempt",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName});try{let a=`pay $${s.toFixed(2)} to ${n.merchantName} (${t} items, $${n.amount.toFixed(2)} each)`,i=await A(`batch:${r.tool}`,s,n.merchantName,a),o=r.requests||(r.count&&r.params?Array.from({length:r.count},()=>({...r.params})):[]),c=Dn.includes(r.tool)?Vn:Fn+t*Hn,u=await S.batch({tool:r.tool,requests:o,attestation:i,idempotencyKey:He.randomUUID()},c,e);return d.info("payment:success",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName}),u.results&&u.results.forEach(p=>{p.urls&&p.urls.forEach(_=>U(_))}),u}catch(a){throw d.error("payment:failure",{tool:"batch",batchTool:r.tool,count:t,totalAmount:s,merchant:n.merchantName,error:a.message}),a}}async function Wn(r){let e=await S.getStatus(r);typeof e?.dailyRemaining=="number"&&(e.dailyRemaining=Math.round(e.dailyRemaining*100)/100);let t=An();return t.file_count>0&&(e.alliumResultsOnDisk=t),e}async function Zn(r){let t=(await S.getStatus(r)).cards||[];return t.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:t.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card ids are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:t}}async function Bn(r){let e=await S.getTransactions(r);return Array.isArray(e?.transactions)&&(e.transactions=e.transactions.filter(t=>!(t.tool_name==null||t.amount===0&&t.status==="failed"))),e}async function Gn(r,e){return await S.feedback(r.message,r.transaction_id,e)}async function Kn(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to update spending controls."};d.info("spending_controls:update",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit});try{let t=await A("spending-controls",0,"","update spending controls"),n=await S.updateSpendingControls({maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit,confirm:!0,attestation:t},e);return d.info("spending_controls:success",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit}),n}catch(t){throw d.error("spending_controls:failure",{error:t.message}),t}}var wr=3e4,Yn=3e5;async function xr(r,e){let t=He.randomBytes(16).toString("hex"),n=`${r}${r.includes("?")?"&":"?"}state=${t}`;U(n);let s=Date.now()+Yn;for(;Date.now()<s;)try{let a=await fetch(`${pt}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:t,timeout:wr,...e&&{user_context:e}}),signal:AbortSignal.timeout(wr+5e3)});if(!a.ok)continue;let i=await a.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(i.sessionToken){await $.saveSessionToken(i.sessionToken);let c=i.user||"",u=i.last4||"****";return d.info("auth:login_complete",{user:c,last4:u}),{success:!0,message:`Signed in as ${c}. Card ending in ${u} added.${vr}`}}let o=i.last4||"****";return d.info("auth:card_added",{last4:o}),{success:!0,message:`Card ending in ${o} enrolled.${vr}`}}}catch{}return{success:!1,message:"Login timed out. Please try again."}}async function Xn(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};d.info("cards:remove_attempt",{cardId:t});let n=`remove-card:${t}`,s=`remove enrolled card #${t}`,a=await A(n,0,"",s);try{let i=await S.removeCard(t,{attestation:a},e);return d.info("cards:remove_success",{cardId:t,promotedId:i?.promotedId??null}),i}catch(i){throw d.error("cards:remove_failure",{cardId:t,error:i.message}),i}}async function Jn(r,e){let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};d.info("cards:set_default_attempt",{cardId:t});let n=`set-default-card:${t}`,s=`set card #${t} as default`,a=await A(n,0,"",s);try{let i=await S.setDefaultCard(t,{attestation:a},e);return d.info("cards:set_default_success",{cardId:t}),i}catch(i){throw d.error("cards:set_default_failure",{cardId:t,error:i.message}),i}}async function Qn(r){return d.info("auth:login_attempt"),xr(`${pt}/login`,r)}async function es(r){return d.info("auth:add_card_attempt"),await $.getSessionToken()?xr(`${pt}/enroll`,r):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function ts(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};d.info("reset:attempt");let t=await A("reset",0,"","reset device and remove all credentials");try{await S.logout({attestation:t},e)}catch{}if(await $.clearAll(),Nt())try{await pr()}catch{}return d.info("reset:success"),{success:!0,message:"Device reset. All credentials, cards, and keys have been removed. Use the login tool to re-enroll."}}function rs(r){let e=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let t of e){let n=r[t];n&&typeof n=="string"&&n.startsWith("http")&&U(n)}Array.isArray(r.urls)&&r.urls.forEach(t=>{t&&typeof t=="string"&&t.startsWith("http")&&U(t)})}async function ns(r){if(!r.query&&!r.category)throw new Error("Provide a query (what you want to do) or category (image, video, audio, 3d, llm) to search the tool catalog.");d.info("catalog:discover",{query:r.query,category:r.category});try{let t=(await S.catalogSearch(r.query,r.category)).tools||[];if(t.length===0)return{content:[{type:"text",text:`No tools found for "${r.query||r.category}". Try a different search term.`}]};let n=t.map((s,a)=>`${a+1}. **${s.name}** (${s.id})
|
|
7
7
|
${s.description}
|
|
8
8
|
Provider: ${s.provider} | Category: ${s.category} | Price: $${(s.priceCents/100).toFixed(2)}
|
|
9
9
|
Params: ${Object.keys(s.inputSchema?.properties||s.inputSchema||{}).join(", ")||"none"}`).join(`
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
${n}
|
|
14
14
|
|
|
15
15
|
Use execute_tool with the tool id and required params to run any of these.`}],_tools:t}}catch(e){throw d.error("catalog:discover:error",{error:e.message}),new Error(`Failed to search tool catalog: ${e.message}`)}}async function ss(r,e){let{tool_id:t,params:n,...s}=r,a=n||s;if(!t)throw new Error("tool_id is required. Use discover_tools first to find available tools.");d.info("catalog:execute",{tool:t});let i=await z(t,void 0,e);d.info("payment:attempt",{tool:t,amount:i.amount,merchant:i.merchantName});try{let o=await A(t,i.amount,i.merchantName,G(i)),c=await S.shortcut(t,{...a,attestation:o},12e4,e);if(d.info("payment:success",{tool:t,amount:i.amount,merchant:i.merchantName}),c.urls?.length){c.urls.forEach(p=>U(p));let u=c.mediaType||(c.urls[0]?.match(/\.(mp4|webm|mov)/)?"video":"image");ze({prompt:a.prompt||`${t} execution`,tool:t,mediaUrl:c.urls[0],mediaType:u,cost:c.amount??i.amount,transactionId:c.transactionId,userContext:e})}return c}catch(o){throw d.error("payment:failure",{tool:t,amount:i.amount,merchant:i.merchantName,error:o.message}),o}}var E=class{static async getStatus(e){return Wn(e)}static async pay(e,t){return Rn(e,t)}static async getCards(e){return Zn(e)}static async transactionHistory(e){return Bn(e)}static async feedback(e,t){return Gn(e,t)}static async updateSpendingControls(e,t){return Kn(e,t)}static async reset(e,t){return ts(e,t)}static async login(e){return Qn(e)}static async addCard(e){return es(e)}static async removeCard(e,t){return Xn(e,t)}static async setDefaultCard(e,t){return Jn(e,t)}static async batch(e,t){return zn(e,t)}static async discoverTools(e){return ns(e)}static async executeTool(e,t){return ss(e,t)}static async shortcut(e,t,n){switch(e){case"generate_image_card":return On(t,n);case"generate_image_fast_card":return Cn(t,n);case"generate_video_tempo_card":return Nn(t,n);case"generate_music_tempo_card":return Pn(t,n);case"check_music_status_tempo_card":return $n(t,n);case"query_onchain_prices_card":return Mn(t,n);case"allium_explorer_card":return jn(t,n);case"allium_explorer_results_card":return Ln(t,n);case"pxlwall_card":return Un(t,n);default:{d.info("payment:attempt",{tool:e});try{let s=await A(e,0,""),a=await S.shortcut(e,{...t,attestation:s},void 0,n);return d.info("payment:success",{tool:e}),a.urls?.length&&a.urls.forEach(i=>U(i)),a}catch(s){throw d.error("payment:failure",{tool:e,error:s.message}),s}}}}static async submitFeedback(e,t,n){d.info("feedback:submit",{length:e.length});try{let s=await S.submitFeedback(e,t,n);return d.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw d.error("feedback:error",{error:a}),s}}static async getFeedback(e,t){d.info("feedback:list",{limit:e||20});try{let n=await S.getFeedback(e,t);return d.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let s=n instanceof Error?n.message:"Unknown error";throw d.error("feedback:error",{error:s}),n}}};var mt={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",priceCents:4,notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",priceCents:1,notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",priceCents:6,notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",priceCents:8,notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",priceCents:5,notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",priceCents:15,notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",priceCents:10,notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",priceCents:20,notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",priceCents:10,notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech or sound effects.",tiers:{tts:{toolId:"fal-metavoice",priceCents:3,notes:"MetaVoice \u2014 high-quality TTS from text"},sfx:{toolId:"fal-stable-audio",priceCents:4,notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:'Pick "tts" for spoken words, "sfx" for music-beds/effects/ambient.',inputProperties:{prompt:{type:"string",description:"Text to speak (tts) or description of sound (sfx)."}},required:["prompt"]},generate_3d:{intro:"Generate a 3D model from a text description.",tiers:{trellis:{toolId:"fal-trellis-3d",priceCents:8,notes:"Trellis \u2014 fast text-to-3D, returns a GLB mesh URL"}},guidance:"Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{prompt:{type:"string",description:"Description of the 3D object."}},required:["prompt"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",priceCents:3,notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",priceCents:2,notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered \u2014 prices below are per 1M input/output tokens. Typical 500-in/500-out prompts cost 1\u20139\xA2 depending on model.",tiers:{fast:{toolId:"or-gpt-4o-mini",priceCents:1,notes:"GPT-4o Mini \u2014 $0.15/M in \xB7 $0.60/M out. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",priceCents:9,notes:"Claude 3.5 Sonnet \u2014 $3.00/M in \xB7 $15.00/M out. Strong reasoning, long-context. ~20x pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",priceCents:2,notes:"DeepSeek R1 \u2014 $0.55/M in \xB7 $2.19/M out. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",priceCents:1,notes:"Perplexity Sonar \u2014 $1.00/M in \xB7 $1.00/M out. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",priceCents:1,notes:"Llama 3.3 70B \u2014 $0.30/M in \xB7 $0.40/M out. Open-source large model."},coding:{toolId:"or-deepseek-chat",priceCents:1,notes:"DeepSeek Chat V3 \u2014 $0.30/M in \xB7 $0.88/M out. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis \u2014 WARN user it's ~$0.09/call), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function We(){return process.env.VISA_SPECIFIC_TOOLS!=="false"}function Ze(){return process.env.VISA_META_TOOLS!=="false"}function Be(){return process.env.VISA_DISCOVER_TOOLS!=="false"}function kr(r){let e=mt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=[e.intro,"","Tiers:"];for(let[n,s]of Object.entries(e.tiers)){let a=`$${(s.priceCents/100).toFixed(2)}`;t.push(` - ${n.padEnd(15)} ${a.padStart(6)} ${s.notes}`)}return t.push("",e.guidance),t.join(`
|
|
16
|
-
`)}function Sr(r){let e=mt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=Object.keys(e.tiers);return{type:"object",properties:{tier:{type:"string",enum:t,default:t[0],description:`Quality/style tier. Default: ${t[0]}.`},...e.inputProperties},required:e.required??[]}}async function Tr(r,e,t){let n=mt[r];if(!n)throw new Error(`Unknown meta-tool: ${r}`);let s=Object.keys(n.tiers),a=s[0],i=e.tier||a,o=n.tiers[i];if(!o)throw new Error(`Unknown tier '${i}' for ${r}. Valid tiers: ${s.join(", ")}`);let{tier:c,...u}=e;return E.executeTool({tool_id:o.toolId,...u},t)}var Ce=Object.keys(mt);var Mt=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card","pxlwall_card"]),jt=new Set(["discover_tools","execute_tool"]),as=new Set(Ce);function Ir(r){return Mt.has(r)&&!We()?"VISA_SPECIFIC_TOOLS":jt.has(r)&&!Be()?"VISA_DISCOVER_TOOLS":as.has(r)&&!Ze()?"VISA_META_TOOLS":null}var ft=I(require("fs")),Er=I(require("path")),Ar=I(require("os"));var Lt=Er.join(Ar.homedir(),".visa-mcp"),Ge=class{static ensureConfigDir(){ft.existsSync(Lt)||ft.mkdirSync(Lt,{recursive:!0,mode:448})}static getConfigDir(){return Lt}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let e=new Set;for(let[t,n]of Object.entries(this.TOOL_STATES))n||e.add(t);return e}static isToolDisabled(e){return this.TOOL_STATES[e]===!1}};var qt=["pay","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card"],is={generate_image_card:"image generation",generate_image_fast_card:"fast image generation",generate_music_tempo_card:"music generation",generate_video_tempo_card:"video generation",query_onchain_prices_card:"onchain price queries",allium_explorer_card:"blockchain data exploration",allium_explorer_results_card:"blockchain data results",pay:"payments"};function os(r){return is[r]||r}var pe=null;async function Rr(r){if(pe!==null)return pe;try{let{transactions:e}=await r.getTransactions();pe={};for(let t of e)t.status==="completed"&&(pe[t.tool_name]=(pe[t.tool_name]||0)+1)}catch{d.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),pe={}}return pe}function Or(r,e,t){return qt.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${os(r)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:t}}:e%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:t}}:{}:{}}var k={};Yt(k,{BRAND:()=>Ps,DIRTY:()=>me,EMPTY_PATH:()=>ds,INVALID:()=>g,NEVER:()=>ya,OK:()=>P,ParseStatus:()=>R,Schema:()=>w,ZodAny:()=>ue,ZodArray:()=>se,ZodBigInt:()=>he,ZodBoolean:()=>ge,ZodBranded:()=>Ye,ZodCatch:()=>Ee,ZodDate:()=>ye,ZodDefault:()=>Ie,ZodDiscriminatedUnion:()=>yt,ZodEffects:()=>F,ZodEnum:()=>Se,ZodError:()=>L,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>vt,ZodIntersection:()=>be,ZodIssueCode:()=>l,ZodLazy:()=>xe,ZodLiteral:()=>ke,ZodMap:()=>Le,ZodNaN:()=>Ue,ZodNativeEnum:()=>Te,ZodNever:()=>W,ZodNull:()=>ve,ZodNullable:()=>X,ZodNumber:()=>fe,ZodObject:()=>q,ZodOptional:()=>D,ZodParsedType:()=>f,ZodPipeline:()=>Xe,ZodPromise:()=>le,ZodReadonly:()=>Ae,ZodRecord:()=>_t,ZodSchema:()=>w,ZodSet:()=>qe,ZodString:()=>ce,ZodSymbol:()=>Me,ZodTransformer:()=>F,ZodTuple:()=>Y,ZodType:()=>w,ZodUndefined:()=>_e,ZodUnion:()=>we,ZodUnknown:()=>ne,ZodVoid:()=>je,addIssueToContext:()=>m,any:()=>Fs,array:()=>Zs,bigint:()=>Ls,boolean:()=>Vr,coerce:()=>ga,custom:()=>qr,date:()=>qs,datetimeRegex:()=>jr,defaultErrorMap:()=>te,discriminatedUnion:()=>Ys,effect:()=>ca,enum:()=>aa,function:()=>ra,getErrorMap:()=>Ne,getParsedType:()=>K,instanceof:()=>Ms,intersection:()=>Xs,isAborted:()=>ht,isAsync:()=>Pe,isDirty:()=>gt,isValid:()=>oe,late:()=>$s,lazy:()=>na,literal:()=>sa,makeIssue:()=>Ke,map:()=>ea,nan:()=>js,nativeEnum:()=>ia,never:()=>zs,null:()=>Vs,nullable:()=>la,number:()=>Dr,object:()=>Bs,objectUtil:()=>Ut,oboolean:()=>ha,onumber:()=>fa,optional:()=>ua,ostring:()=>ma,pipeline:()=>pa,preprocess:()=>da,promise:()=>oa,quotelessJson:()=>cs,record:()=>Qs,set:()=>ta,setErrorMap:()=>ls,strictObject:()=>Gs,string:()=>Ur,symbol:()=>Us,transformer:()=>ca,tuple:()=>Js,undefined:()=>Ds,union:()=>Ks,unknown:()=>Hs,util:()=>b,void:()=>Ws});var b;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var Ut;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ut||(Ut={}));var f=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var l=b.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"]),cs=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),L=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};L.create=r=>new L(r);var us=(r,e)=>{let t;switch(r.code){case l.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,b.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(r.options)}, received '${r.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:b.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case l.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case l.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(r)}return{message:t}},te=us;var Cr=te;function ls(r){Cr=r}function Ne(){return Cr}var Ke=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},ds=[];function m(r,e){let t=Ne(),n=Ke({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===te?void 0:te].filter(s=>!!s)});r.common.issues.push(n)}var R=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),me=r=>({status:"dirty",value:r}),P=r=>({status:"valid",value:r}),ht=r=>r.status==="aborted",gt=r=>r.status==="dirty",oe=r=>r.status==="valid",Pe=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var V=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Nr=(r,e)=>{if(oe(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new L(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var w=class{get description(){return this._def.description}_getType(e){return K(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Nr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return oe(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>oe(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Pe(s)?s:Promise.resolve(s));return Nr(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:l.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new F({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return D.create(this,this._def)}nullable(){return X.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return le.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new F({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ie({...v(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Ye({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ee({...v(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xe.create(this,e)}readonly(){return Ae.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ps=/^c[^\s-]{8,}$/i,ms=/^[0-9a-z]+$/,fs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hs=/^[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,gs=/^[a-z0-9_-]{21}$/i,ys=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_s=/^[-+]?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)?)??$/,vs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ws="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dt,bs=/^(?:(?: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])$/,xs=/^(?:(?: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])$/,ks=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ss=/^(([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])$/,Ts=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Is=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$r="((\\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])))",Es=new RegExp(`^${$r}$`);function Mr(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function As(r){return new RegExp(`^${Mr(r)}$`)}function jr(r){let e=`${$r}T${Mr(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Rs(r,e){return!!((e==="v4"||!e)&&bs.test(r)||(e==="v6"||!e)&&ks.test(r))}function Os(r,e){if(!ys.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Cs(r,e){return!!((e==="v4"||!e)&&xs.test(r)||(e==="v6"||!e)&&Ss.test(r))}var ce=class r extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new R,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&m(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")vs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Dt||(Dt=new RegExp(ws,"u")),Dt.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")hs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")gs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")ps.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")ms.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")fs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:l.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:l.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?jr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Es.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?As(a).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?_s.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Rs(e.data,a.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Os(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Cs(e.data,a.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Ts.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Is.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:l.invalid_string,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:l.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};ce.create=r=>new ce({checks:[],typeName:y.ZodString,coerce:r?.coerce??!1,...v(r)});function Ns(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var fe=class r extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new R;for(let a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Ns(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_finite,message:a.message}),s.dirty()):b.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};fe.create=r=>new fe({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...v(r)});var he=class r extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new R;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):b.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};he.create=r=>new he({checks:[],typeName:y.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var ge=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.boolean,received:n.parsedType}),g}return P(e.data)}};ge.create=r=>new ge({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var ye=class r extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_date}),g}let n=new R,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):b.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};ye.create=r=>new ye({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...v(r)});var Me=class extends w{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.symbol,received:n.parsedType}),g}return P(e.data)}};Me.create=r=>new Me({typeName:y.ZodSymbol,...v(r)});var _e=class extends w{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.undefined,received:n.parsedType}),g}return P(e.data)}};_e.create=r=>new _e({typeName:y.ZodUndefined,...v(r)});var ve=class extends w{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.null,received:n.parsedType}),g}return P(e.data)}};ve.create=r=>new ve({typeName:y.ZodNull,...v(r)});var ue=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return P(e.data)}};ue.create=r=>new ue({typeName:y.ZodAny,...v(r)});var ne=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return P(e.data)}};ne.create=r=>new ne({typeName:y.ZodUnknown,...v(r)});var W=class extends w{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:f.never,received:t.parsedType}),g}};W.create=r=>new W({typeName:y.ZodNever,...v(r)});var je=class extends w{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.void,received:n.parsedType}),g}return P(e.data)}};je.create=r=>new je({typeName:y.ZodVoid,...v(r)});var se=class r extends w{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return m(t,{code:l.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(m(t,{code:i?l.too_big:l.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(m(t,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(m(t,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new V(t,i,t.path,o)))).then(i=>R.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new V(t,i,t.path,o)));return R.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function $e(r){if(r instanceof q){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=D.create($e(n))}return new q({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:$e(r.element)}):r instanceof D?D.create($e(r.unwrap())):r instanceof X?X.create($e(r.unwrap())):r instanceof Y?Y.create(r.items.map(e=>$e(e))):r}var q=class r extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return m(u,{code:l.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof W&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let p=a[u],_=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new V(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof W){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of o)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")o.length>0&&(m(s,{code:l.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of o){let _=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new V(s,_,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let _=await p.key,O=await p.value;u.push({key:_,value:O,alwaysSet:p.alwaysSet})}return u}).then(u=>R.mergeObjectSync(n,u)):R.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of b.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of b.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){let t={};for(let n of b.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of b.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof D;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Lr(b.objectKeys(this.shape))}};q.create=(r,e)=>new q({shape:()=>r,unknownKeys:"strip",catchall:W.create(),typeName:y.ZodObject,...v(e)});q.strictCreate=(r,e)=>new q({shape:()=>r,unknownKeys:"strict",catchall:W.create(),typeName:y.ZodObject,...v(e)});q.lazycreate=(r,e)=>new q({shape:r,unknownKeys:"strip",catchall:W.create(),typeName:y.ZodObject,...v(e)});var we=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new L(o.ctx.common.issues));return m(t,{code:l.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},p=c._parseSync({data:t.data,path:t.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new L(c));return m(t,{code:l.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};we.create=(r,e)=>new we({options:r,typeName:y.ZodUnion,...v(e)});var re=r=>r instanceof xe?re(r.schema):r instanceof F?re(r.innerType()):r instanceof ke?[r.value]:r instanceof Se?r.options:r instanceof Te?b.objectValues(r.enum):r instanceof Ie?re(r._def.innerType):r instanceof _e?[void 0]:r instanceof ve?[null]:r instanceof D?[void 0,...re(r.unwrap())]:r instanceof X?[null,...re(r.unwrap())]:r instanceof Ye||r instanceof Ae?re(r.unwrap()):r instanceof Ee?re(r._def.innerType):[],yt=class r extends w{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return m(t,{code:l.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=re(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function Vt(r,e){let t=K(r),n=K(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=b.objectKeys(e),a=b.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=Vt(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=Vt(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var be=class extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(ht(a)||ht(i))return g;let o=Vt(a.value,i.value);return o.valid?((gt(a)||gt(i))&&t.dirty(),{status:t.value,value:o.data}):(m(n,{code:l.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};be.create=(r,e,t)=>new be({left:r,right:e,typeName:y.ZodIntersection,...v(t)});var Y=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return m(n,{code:l.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return m(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new V(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>R.mergeArray(t,i)):R.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Y.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Y({items:r,typeName:y.ZodTuple,rest:null,...v(e)})};var _t=class r extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return m(n,{code:l.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new V(n,o,n.path,o)),value:i._parse(new V(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?R.mergeObjectAsync(t,s):R.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof w?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...v(n)}):new r({keyType:ce.create(),valueType:e,typeName:y.ZodRecord,...v(t)})}},Le=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return m(n,{code:l.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new V(n,o,n.path,[u,"key"])),value:a._parse(new V(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return g;(u.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(u.value,p.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return g;(u.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(u.value,p.value)}return{status:t.value,value:o}}}};Le.create=(r,e,t)=>new Le({valueType:e,keyType:r,typeName:y.ZodMap,...v(t)});var qe=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return m(n,{code:l.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let p of c){if(p.status==="aborted")return g;p.status==="dirty"&&t.dirty(),u.add(p.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new V(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};qe.create=(r,e)=>new qe({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var vt=class r extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return m(t,{code:l.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return Ke({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ne(),te].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:c}})}function s(o,c){return Ke({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ne(),te].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof le){let o=this;return P(async function(...c){let u=new L([]),p=await o._def.args.parseAsync(c,a).catch(x=>{throw u.addIssue(n(c,x)),u}),_=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(_,a).catch(x=>{throw u.addIssue(s(_,x)),u})})}else{let o=this;return P(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new L([n(c,u.error)]);let p=Reflect.apply(i,this,u.data),_=o._def.returns.safeParse(p,a);if(!_.success)throw new L([s(p,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Y.create(e).rest(ne.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Y.create([]).rest(ne.create()),returns:t||ne.create(),typeName:y.ZodFunction,...v(n)})}},xe=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};xe.create=(r,e)=>new xe({getter:r,typeName:y.ZodLazy,...v(e)});var ke=class extends w{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};ke.create=(r,e)=>new ke({value:r,typeName:y.ZodLiteral,...v(e)});function Lr(r,e){return new Se({values:r,typeName:y.ZodEnum,...v(e)})}var Se=class r extends w{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{expected:b.joinValues(n),received:t.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{received:t.data,code:l.invalid_enum_value,options:n}),g}return P(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Se.create=Lr;var Te=class extends w{_parse(e){let t=b.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=b.objectValues(t);return m(n,{expected:b.joinValues(s),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=b.objectValues(t);return m(n,{received:n.data,code:l.invalid_enum_value,options:s}),g}return P(e.data)}get enum(){return this._def.values}};Te.create=(r,e)=>new Te({values:r,typeName:y.ZodNativeEnum,...v(e)});var le=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return m(t,{code:l.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return P(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};le.create=(r,e)=>new le({type:r,typeName:y.ZodPromise,...v(e)});var F=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{m(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?me(c.value):t.value==="dirty"?me(c.value):c});{if(t.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?me(o.value):t.value==="dirty"?me(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!oe(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>oe(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);b.assertNever(s)}};F.create=(r,e,t)=>new F({schema:r,typeName:y.ZodEffects,effect:e,...v(t)});F.createWithPreprocess=(r,e,t)=>new F({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...v(t)});var D=class extends w{_parse(e){return this._getType(e)===f.undefined?P(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};D.create=(r,e)=>new D({innerType:r,typeName:y.ZodOptional,...v(e)});var X=class extends w{_parse(e){return this._getType(e)===f.null?P(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};X.create=(r,e)=>new X({innerType:r,typeName:y.ZodNullable,...v(e)});var Ie=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var Ee=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ee.create=(r,e)=>new Ee({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Ue=class extends w{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Ue.create=r=>new Ue({typeName:y.ZodNaN,...v(r)});var Ps=Symbol("zod_brand"),Ye=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Xe=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),me(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:y.ZodPipeline})}},Ae=class extends w{_parse(e){let t=this._def.innerType._parse(e),n=s=>(oe(s)&&(s.value=Object.freeze(s.value)),s);return Pe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Ae.create=(r,e)=>new Ae({innerType:r,typeName:y.ZodReadonly,...v(e)});function Pr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function qr(r,e={},t){return r?ue.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Pr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Pr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):ue.create()}var $s={object:q.lazycreate},y;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(y||(y={}));var Ms=(r,e={message:`Input not instance of ${r.name}`})=>qr(t=>t instanceof r,e),Ur=ce.create,Dr=fe.create,js=Ue.create,Ls=he.create,Vr=ge.create,qs=ye.create,Us=Me.create,Ds=_e.create,Vs=ve.create,Fs=ue.create,Hs=ne.create,zs=W.create,Ws=je.create,Zs=se.create,Bs=q.create,Gs=q.strictCreate,Ks=we.create,Ys=yt.create,Xs=be.create,Js=Y.create,Qs=_t.create,ea=Le.create,ta=qe.create,ra=vt.create,na=xe.create,sa=ke.create,aa=Se.create,ia=Te.create,oa=le.create,ca=F.create,ua=D.create,la=X.create,da=F.createWithPreprocess,pa=Xe.create,ma=()=>Ur().optional(),fa=()=>Dr().optional(),ha=()=>Vr().optional(),ga={string:(r=>ce.create({...r,coerce:!0})),number:(r=>fe.create({...r,coerce:!0})),boolean:(r=>ge.create({...r,coerce:!0})),bigint:(r=>he.create({...r,coerce:!0})),date:(r=>ye.create({...r,coerce:!0}))};var ya=g;var Fr="1.0.6",Hr=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),zr=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),Wr=k.object({daily_remaining:k.number(),daily_limit:k.number()}),_a=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),va=k.object({proactive:_a,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),wa=k.object({user:Hr,usage:zr,budget:Wr,suggestions:va}),ba=k.object({user:Hr,usage:zr,budget:Wr});function xa(r){let e=wa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=ba.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Re(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var ka=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
16
|
+
`)}function Sr(r){let e=mt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=Object.keys(e.tiers);return{type:"object",properties:{tier:{type:"string",enum:t,default:t[0],description:`Quality/style tier. Default: ${t[0]}.`},...e.inputProperties},required:e.required??[]}}async function Tr(r,e,t){let n=mt[r];if(!n)throw new Error(`Unknown meta-tool: ${r}`);let s=Object.keys(n.tiers),a=s[0],i=e.tier||a,o=n.tiers[i];if(!o)throw new Error(`Unknown tier '${i}' for ${r}. Valid tiers: ${s.join(", ")}`);let{tier:c,...u}=e;return E.executeTool({tool_id:o.toolId,...u},t)}var Ce=Object.keys(mt);var Mt=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card","pxlwall_card"]),jt=new Set(["discover_tools","execute_tool"]),as=new Set(Ce);function Ir(r){return Mt.has(r)&&!We()?"VISA_SPECIFIC_TOOLS":jt.has(r)&&!Be()?"VISA_DISCOVER_TOOLS":as.has(r)&&!Ze()?"VISA_META_TOOLS":null}var ft=I(require("fs")),Er=I(require("path")),Ar=I(require("os"));var Lt=Er.join(Ar.homedir(),".visa-mcp"),Ge=class{static ensureConfigDir(){ft.existsSync(Lt)||ft.mkdirSync(Lt,{recursive:!0,mode:448})}static getConfigDir(){return Lt}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let e=new Set;for(let[t,n]of Object.entries(this.TOOL_STATES))n||e.add(t);return e}static isToolDisabled(e){return this.TOOL_STATES[e]===!1}};var qt=["pay","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card"],is={generate_image_card:"image generation",generate_image_fast_card:"fast image generation",generate_music_tempo_card:"music generation",generate_video_tempo_card:"video generation",query_onchain_prices_card:"onchain price queries",allium_explorer_card:"blockchain data exploration",allium_explorer_results_card:"blockchain data results",pay:"payments"};function os(r){return is[r]||r}var pe=null;async function Rr(r){if(pe!==null)return pe;try{let{transactions:e}=await r.getTransactions();pe={};for(let t of e)t.status==="completed"&&(pe[t.tool_name]=(pe[t.tool_name]||0)+1)}catch{d.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),pe={}}return pe}function Or(r,e,t){return qt.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${os(r)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:t}}:e%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:t}}:{}:{}}var k={};Yt(k,{BRAND:()=>Ps,DIRTY:()=>me,EMPTY_PATH:()=>ds,INVALID:()=>g,NEVER:()=>ya,OK:()=>P,ParseStatus:()=>R,Schema:()=>w,ZodAny:()=>ue,ZodArray:()=>se,ZodBigInt:()=>he,ZodBoolean:()=>ge,ZodBranded:()=>Ye,ZodCatch:()=>Ee,ZodDate:()=>ye,ZodDefault:()=>Ie,ZodDiscriminatedUnion:()=>yt,ZodEffects:()=>F,ZodEnum:()=>Se,ZodError:()=>L,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>vt,ZodIntersection:()=>be,ZodIssueCode:()=>l,ZodLazy:()=>xe,ZodLiteral:()=>ke,ZodMap:()=>Le,ZodNaN:()=>Ue,ZodNativeEnum:()=>Te,ZodNever:()=>W,ZodNull:()=>ve,ZodNullable:()=>X,ZodNumber:()=>fe,ZodObject:()=>q,ZodOptional:()=>D,ZodParsedType:()=>f,ZodPipeline:()=>Xe,ZodPromise:()=>le,ZodReadonly:()=>Ae,ZodRecord:()=>_t,ZodSchema:()=>w,ZodSet:()=>qe,ZodString:()=>ce,ZodSymbol:()=>Me,ZodTransformer:()=>F,ZodTuple:()=>Y,ZodType:()=>w,ZodUndefined:()=>_e,ZodUnion:()=>we,ZodUnknown:()=>ne,ZodVoid:()=>je,addIssueToContext:()=>m,any:()=>Fs,array:()=>Zs,bigint:()=>Ls,boolean:()=>Vr,coerce:()=>ga,custom:()=>qr,date:()=>qs,datetimeRegex:()=>jr,defaultErrorMap:()=>te,discriminatedUnion:()=>Ys,effect:()=>ca,enum:()=>aa,function:()=>ra,getErrorMap:()=>Ne,getParsedType:()=>K,instanceof:()=>Ms,intersection:()=>Xs,isAborted:()=>ht,isAsync:()=>Pe,isDirty:()=>gt,isValid:()=>oe,late:()=>$s,lazy:()=>na,literal:()=>sa,makeIssue:()=>Ke,map:()=>ea,nan:()=>js,nativeEnum:()=>ia,never:()=>zs,null:()=>Vs,nullable:()=>la,number:()=>Dr,object:()=>Bs,objectUtil:()=>Ut,oboolean:()=>ha,onumber:()=>fa,optional:()=>ua,ostring:()=>ma,pipeline:()=>pa,preprocess:()=>da,promise:()=>oa,quotelessJson:()=>cs,record:()=>Qs,set:()=>ta,setErrorMap:()=>ls,strictObject:()=>Gs,string:()=>Ur,symbol:()=>Us,transformer:()=>ca,tuple:()=>Js,undefined:()=>Ds,union:()=>Ks,unknown:()=>Hs,util:()=>b,void:()=>Ws});var b;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var Ut;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ut||(Ut={}));var f=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var l=b.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"]),cs=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),L=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};L.create=r=>new L(r);var us=(r,e)=>{let t;switch(r.code){case l.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,b.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(r.options)}, received '${r.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:b.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case l.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case l.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(r)}return{message:t}},te=us;var Cr=te;function ls(r){Cr=r}function Ne(){return Cr}var Ke=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},ds=[];function m(r,e){let t=Ne(),n=Ke({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===te?void 0:te].filter(s=>!!s)});r.common.issues.push(n)}var R=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),me=r=>({status:"dirty",value:r}),P=r=>({status:"valid",value:r}),ht=r=>r.status==="aborted",gt=r=>r.status==="dirty",oe=r=>r.status==="valid",Pe=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var V=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Nr=(r,e)=>{if(oe(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new L(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var w=class{get description(){return this._def.description}_getType(e){return K(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Nr(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return oe(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>oe(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Pe(s)?s:Promise.resolve(s));return Nr(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:l.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new F({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return D.create(this,this._def)}nullable(){return X.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return le.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new F({...v(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ie({...v(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Ye({typeName:y.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ee({...v(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xe.create(this,e)}readonly(){return Ae.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ps=/^c[^\s-]{8,}$/i,ms=/^[0-9a-z]+$/,fs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hs=/^[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,gs=/^[a-z0-9_-]{21}$/i,ys=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_s=/^[-+]?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)?)??$/,vs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ws="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dt,bs=/^(?:(?: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])$/,xs=/^(?:(?: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])$/,ks=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ss=/^(([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])$/,Ts=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Is=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$r="((\\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])))",Es=new RegExp(`^${$r}$`);function Mr(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function As(r){return new RegExp(`^${Mr(r)}$`)}function jr(r){let e=`${$r}T${Mr(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Rs(r,e){return!!((e==="v4"||!e)&&bs.test(r)||(e==="v6"||!e)&&ks.test(r))}function Os(r,e){if(!ys.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Cs(r,e){return!!((e==="v4"||!e)&&xs.test(r)||(e==="v6"||!e)&&Ss.test(r))}var ce=class r extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.string,received:a.parsedType}),g}let n=new R,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&m(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")vs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Dt||(Dt=new RegExp(ws,"u")),Dt.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")hs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")gs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")ps.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")ms.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")fs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:l.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:l.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?jr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Es.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?As(a).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:l.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?_s.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Rs(e.data,a.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Os(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Cs(e.data,a.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Ts.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Is.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:l.invalid_string,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:l.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};ce.create=r=>new ce({checks:[],typeName:y.ZodString,coerce:r?.coerce??!1,...v(r)});function Ns(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var fe=class r extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.number,received:a.parsedType}),g}let n,s=new R;for(let a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Ns(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_finite,message:a.message}),s.dirty()):b.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};fe.create=r=>new fe({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...v(r)});var he=class r extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new R;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):b.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};he.create=r=>new he({checks:[],typeName:y.ZodBigInt,coerce:r?.coerce??!1,...v(r)});var ge=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.boolean,received:n.parsedType}),g}return P(e.data)}};ge.create=r=>new ge({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...v(r)});var ye=class r extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_type,expected:f.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return m(a,{code:l.invalid_date}),g}let n=new R,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):b.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};ye.create=r=>new ye({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...v(r)});var Me=class extends w{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.symbol,received:n.parsedType}),g}return P(e.data)}};Me.create=r=>new Me({typeName:y.ZodSymbol,...v(r)});var _e=class extends w{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.undefined,received:n.parsedType}),g}return P(e.data)}};_e.create=r=>new _e({typeName:y.ZodUndefined,...v(r)});var ve=class extends w{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.null,received:n.parsedType}),g}return P(e.data)}};ve.create=r=>new ve({typeName:y.ZodNull,...v(r)});var ue=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return P(e.data)}};ue.create=r=>new ue({typeName:y.ZodAny,...v(r)});var ne=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return P(e.data)}};ne.create=r=>new ne({typeName:y.ZodUnknown,...v(r)});var W=class extends w{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:f.never,received:t.parsedType}),g}};W.create=r=>new W({typeName:y.ZodNever,...v(r)});var je=class extends w{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.void,received:n.parsedType}),g}return P(e.data)}};je.create=r=>new je({typeName:y.ZodVoid,...v(r)});var se=class r extends w{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return m(t,{code:l.invalid_type,expected:f.array,received:t.parsedType}),g;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(m(t,{code:i?l.too_big:l.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(m(t,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(m(t,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new V(t,i,t.path,o)))).then(i=>R.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new V(t,i,t.path,o)));return R.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...v(e)});function $e(r){if(r instanceof q){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=D.create($e(n))}return new q({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:$e(r.element)}):r instanceof D?D.create($e(r.unwrap())):r instanceof X?X.create($e(r.unwrap())):r instanceof Y?Y.create(r.items.map(e=>$e(e))):r}var q=class r extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return m(u,{code:l.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof W&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let p=a[u],_=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new V(s,_,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof W){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of o)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")o.length>0&&(m(s,{code:l.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of o){let _=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new V(s,_,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let _=await p.key,O=await p.value;u.push({key:_,value:O,alwaysSet:p.alwaysSet})}return u}).then(u=>R.mergeObjectSync(n,u)):R.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of b.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of b.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){let t={};for(let n of b.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of b.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof D;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return Lr(b.objectKeys(this.shape))}};q.create=(r,e)=>new q({shape:()=>r,unknownKeys:"strip",catchall:W.create(),typeName:y.ZodObject,...v(e)});q.strictCreate=(r,e)=>new q({shape:()=>r,unknownKeys:"strict",catchall:W.create(),typeName:y.ZodObject,...v(e)});q.lazycreate=(r,e)=>new q({shape:r,unknownKeys:"strip",catchall:W.create(),typeName:y.ZodObject,...v(e)});var we=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new L(o.ctx.common.issues));return m(t,{code:l.invalid_union,unionErrors:i}),g}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},p=c._parseSync({data:t.data,path:t.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new L(c));return m(t,{code:l.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};we.create=(r,e)=>new we({options:r,typeName:y.ZodUnion,...v(e)});var re=r=>r instanceof xe?re(r.schema):r instanceof F?re(r.innerType()):r instanceof ke?[r.value]:r instanceof Se?r.options:r instanceof Te?b.objectValues(r.enum):r instanceof Ie?re(r._def.innerType):r instanceof _e?[void 0]:r instanceof ve?[null]:r instanceof D?[void 0,...re(r.unwrap())]:r instanceof X?[null,...re(r.unwrap())]:r instanceof Ye||r instanceof Ae?re(r.unwrap()):r instanceof Ee?re(r._def.innerType):[],yt=class r extends w{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return m(t,{code:l.invalid_type,expected:f.object,received:t.parsedType}),g;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=re(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(n)})}};function Vt(r,e){let t=K(r),n=K(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=b.objectKeys(e),a=b.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=Vt(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=Vt(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var be=class extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(ht(a)||ht(i))return g;let o=Vt(a.value,i.value);return o.valid?((gt(a)||gt(i))&&t.dirty(),{status:t.value,value:o.data}):(m(n,{code:l.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};be.create=(r,e,t)=>new be({left:r,right:e,typeName:y.ZodIntersection,...v(t)});var Y=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return m(n,{code:l.invalid_type,expected:f.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return m(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new V(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>R.mergeArray(t,i)):R.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Y.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Y({items:r,typeName:y.ZodTuple,rest:null,...v(e)})};var _t=class r extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return m(n,{code:l.invalid_type,expected:f.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new V(n,o,n.path,o)),value:i._parse(new V(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?R.mergeObjectAsync(t,s):R.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof w?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...v(n)}):new r({keyType:ce.create(),valueType:e,typeName:y.ZodRecord,...v(t)})}},Le=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return m(n,{code:l.invalid_type,expected:f.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new V(n,o,n.path,[u,"key"])),value:a._parse(new V(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return g;(u.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(u.value,p.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return g;(u.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(u.value,p.value)}return{status:t.value,value:o}}}};Le.create=(r,e,t)=>new Le({valueType:e,keyType:r,typeName:y.ZodMap,...v(t)});var qe=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return m(n,{code:l.invalid_type,expected:f.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let p of c){if(p.status==="aborted")return g;p.status==="dirty"&&t.dirty(),u.add(p.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new V(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};qe.create=(r,e)=>new qe({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...v(e)});var vt=class r extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return m(t,{code:l.invalid_type,expected:f.function,received:t.parsedType}),g;function n(o,c){return Ke({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ne(),te].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:c}})}function s(o,c){return Ke({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ne(),te].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof le){let o=this;return P(async function(...c){let u=new L([]),p=await o._def.args.parseAsync(c,a).catch(x=>{throw u.addIssue(n(c,x)),u}),_=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(_,a).catch(x=>{throw u.addIssue(s(_,x)),u})})}else{let o=this;return P(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new L([n(c,u.error)]);let p=Reflect.apply(i,this,u.data),_=o._def.returns.safeParse(p,a);if(!_.success)throw new L([s(p,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Y.create(e).rest(ne.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Y.create([]).rest(ne.create()),returns:t||ne.create(),typeName:y.ZodFunction,...v(n)})}},xe=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};xe.create=(r,e)=>new xe({getter:r,typeName:y.ZodLazy,...v(e)});var ke=class extends w{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};ke.create=(r,e)=>new ke({value:r,typeName:y.ZodLiteral,...v(e)});function Lr(r,e){return new Se({values:r,typeName:y.ZodEnum,...v(e)})}var Se=class r extends w{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{expected:b.joinValues(n),received:t.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{received:t.data,code:l.invalid_enum_value,options:n}),g}return P(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Se.create=Lr;var Te=class extends w{_parse(e){let t=b.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=b.objectValues(t);return m(n,{expected:b.joinValues(s),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=b.objectValues(t);return m(n,{received:n.data,code:l.invalid_enum_value,options:s}),g}return P(e.data)}get enum(){return this._def.values}};Te.create=(r,e)=>new Te({values:r,typeName:y.ZodNativeEnum,...v(e)});var le=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return m(t,{code:l.invalid_type,expected:f.promise,received:t.parsedType}),g;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return P(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};le.create=(r,e)=>new le({type:r,typeName:y.ZodPromise,...v(e)});var F=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{m(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?me(c.value):t.value==="dirty"?me(c.value):c});{if(t.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?me(o.value):t.value==="dirty"?me(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!oe(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>oe(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):g);b.assertNever(s)}};F.create=(r,e,t)=>new F({schema:r,typeName:y.ZodEffects,effect:e,...v(t)});F.createWithPreprocess=(r,e,t)=>new F({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...v(t)});var D=class extends w{_parse(e){return this._getType(e)===f.undefined?P(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};D.create=(r,e)=>new D({innerType:r,typeName:y.ZodOptional,...v(e)});var X=class extends w{_parse(e){return this._getType(e)===f.null?P(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};X.create=(r,e)=>new X({innerType:r,typeName:y.ZodNullable,...v(e)});var Ie=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var Ee=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ee.create=(r,e)=>new Ee({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Ue=class extends w{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return m(n,{code:l.invalid_type,expected:f.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Ue.create=r=>new Ue({typeName:y.ZodNaN,...v(r)});var Ps=Symbol("zod_brand"),Ye=class extends w{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Xe=class r extends w{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(t.dirty(),me(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:y.ZodPipeline})}},Ae=class extends w{_parse(e){let t=this._def.innerType._parse(e),n=s=>(oe(s)&&(s.value=Object.freeze(s.value)),s);return Pe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Ae.create=(r,e)=>new Ae({innerType:r,typeName:y.ZodReadonly,...v(e)});function Pr(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function qr(r,e={},t){return r?ue.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Pr(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=Pr(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):ue.create()}var $s={object:q.lazycreate},y;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(y||(y={}));var Ms=(r,e={message:`Input not instance of ${r.name}`})=>qr(t=>t instanceof r,e),Ur=ce.create,Dr=fe.create,js=Ue.create,Ls=he.create,Vr=ge.create,qs=ye.create,Us=Me.create,Ds=_e.create,Vs=ve.create,Fs=ue.create,Hs=ne.create,zs=W.create,Ws=je.create,Zs=se.create,Bs=q.create,Gs=q.strictCreate,Ks=we.create,Ys=yt.create,Xs=be.create,Js=Y.create,Qs=_t.create,ea=Le.create,ta=qe.create,ra=vt.create,na=xe.create,sa=ke.create,aa=Se.create,ia=Te.create,oa=le.create,ca=F.create,ua=D.create,la=X.create,da=F.createWithPreprocess,pa=Xe.create,ma=()=>Ur().optional(),fa=()=>Dr().optional(),ha=()=>Vr().optional(),ga={string:(r=>ce.create({...r,coerce:!0})),number:(r=>fe.create({...r,coerce:!0})),boolean:(r=>ge.create({...r,coerce:!0})),bigint:(r=>he.create({...r,coerce:!0})),date:(r=>ye.create({...r,coerce:!0}))};var ya=g;var Fr="1.0.7-rc.1",Hr=k.object({name:k.string().max(100).nullable(),location:k.string().max(100).nullable(),member_since:k.string()}),zr=k.object({total_transactions:k.number(),total_spent:k.number(),tools_used:k.record(k.string(),k.number()),last_active:k.string().nullable(),themes:k.array(k.string().max(100)).max(20),recent_prompts:k.array(k.string().max(500)).max(50).optional().default([])}),Wr=k.object({daily_remaining:k.number(),daily_limit:k.number()}),_a=k.object({message:k.string().max(500),tool:k.string(),reason:k.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),va=k.object({proactive:_a,reactive:k.record(k.string(),k.array(k.string().max(500)).nullable())}),wa=k.object({user:Hr,usage:zr,budget:Wr,suggestions:va}),ba=k.object({user:Hr,usage:zr,budget:Wr});function xa(r){let e=wa.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=ba.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Re(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var ka=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
17
17
|
|
|
18
18
|
Rules:
|
|
19
19
|
- If the user asks a question that one of your tools can answer \u2014 including historical data, analytics, comparisons, or trends \u2014 offer to use the tool. Don't just answer from your training data when live data is available.
|
|
@@ -55,7 +55,7 @@ Your first response in this session MUST end with this line in bold italic:
|
|
|
55
55
|
`+_.map(O=>`- "${O}"`).join(`
|
|
56
56
|
`))}}return e.join(`
|
|
57
57
|
|
|
58
|
-
`)}},Ht=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),zt=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!Ht.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!Ht.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Re(n)),t}},Aa=3e3;async function Wt(r,e,t){let n={instructions:new Je(null,t).build(),manager:null};try{let s=await r();if(!s)return d.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Tt(),Xt)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":Fr},timeoutMs:Aa});if(!i.ok)return d.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!tt()){let p=i.headers.get("X-Latest-Version"),_=i.headers.get("X-Update-Message");p&&et(p,Fr)&&(o=_||`Update available: v${p}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),u=xa(c);if(u.full)return d.info(`suggestions: loaded for ${u.full.user.name??"unknown"} (proactive: ${u.full.suggestions.proactive?"yes":"none"})`),{instructions:new Je(u.full,t,o).build(),manager:new zt(u.full.suggestions.reactive)};if(u.partial){d.warn("suggestions: suggestions block malformed, using partial payload");let p={...u.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new Je(p,t,o).build(),manager:null}}return d.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return d.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var wt=I(require("crypto")),bt=I(require("tty")),xt=I(require("fs"));var Oe="
|
|
58
|
+
`)}},Ht=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),zt=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!Ht.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!Ht.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Re(n)),t}},Aa=3e3;async function Wt(r,e,t){let n={instructions:new Je(null,t).build(),manager:null};try{let s=await r();if(!s)return d.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Tt(),Xt)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":Fr},timeoutMs:Aa});if(!i.ok)return d.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!tt()){let p=i.headers.get("X-Latest-Version"),_=i.headers.get("X-Update-Message");p&&et(p,Fr)&&(o=_||`Update available: v${p}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),u=xa(c);if(u.full)return d.info(`suggestions: loaded for ${u.full.user.name??"unknown"} (proactive: ${u.full.suggestions.proactive?"yes":"none"})`),{instructions:new Je(u.full,t,o).build(),manager:new zt(u.full.suggestions.reactive)};if(u.partial){d.warn("suggestions: suggestions block malformed, using partial payload");let p={...u.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new Je(p,t,o).build(),manager:null}}return d.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return d.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var wt=I(require("crypto")),bt=I(require("tty")),xt=I(require("fs"));var Oe="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";function Oa(r){return/-rc\.|-beta\./.test(r)}function Zt(r){return wt.createHash("sha256").update(r.trim()).digest("hex")}function Br(r){return Oe==="SKIP"?!0:wt.timingSafeEqual(Buffer.from(Zt(r)),Buffer.from(Oe))}function Ca(r){return new Promise((e,t)=>{let n=xt.openSync("/dev/tty","r+"),s=new bt.ReadStream(n),a=new bt.WriteStream(n),i=()=>{try{s.destroy()}catch{}try{a.destroy()}catch{}try{xt.closeSync(n)}catch{}};a.write(r),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let o="";s.on("data",c=>{c==="\r"||c===`
|
|
59
59
|
`?(a.write(`
|
|
60
60
|
`),i(),e(o)):c===""?(a.write(`
|
|
61
61
|
`),i(),t(new Error("Cancelled"))):c==="\x7F"||c==="\b"?o.length>0&&(o=o.slice(0,-1),a.write("\b \b")):(o+=c,a.write("\u2022"))})})}var Na=`
|