@visa/cli 4.1.0-rc.52 → 4.1.0-rc.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var jgt=Object.create;var cB=Object.defineProperty;var Ugt=Object.getOwnPropertyDescriptor;var Mgt=Object.getOwnPropertyNames;var qgt=Object.getPrototypeOf,Dgt=Object.prototype.hasOwnProperty;var P=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Ei=(e,t)=>{for(var r in t)cB(e,r,{get:t[r],enumerable:!0})},jAe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Mgt(t))!Dgt.call(e,i)&&i!==r&&cB(e,i,{get:()=>t[i],enumerable:!(n=Ugt(t,i))||n.enumerable});return e};var Me=(e,t,r)=>(r=e!=null?jgt(qgt(e)):{},jAe(t||!e||!e.__esModule?cB(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>jAe(cB({},"__esModule",{value:!0}),e);async function UAe(e,t){let r=t?.timeoutMs??3e4,n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let{timeoutMs:o,...s}=t??{};return await fetch(e,{...s,signal:n.signal})}finally{clearTimeout(i)}}var MAe=P(()=>{"use strict"});var uB,qAe=P(()=>{"use strict";uB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}}});function LAe(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let r=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return r&&DAe[r]?DAe[r]:`Network error contacting the Visa CLI server (${r?`${r}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var DAe,zAe=P(()=>{"use strict";DAe={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."}});function FAe(e,t){let r=HAe(e),n=HAe(t);if(!r||!n)return!1;for(let i=0;i<3;i++)if(r.main[i]!==n.main[i])return r.main[i]>n.main[i];return r.pre&&!n.pre?!1:!r.pre&&n.pre?!0:!r.pre&&!n.pre?!1:zgt(r.pre,n.pre)>0}function HAe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Lgt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function zgt(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){if(o>=r.length)return-1;if(o>=n.length)return 1;let s=r[o],a=n[o],c=/^\d+$/.test(s),u=/^\d+$/.test(a);if(c&&u){let d=Number(s)-Number(a);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(s<a)return-1;if(s>a)return 1}}return 0}var Lgt,VAe=P(()=>{"use strict";Lgt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function dB(){return!!($Ae(process.env.VISA_CLI_NO_UPDATE_CHECK)||$Ae(process.env.CI)||process.env.NODE_ENV==="test")}function $Ae(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var qX=P(()=>{"use strict"});var lB,KAe,WAe,DX,zS,GAe=P(()=>{"use strict";lB=Me(require("fs")),KAe=Me(require("path")),WAe=Me(require("os")),DX=KAe.join(WAe.homedir(),".visa-mcp"),zS=class{static ensureConfigDir(){lB.existsSync(DX)||lB.mkdirSync(DX,{recursive:!0,mode:448})}static getConfigDir(){return DX}}});function Fgt(){Ja.existsSync(zX)||Ja.mkdirSync(zX,{recursive:!0,mode:448})}function Vgt(){if(!LX){if(Fgt(),Ja.existsSync(HS)&&Ja.statSync(HS).size>Hgt){let t=HS+".1";Ja.existsSync(t)&&Ja.unlinkSync(t),Ja.renameSync(HS,t)}LX=Ja.createWriteStream(HS,{flags:"a"})}return LX}function $gt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function pB(e,...t){let r=new Date().toISOString(),n=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${r}] [${e}] ${n}
|
|
3
|
-
`;$gt(e)&&process.stderr.write(i),Vgt().write(i)}var Ja,HX,JAe,zX,HS,Hgt,LX,Ne,xl=P(()=>{"use strict";Ja=Me(require("fs")),HX=Me(require("path")),JAe=Me(require("os")),zX=HX.join(JAe.homedir(),".visa-mcp"),HS=HX.join(zX,"mcp-server.log"),Hgt=5*1024*1024,LX=null;Ne={debug:(...e)=>pB("DEBUG",...e),info:(...e)=>pB("INFO",...e),warn:(...e)=>pB("WARN",...e),error:(...e)=>pB("ERROR",...e)}});var fB=g((KOr,Kgt)=>{Kgt.exports={name:"@visa/cli",version:"4.1.0-rc.
|
|
3
|
+
`;$gt(e)&&process.stderr.write(i),Vgt().write(i)}var Ja,HX,JAe,zX,HS,Hgt,LX,Ne,xl=P(()=>{"use strict";Ja=Me(require("fs")),HX=Me(require("path")),JAe=Me(require("os")),zX=HX.join(JAe.homedir(),".visa-mcp"),HS=HX.join(zX,"mcp-server.log"),Hgt=5*1024*1024,LX=null;Ne={debug:(...e)=>pB("DEBUG",...e),info:(...e)=>pB("INFO",...e),warn:(...e)=>pB("WARN",...e),error:(...e)=>pB("ERROR",...e)}});var fB=g((KOr,Kgt)=>{Kgt.exports={name:"@visa/cli",version:"4.1.0-rc.53",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test: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","@ucp-js/sdk":"0.4.1",commander:"^12.1.0",zod:"^3.23.0"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1","playwright-core":"^1.48.2"},devDependencies:{"@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.65.0","@typescript-eslint/parser":"^8.65.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function YAe(e){let t=ZAe.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function mB(){return XAe.join(zS.getConfigDir(),Wgt)}function QAe(e){if((0,VX.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Jgt(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),n=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(n))return!1;let i=[r>>8&255,r&255,n>>8&255,n&255].join(".");return QAe(i)}function Ygt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,VX.isIP)(t);return r===4?QAe(t):r===6?t==="::1"||Jgt(t):!1}function FX(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&Ygt(r.hostname)))throw new Error(`${t} ${Ggt}`)}function hB(){let e=mB();if(!Mh.existsSync(e))return{};try{let t=Mh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Ne.warn("settings:corrupt",{path:YAe(e),reason:"not_object"}),{}):r}catch(t){return Ne.warn("settings:corrupt",{path:YAe(e),error:t?.message||String(t)}),{}}}function e9e(e){zS.ensureConfigDir();let t=mB(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
|
|
4
4
|
`;Mh.writeFileSync(r,n,{mode:384}),Mh.renameSync(r,t)}function $X(e){let t=hB()[e];return typeof t=="string"?t:void 0}function KX(e){let t=hB()[e];return typeof t=="boolean"?t:void 0}function t9e(e,t){let r=FS[e];if(!r)throw new s0(e);let n;if(r.type==="boolean")if(typeof t=="boolean")n=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")n=!0;else if(o==="false")n=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(r.type==="number")if(typeof t=="number")n=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);n=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);n=t}r.validate&&r.validate(n);let i=hB();return i[e]=n,e9e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:mB()}}function r9e(e){let t=FS[e];if(!t)throw new s0(e);let r=hB(),n=e in r;return n&&(delete r[e],e9e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:mB()}}function Qgt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function ebt(){try{let e=fB();return Qgt(e.version)}catch{return!1}}function tbt(e){return e.envVar!==void 0&&e.envVar!==""?(FX(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(FX(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Xgt:Zgt}function td(){return tbt({envVar:process.env.VISA_AUTH_URL,settingValue:$X("auth.serverUrl"),isPrerelease:ebt()})}function n9e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":KX("ui.suppressBrowser")??!1}var Mh,VX,ZAe,XAe,Wgt,Ggt,FS,s0,Zgt,Xgt,p4=P(()=>{"use strict";Mh=Me(require("fs")),VX=require("node:net"),ZAe=Me(require("os")),XAe=Me(require("path"));GAe();xl();Wgt="settings.json",Ggt="must use https unless it points at localhost/loopback for local development";FS={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");FX(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};s0=class extends Error{constructor(t){let r=Object.keys(FS).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Zgt="https://auth.visacli.sh",Xgt="https://auth-visa-code-preview.up.railway.app"});function nbt(e,t){let r=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return r?new Error(r):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function f4(e){return typeof e=="string"?e.trim():""}function obt(e){let t=e&&typeof e=="object"?e:{},r=f4(t.error)||f4(t.message);if(!r)return ibt;let n=f4(t.error_code),i=[["surface",f4(t.disabled_surface)],["flag",f4(t.flag)],["correlation_id",f4(t.correlation_id)]].filter(([,s])=>s).map(([s,a])=>`${s}=${a}`),o=i.length?` (${i.join(" ")})`:"";return n?`503 [${n}] ${r}${o}`:`503 ${r}${o}`}function sbt(e=process.env,t=process.stdin.isTTY){let r=["Not logged in. No local Visa CLI session credentials were found."],n=e.VISA_CLI_API_KEY?.trim();return n?rbt.test(n)?(r.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."),r.push("Use the Visa Key with X-Api-Key on the /v2/harness/* surface.")):(r.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>)."),r.push("Create a new Visa Key with: visa-cli keys create <app-name>")):r.push("Ask your agent to call `enroll_agent` to connect this device."),t===!1&&r.push("Complete enrollment in a normal terminal, then restart the MCP client."),r.join(`
|
|
5
|
-
`)}var yB,rbt,ibt,m4,WX=P(()=>{"use strict";MAe();qAe();zAe();VAe();qX();p4();yB="4.1.0-rc.
|
|
5
|
+
`)}var yB,rbt,ibt,m4,WX=P(()=>{"use strict";MAe();qAe();zAe();VAe();qX();p4();yB="4.1.0-rc.53",rbt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;ibt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";m4=class{constructor(t){this.getSessionToken=t;this.baseUrl=td()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!dB()){let n=t.headers.get("X-Latest-Version");n&&FAe(n,yB)&&(this.lastSignals.updateAvailable={currentVersion:yB,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return yB}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new uB(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let r=null;try{r=await t.json()}catch{}throw new Error(obt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(sbt());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{c=await UAe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":yB,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(LAe(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your device session has expired. Ask your agent to call `enroll_agent` to reconnect.");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s, then retry.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${r}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):(this.throwIfAttestationDrift(u),nbt(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}}});function GX(e=i9e){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function o9e(e=i9e){return/-(?:rc|alpha|beta)\./i.test(e)}function JX(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function qh(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?JX(t):o9e()?cbt:abt}function s9e(e){return`${JX(e)}${ubt}`}function dbt(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||o9e()}function YX(e,t=process.env){if(!e||!dbt(t))return e;try{let r=new URL(qh(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function a9e(e,t=fetch){let r=`${JX(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var i9e,abt,cbt,ubt,gB=P(()=>{"use strict";i9e="4.1.0-rc.53",abt="https://app.visacli.sh",cbt="https://web-visa-code-preview.up.railway.app",ubt="/agent/enroll"});var a0,ZX=P(()=>{"use strict";a0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function p9e(e){return`${e}-${d9e.randomBytes(24).toString("base64url")}`}function f9e(e=process.env){return e.NODE_ENV==="test"||e[l9e]==="true"}function Dh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&f9e(e)}function bB(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&f9e(e)}function XX(){return`Set ${l9e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function m9e(){return c9e??=p9e("mock-session"),c9e}function h9e(e=process.env){return e.NODE_ENV==="test"?a0:(u9e??=p9e("mock-rc"),u9e)}var d9e,l9e,c9e,u9e,_B=P(()=>{"use strict";d9e=Me(require("crypto"));ZX();l9e="VISA_ALLOW_INSECURE_MOCKS"});function pbt(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
|
|
6
6
|
`)}function iQ(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=pbt(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function Hh(){return process.platform!=="darwin"?Promise.resolve(!1):(y9e??=(async()=>{try{return await Sl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return iQ(e)}})(),y9e)}async function fbt(){if(!await Hh())return null;try{let{stdout:e}=await Sl("security",["find-generic-password","-s",rd,"-a",Lh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(iQ(e))throw new wB("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function mbt(e){if(!await Hh())return!1;try{try{await Sl("security",["delete-generic-password","-s",rd,"-a",Lh],{timeout:5e3})}catch{}return await Sl("security",["add-generic-password","-s",rd,"-a",Lh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function hbt(){if(await Hh())try{await Sl("security",["delete-generic-password","-s",rd,"-a",Lh],{timeout:5e3})}catch{}}async function ybt(){if(!oQ())return null;try{let{stdout:e}=await Sl("secret-tool",["lookup","service",rd,"account",Lh],{timeout:5e3});return e.trim()||null}catch{return null}}async function gbt(e){if(!oQ())return!1;try{let t=(0,EB.execFile)("secret-tool",["store","--label",`${rd} ${Lh}`,"service",rd,"account",Lh]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((r,n)=>{t.on("exit",i=>i===0?r():n(new Error(`secret-tool exited ${i}`))),t.on("error",n)}),new Promise((r,n)=>setTimeout(()=>{t.kill(),n(new Error("secret-tool timed out"))},lbt))]),!0):!1}catch{return!1}}async function bbt(){if(oQ())try{await Sl("secret-tool",["clear","service",rd,"account",Lh],{timeout:5e3})}catch{}}function oQ(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function _bt(){if(!await Hh())return null;try{let{stdout:e}=await Sl("security",["find-generic-password","-s",rd,"-a",vB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function vbt(e){if(await Hh())try{try{await Sl("security",["delete-generic-password","-s",rd,"-a",vB],{timeout:5e3})}catch{}await Sl("security",["add-generic-password","-s",rd,"-a",vB,"-w",e],{timeout:5e3})}catch{}}async function wbt(){if(await Hh())try{await Sl("security",["delete-generic-password","-s",rd,"-a",vB],{timeout:5e3})}catch{}}function eQ(){try{return zh.readFileSync(VS,"utf-8").trim()||null}catch(e){if(iQ(e))throw new wB(`Unable to read Visa CLI credentials from ${VS}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function b9e(e){zh.mkdirSync(nQ,{recursive:!0,mode:448}),zh.writeFileSync(VS,e,{mode:384}),process.platform==="win32"&&Ebt(VS)}function tQ(){try{zh.unlinkSync(VS)}catch{}}function Ebt(e){try{let t=AB.userInfo().username;(0,EB.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function QX(){switch(process.platform){case"darwin":return{get:fbt,store:mbt,delete:hbt};case"linux":return{get:ybt,store:gbt,delete:bbt};default:return{get:async()=>eQ(),store:async e=>{try{return b9e(e),!0}catch{return!1}},delete:async()=>tQ(),storesInSessionFile:!0}}}var EB,g9e,zh,AB,rQ,Sl,nQ,VS,rd,Lh,vB,lbt,wB,y9e,Ya,h4=P(()=>{"use strict";EB=require("child_process"),g9e=require("util"),zh=Me(require("fs")),AB=Me(require("os")),rQ=Me(require("path"));_B();Sl=(0,g9e.promisify)(EB.execFile),nQ=rQ.join(AB.homedir(),".visa-mcp"),VS=rQ.join(nQ,"session-token"),rd="visa-cli",Lh="session-token",vB="rc-access",lbt=5e3,wB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};y9e=null;Ya=class{static async getSessionToken(){if(Dh())return Promise.resolve(m9e());let t=QX(),r=await t.get();if(r)return r;let n=eQ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(Dh())return;let r=QX();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||tQ();return}await r.delete()}if(b9e(t),eQ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${nQ} is writable.`))}static async getRcAccessToken(){return Dh()?h9e():_bt()}static async saveRcAccessToken(t){Dh()||await vbt(t)}static async deleteSessionToken(){if(Dh())return;await QX().delete(),tQ()}static async clearAll(){await this.deleteSessionToken(),await wbt()}}});function $S(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function kbt(e){let r=e.length+4;return[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(r)}\u2518`].join(`
|
|
7
7
|
`)}function KS(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function q9e(e,t){let r=KS(e);if(!r)return null;let n,i;try{n=new URL(r),i=new URL(t)}catch{return null}return n.origin===i.origin?r:null}function D9e(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function L9e(e,t=process.platform){let r=KS(e);return r?D9e(r,t):null}function U9e(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function WS(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=KS(e),s=t.spawn??((u,d,l)=>{(0,M9e.execFile)(u,d,p=>l(p))});r(""),r(" Sign in to Visa CLI by opening this URL in your browser:"),r("");for(let u of kbt(o??e).split(`
|
|
8
8
|
`))r(` ${u}`);if(r(""),!o){r(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),r(" Open the URL above manually to continue."),r("");return}let a=$S(n,i);if(a.headless){r(` (${a.reason} \u2014 skipping browser auto-open.)`),r(" Open the URL above on any device with a browser. The CLI will"),r(" continue waiting for you to complete sign-in."),r("");return}let c=D9e(o,i);if(!c){r(` No known browser-open command for platform "${i}".`),r(" Open the URL above manually to continue."),r("");return}await new Promise(u=>{let d=l=>{l?U9e(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){U9e(r,l instanceof Error?l:new Error(String(l))),u()}})}var M9e,sQ=P(()=>{"use strict";M9e=require("child_process")});function Xbt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function wxe(e,t,r=""){let n=Xbt(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function G9e(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Qbt(e,t){wxe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function bQ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function dQ(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function e2t(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function n2t(e,t=!1){return t?{h:Number(e&IB),l:Number(e>>J9e&IB)}:{h:Number(e>>J9e&IB)|0,l:Number(e&IB)|0}}function i2t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=n2t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function d0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function y2t(){return Gbt.randomSecretKey()}function d_(e){return Fbt(e)}function Axe(){let e=y2t();return{secretKey:e,publicKey:d_(e)}}function xxe(e){if(e.length!==Q9e)throw new Error(`Ed25519 seed must be ${Q9e} bytes, got ${e.length}`);return{secretKey:e,publicKey:d_(e)}}function w4(e,t){return Kbt(t,e)}function g2t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function b2t(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function UB(e){return g2t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Txe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return b2t(r)}function _2t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function l_(e){let t=d_(e);return{kty:"OKP",crv:"Ed25519",x:UB(t),d:UB(e)}}function Gh(e){return{kty:"OKP",crv:"Ed25519",x:UB(e)}}function E4(e){if(_2t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return Txe(e.d)}function txe(e,t){return e<t?-1:e>t?1:0}function pQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sr(e){if(typeof e!="string"||!E2t.test(e))return!1;try{let t=Txe(e);return t.byteLength===32&&UB(t)===e}catch{return!1}}function fQ(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function O2t(e,t){if(typeof t!="string"||!w2t.test(t))throw new Error(`${e} must be a UUID`)}function GS(e,t){return O2t(e,t),t.toLowerCase()}function rxe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=x2t.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function CB(e,t,r=!1){if(typeof t!="string"||!A2t.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>T2t)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function C2t(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>S2t)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function nxe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Ixe.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>I2t)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function R2t(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Ixe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function mQ(e,t){return typeof e=="string"&&t.includes(e)}function k2t(e){if(!pQ(e))throw new Error("agent authority grant must be an object");if(fQ("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==b4)throw new Error("grant.v must be 2");let t=GS("grantId",e.grantId),r=GS("agentId",e.agentId),n=C2t("version",e.version),i=GS("budgetEpochId",e.budgetEpochId);if(!mQ(e.budgetEpochMode,v2t))throw new Error("budgetEpochMode must be new or continue");if(!mQ(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==lQ)throw new Error(`valuationPolicy must be '${lQ}'`);let o=CB("totalMicros",e.totalMicros),s=CB("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!pQ(l))throw new Error("grant scope must be an object");if(fQ("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!mQ(l.scope,Kh))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:CB("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:CB("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=R2t("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>exe)throw new Error(`payeeConstraints must contain between 1 and ${exe} entries`);if(c=e.payeeConstraints.map(p=>{if(!pQ(p))throw new Error("payee constraint must be an object");if(fQ("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:nxe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=nxe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!P2t.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=rxe("effectiveAt",e.effectiveAt),d=rxe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&GS("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:b4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:lQ,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>txe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>txe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:GS("supersedesGrantId",e.supersedesGrantId)}:{}}}function Rxe(e,t){return e<t?-1:e>t?1:0}function nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tl(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function z2t(e){if(typeof e!="string")throw new Error("displayName must be a string");if(qB.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>j2t)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function H2t(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(qB.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!B2t.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function RB(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(qB.test(t)||Cxe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function F2t(e){if(!nd(e))throw new Error("runtime context v2 must be an object");Tl("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=RB("runtime",e.runtime,M2t),r=RB("contextLabel",e.contextLabel,q2t),n=e.cliVersion===void 0?void 0:RB("cliVersion",e.cliVersion,D2t),i=e.platform===void 0?void 0:RB("platform",e.platform,L2t);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function IQ(e){if(typeof e!="string"||!Oxe.test(e))throw new Error("pairingId must be a server-generated pairing id")}function DB(e){if(e!==kt)throw new Error("protocolVersion must be 2")}function Wh(e,t){if(typeof t!="string"||!U2t.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function vo(e,t){if(!Sr(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function kxe(e){if(typeof e!="string"||!V2t.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function $2t(e){if(typeof e!="string"||!ixe.includes(e))throw new Error(`capability must be one of ${ixe.join(", ")}`)}function K2t(e){if(typeof e!="string"||!Kh.includes(e))throw new Error(`rail must be one of ${Kh.join(", ")}`)}function axe(e,t){if(typeof t!="string"||t.length===0||t.length>sxe||qB.test(t)||Cxe.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>sxe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function Nxe(){return YS.default.randomBytes(32).toString("base64url")}function Bxe(e){if(!Sr(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return XS(e)}function W2t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function G2t(e){let t=W2t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function LB(){return YS.default.randomBytes(32).toString("base64url")}function l0(e){if(!Sr(e))throw new Error("claim token must be 32 unpadded base64url bytes");return XS(`visa-agent-pairing-claim-token:v1:${e}`)}function zB(e,t){l0(t);let r=YS.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<N2t;i+=1)n+=TQ[r[i]&Pxe];return G2t(n)}function jxe(e){if(!nd(e))throw new Error("pairing terms v2 must be an object");if(Tl("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==b4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!Oxe.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!oxe.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!Sr(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!oxe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=z2t(e.displayName),i=e.dotVisaAddress===void 0?void 0:H2t(e.dotVisaAddress);if(e.authority===null){if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:b4})}if(!nd(e.authority))throw new Error("pairing authority must be an object or null");if(Tl("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>Kh.length)throw new Error(`pairing authority scopes must contain between 1 and ${Kh.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!nd(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(Tl("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!Kh.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Sr(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=k2t({v:b4,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:b4})}function J2t(e){return XS(`visa-agent-pairing-terms:v2:${jxe(e)}`)}function PQ(e){if(!nd(e))throw new Error("pairing claim v2 must be an object");Tl("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),DB(e.protocolVersion),IQ(e.pairingId),Wh("agentId",e.agentId),vo("serverNonce",e.serverNonce),vo("claimTokenHash",e.claimTokenHash),vo("identityKeyJkt",e.identityKeyJkt);let t=F2t(e.runtime);return HB("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function Uxe(e){if(!nd(e))throw new Error("pairing activation v2 must be an object");return Tl("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),DB(e.protocolVersion),IQ(e.pairingId),Wh("agentId",e.agentId),Wh("ownerPublicId",e.ownerPublicId),vo("claimTokenHash",e.claimTokenHash),vo("identityKeyJkt",e.identityKeyJkt),vo("ceremonyHash",e.ceremonyHash),vo("deliveryArtifactHash",e.deliveryArtifactHash),HB("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function Mxe(e){if(!nd(e))throw new Error("capability attach claim v2 must be an object");return Tl("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),DB(e.protocolVersion),kxe(e.attachId),Wh("agentId",e.agentId),$2t(e.capability),vo("serverNonce",e.serverNonce),vo("claimTokenHash",e.claimTokenHash),vo("identityKeyJkt",e.identityKeyJkt),HB("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function OQ(e){if(!nd(e))throw new Error("capability attach activation v2 must be an object");return Tl("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),DB(e.protocolVersion),kxe(e.attachId),Wh("agentId",e.agentId),Wh("ownerPublicId",e.ownerPublicId),vo("identityKeyJkt",e.identityKeyJkt),vo("claimTokenHash",e.claimTokenHash),vo("grantHash",e.grantHash),vo("ceremonyHash",e.ceremonyHash),vo("deliveryArtifactHash",e.deliveryArtifactHash),K2t(e.rail),HB("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function ZS(e){if(!nd(e))throw new Error("pairing delivery artifact v2 must be an object");if(Tl("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==kt)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(IQ(e.pairingId),Wh("agentId",e.agentId),Wh("ownerPublicId",e.ownerPublicId),vo("ceremonyHash",e.ceremonyHash),!nd(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Tl("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),vo("identityKey.jkt",e.identityKey.jkt),!nd(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Tl("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");vo("identityKey.publicJwk.x",t.x);let r=XS(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!nd(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let n=jxe(e.terms);if(J2t(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=axe("issuer",e.issuer),o=axe("activationAudience",e.activationAudience);return _Q({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(n),v:kt})}function qxe(e){return XS(`visa-agent-pairing-delivery-artifact:v2:${ZS(e)}`)}function XS(e){return YS.default.createHash("sha256").update(e,"utf8").digest("base64url")}function HB(e,t){return`${e}
|
|
@@ -33,7 +33,7 @@ ${e.nonce}`;return W_t.encode(r)}function Y_t(e,t,r,n,i,o,s){return J_t({message
|
|
|
33
33
|
`)?a:a+`
|
|
34
34
|
`}function gvt(e){for(let t of e.split(`
|
|
35
35
|
`)){if(t.trim()===""||fj(t)>0)continue;let r=t.trim();if(!(r.startsWith("#")||r==="---"||r==="..."||r.startsWith("- "))&&!/^[^\s:#][^:]*:(\s|$)/.test(r))return!1}return!0}function uee(e,t){return e?e.command===t.command&&Array.isArray(e.args)&&e.args.length===t.args.length&&t.args.every((r,n)=>e.args[n]===r):!1}function ETe(e,t,r=dee()){let n=e.configFormat??"json";try{let i=id.existsSync(t),o=i?id.readFileSync(t,"utf-8"):"",s;if(n==="toml"){if(uee(lvt(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=pvt(o,"visa-cli",r)}else if(n==="yaml"){if(i&&!gvt(o))return{status:"error",configPath:t,error:`existing config at ${t} does not look like editable YAML \u2014 fix or remove it, then re-run`};if(uee(mvt(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=yvt(o,"visa-cli",r)}else{let a={};if(i){try{a=JSON.parse(o)}catch{return{status:"error",configPath:t,error:`existing config at ${t} is not valid JSON \u2014 fix or remove it, then re-run`}}if(!a||typeof a!="object"||Array.isArray(a))return{status:"error",configPath:t,error:`existing config at ${t} is not a JSON object \u2014 fix or remove it, then re-run`}}if(uee(dvt(a,e.configKey)?.["visa-cli"],r))return{status:"already-mounted",configPath:t};uvt(a,e.configKey)["visa-cli"]=e.buildEntry?e.buildEntry(r):r,s=JSON.stringify(a,null,2)+`
|
|
36
|
-
`}return id.mkdirSync(Vt.dirname(t),{recursive:!0}),id.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}var id,Vt,mTe,Bn,ivt,cvt,_Te,ATe=P(()=>{"use strict";id=Me(require("fs")),Vt=Me(require("path")),mTe=Me(require("os")),Bn=mTe.homedir(),ivt=["Claude_","Anthropic.ClaudeDesktop_"];cvt=[{id:"claude",displayName:"Claude Code",globalConfigPath:Vt.join(Bn,".claude.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:svt(),configKey:"mcpServers",detectPaths:avt(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Vt.join(Bn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Vt.join(Bn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Vt.join(Bn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:cee({win32:Vt.join(dT(),"Roo","mcp_settings.json"),posix:Vt.join(Bn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Vt.join(Bn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Vt.join(Bn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:cee({win32:Vt.join(dT(),"Zed","settings.json"),posix:Vt.join(Bn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:cee({win32:[Vt.join(dT(),"Zed")],posix:[Vt.join(Bn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Vt.join(Bn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Vt.join(Bn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Vt.join(Bn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Vt.join(Bn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Vt.join(Bn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Vt.join(Bn,".hermes")],postInstallHint:"Restart Hermes to connect."}];_Te="mcp_servers"});function lee(e,t={}){let r=t.home??mj.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return Yn.join(r,".openclaw","skills");case"hermes":return Yn.join(r,".hermes","skills");case"claude-code":case"claude":return Yn.join(r,".claude","skills");case"default":case"agentskills":return Yn.join(n,".agents","skills");default:return null}}function bvt(e={}){let t=e.home??mj.homedir(),r=[["openclaw",Yn.join(t,".openclaw")],["hermes",Yn.join(t,".hermes")],["claude-code",Yn.join(t,".claude")]];for(let[n,i]of r)if(Ms.existsSync(i))return{runtime:n,base:lee(n,e)};return{runtime:"default",base:lee("default",e)}}function xTe(e){let t=[Yn.join(e,"skills",b0),Yn.join(e,"..","skills",b0),Yn.join(e,"..","..","visa-cli-openclaw","skills",b0),Yn.join(e,"..","..","..","visa-cli-openclaw","skills",b0)];for(let r of t)if(Ms.existsSync(Yn.join(r,"SKILL.md")))return r;return null}function _vt(e){let{bundledDir:t,base:r,force:n}=e;if(!Ms.existsSync(Yn.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=Yn.join(r,b0),o=Ms.existsSync(i)&&Ms.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Ms.mkdirSync(r,{recursive:!0}),o&&Ms.rmSync(i,{recursive:!0,force:!0}),Ms.cpSync(t,i,{recursive:!0}),{installedDir:i,files:vvt(i),overwrote:o}}function vvt(e){let t=[],r=(n,i)=>{for(let o of Ms.readdirSync(n,{withFileTypes:!0})){let s=i?Yn.join(i,o.name):o.name;o.isDirectory()?r(Yn.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function STe(e){return Ms.readFileSync(Yn.join(e,"SKILL.md"),"utf8")}function Evt(e){let{runtime:t}=e;if(!wvt.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=yTe(t),n=e.home?Yn.join(e.home,Yn.relative(mj.homedir(),r.globalConfigPath)):r.globalConfigPath,i=ETe(r,n,dee());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function TTe(e){let t,r;if(e.dir)t=Yn.resolve(e.dir),r="custom";else if(e.runtime){let o=lee(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=bvt(e);t=o.base,r=o.runtime}let n=_vt({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:Evt({runtime:r,home:e.home});return{skill:b0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Ms,mj,Yn,b0,wvt,ITe=P(()=>{"use strict";Ms=Me(require("fs")),mj=Me(require("os")),Yn=Me(require("path"));ATe();b0="pair-visa-agent";wvt=["openclaw","hermes"]});function Avt(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function OTe(e,t=PTe.spawn){try{let{cmd:r,args:n}=Avt(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var PTe,CTe=P(()=>{"use strict";PTe=require("node:child_process")});function BTe(e=process.env){return e[Svt]==="true"}function A_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gj(e){return typeof e=="string"&&Tvt.test(e)}function mee(e){return typeof e=="string"&&Ivt.test(e)}function hj(e){return typeof e=="string"&&Pvt.test(e)}function bj(e){return typeof e=="string"&&Kh.includes(e)}function jTe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=Cvt&&!Rvt.test(e)}function Bvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function jvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function UTe(e){if(e.length===0||e.length>Ovt)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&jvt(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Uvt(e){if(typeof e!="string")return!1;try{return UTe(e)===e}catch{return!1}}function MTe(e){return A_(e)&&e.protocolVersion===kt&&gj(e.attachId)&&mee(e.agentId)&&Uvt(e.authUrl)&&e.capability===k4&&bj(e.rail)&&e.currency==="USD"&&hj(e.aggregateCeilingMicros)&&hj(e.perTransactionMicros)&&jTe(e.instrumentLabel)&&Sr(e.serverNonce)&&Sr(e.identityKeyJkt)&&Sr(e.claimToken)&&Bvt(e.createdAt)}function hee(e,t=lT){if(!gj(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return fee.join(t,`${e}.json`)}function Mvt(e){iy.mkdirSync(e,{recursive:!0,mode:448});let t=iy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");iy.chmodSync(e,448),Za(e)}function qvt(e,t=lT){if(!MTe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Mvt(t),g0(hee(e.attachId,t),JSON.stringify(e,null,2))}function yee(e,t=lT){if(!gj(e))return null;let r=E_(hee(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!MTe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function RTe(e,t=lT){yee(e,t)&&Za(t)&&iy.rmSync(hee(e,t),{force:!0})}function yj(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function pee(e,t){return t?t.aborted?Promise.reject(yj(t)):new Promise((r,n)=>{let i=()=>n(yj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function gee(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${kTe}ms`)),kTe);s.unref?.();try{if(i.signal.aborted)throw yj(i.signal);let a=await pee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":xvt,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await pee(a.json(),i.signal)}catch{if(i.signal.aborted)throw yj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=A_(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function qTe(e,t){return Buffer.from(w4(e,Buffer.from(t,"utf8"))).toString("base64url")}function DTe(e,t,r){let n=pT(e,r);if(!n||!Qp(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||Gp(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function LTe(e){let t=e.attachDir??lT,r=pT(e.agentId,e.agentDir);if(!r||!Qp(r))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let n=UTe(e.authUrl??r.auth_url??td());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let i=await e.createCall(e.agentId,{protocolVersion:kt,capability:k4,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!A_(i)||i.protocolVersion!==kt||!gj(i.attachId)||i.agentId!==e.agentId||i.state!=="attach_initiated"||i.capability!==k4||!bj(i.rail)||i.currency!=="USD"||!hj(i.aggregateCeilingMicros)||!hj(i.perTransactionMicros)||!jTe(i.instrumentLabel??null)||!Sr(i.serverNonce))throw new Error("capability-attach server returned an invalid create response");let o={protocolVersion:kt,attachId:i.attachId,agentId:e.agentId,authUrl:n,capability:k4,rail:i.rail,currency:"USD",aggregateCeilingMicros:i.aggregateCeilingMicros,perTransactionMicros:i.perTransactionMicros,instrumentLabel:i.instrumentLabel??null,serverNonce:i.serverNonce,identityKeyJkt:r.identity_key.jkt,claimToken:LB(),createdAt:new Date().toISOString()};return qvt(o,t),o}function Dvt(e,t,r){let n=qTe(r,Mxe({protocolVersion:kt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:l0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:kt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function zTe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=DTe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await gee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dvt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!A_(i)||i.protocolVersion!==kt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function Lvt(e,t){if(!A_(e)||e.protocolVersion!==kt||e.attachId!==t.attachId||e.agentId!==t.agentId||!bj(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==l0(t.claimToken)||!mee(e.ownerPublicId)||!Sr(e.grantHash)||!Sr(e.ceremonyHash)||!Sr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:kt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:l0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return OQ(r),r}async function zvt(e,t,r,n){let{status:i,body:o}=await gee(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!A_(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!kvt.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),Nvt.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=Lvt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function Hvt(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await zvt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&RTe(t.attachId,e.attachDir),a}if(!n)return null;let i=DTe(t.agentId,t.identityKeyJkt,e.agentDir),o=qTe(i.seed,OQ(n)),{body:s}=await gee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:kt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!A_(s)||s.protocolVersion!==kt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!bj(s.rail)||s.rail!==t.rail||!mee(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return RTe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function bee(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await Hvt({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await pee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var iy,NTe,fee,xvt,lT,Svt,Tvt,Ivt,Pvt,Ovt,Cvt,Rvt,k4,kvt,Nvt,kTe,HTe=P(()=>{"use strict";iy=Me(require("node:fs")),NTe=Me(require("node:os")),fee=Me(require("node:path"));p_();p4();eT();cT();oy();xvt="4.1.0-rc.52",lT=fee.join(NTe.homedir(),".visa-cli","capability-attach"),Svt="VISA_V4_CAPABILITY_ATTACH_ENABLED";Tvt=/^ca_[A-Za-z0-9_-]{24}$/,Ivt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Pvt=/^(0|[1-9][0-9]{0,17})$/,Ovt=2048,Cvt=255,Rvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,k4="card",kvt=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),Nvt=new Set(["failed","expired"]);kTe=3e4});var i7e={};Ei(i7e,{agentFilePath:()=>B4,agentFormatIsJson:()=>x_,attachAgentCommand:()=>n5t,attachPollOptsFromFlags:()=>Aee,claimOptsFromFlags:()=>N4,decodeBindingClaims:()=>j4,enrollClaimEnvelope:()=>t7e,formatUsdMicros:()=>mT,isAgentCommandEnabled:()=>e7e,isAgentRecord:()=>See,isAgentRecordV2:()=>Qp,isStoredAgentRecord:()=>Tee,listAgentFiles:()=>Ej,listLegacyAgentRecords:()=>Sj,loginClaimEnvelope:()=>r7e,loginClaimOptsFromFlags:()=>n7e,newestAgentRecord:()=>xj,newestAgentRecordV2:()=>ef,parseUsdToCents:()=>Eee,readAgent:()=>pT,renderGrantActivated:()=>xee,writeAgent:()=>Iee});function See(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function Vvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function $vt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function Kvt(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&$vt(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function Wvt(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!Fvt.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function Gvt(e,t){try{let r=l_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function FTe(e){if(e.length===0||e.length>wee)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function VTe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function Jvt(e){let t=FTe(e.activation_credentials.binding_jwt),r=FTe(e.activation_credentials.registration_jwt);return!t||!r||!VTe(t)||!VTe(r)?!1:t.v===kt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function QTe(e){return typeof e=="string"&&(vee.test(e)||Sr(e))}function fT(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Qp(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!fT(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==kt||typeof t.agent_id!="string"||!vee.test(t.agent_id)||typeof t.owner_public_id!="string"||!vee.test(t.owner_public_id)||!Wvt(t.display_name)||!t.identity_key||!fT(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!fT(t.identity_key.public_jwk??{},["kty","crv","x"])||!fT(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Sr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Sr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Sr(t.identity_key.private_jwk.x)||!Sr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!Gvt(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!fT(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>wee||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>wee||!t.delivery_artifact||!Kvt(t.auth_url)||!Vvt(t.created_at)||!Jvt(t))return!1;try{let r=JSON.parse(ZS(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Tee(e){return Qp(e)||See(e)}function e7e(){return!0}function x_(e){return e==="json"}function t7e(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function r7e(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function N4(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Eee(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function mT(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Aee(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=N4({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function xee(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${mT(e.aggregateCeilingMicros)} ceiling.
|
|
36
|
+
`}return id.mkdirSync(Vt.dirname(t),{recursive:!0}),id.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}var id,Vt,mTe,Bn,ivt,cvt,_Te,ATe=P(()=>{"use strict";id=Me(require("fs")),Vt=Me(require("path")),mTe=Me(require("os")),Bn=mTe.homedir(),ivt=["Claude_","Anthropic.ClaudeDesktop_"];cvt=[{id:"claude",displayName:"Claude Code",globalConfigPath:Vt.join(Bn,".claude.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:svt(),configKey:"mcpServers",detectPaths:avt(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Vt.join(Bn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Vt.join(Bn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Vt.join(Bn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:cee({win32:Vt.join(dT(),"Roo","mcp_settings.json"),posix:Vt.join(Bn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Vt.join(Bn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Vt.join(Bn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Vt.join(Bn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:cee({win32:Vt.join(dT(),"Zed","settings.json"),posix:Vt.join(Bn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:cee({win32:[Vt.join(dT(),"Zed")],posix:[Vt.join(Bn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Vt.join(Bn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Vt.join(Bn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Vt.join(Bn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Vt.join(Bn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Vt.join(Bn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Vt.join(Bn,".hermes")],postInstallHint:"Restart Hermes to connect."}];_Te="mcp_servers"});function lee(e,t={}){let r=t.home??mj.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return Yn.join(r,".openclaw","skills");case"hermes":return Yn.join(r,".hermes","skills");case"claude-code":case"claude":return Yn.join(r,".claude","skills");case"default":case"agentskills":return Yn.join(n,".agents","skills");default:return null}}function bvt(e={}){let t=e.home??mj.homedir(),r=[["openclaw",Yn.join(t,".openclaw")],["hermes",Yn.join(t,".hermes")],["claude-code",Yn.join(t,".claude")]];for(let[n,i]of r)if(Ms.existsSync(i))return{runtime:n,base:lee(n,e)};return{runtime:"default",base:lee("default",e)}}function xTe(e){let t=[Yn.join(e,"skills",b0),Yn.join(e,"..","skills",b0),Yn.join(e,"..","..","visa-cli-openclaw","skills",b0),Yn.join(e,"..","..","..","visa-cli-openclaw","skills",b0)];for(let r of t)if(Ms.existsSync(Yn.join(r,"SKILL.md")))return r;return null}function _vt(e){let{bundledDir:t,base:r,force:n}=e;if(!Ms.existsSync(Yn.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=Yn.join(r,b0),o=Ms.existsSync(i)&&Ms.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Ms.mkdirSync(r,{recursive:!0}),o&&Ms.rmSync(i,{recursive:!0,force:!0}),Ms.cpSync(t,i,{recursive:!0}),{installedDir:i,files:vvt(i),overwrote:o}}function vvt(e){let t=[],r=(n,i)=>{for(let o of Ms.readdirSync(n,{withFileTypes:!0})){let s=i?Yn.join(i,o.name):o.name;o.isDirectory()?r(Yn.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function STe(e){return Ms.readFileSync(Yn.join(e,"SKILL.md"),"utf8")}function Evt(e){let{runtime:t}=e;if(!wvt.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=yTe(t),n=e.home?Yn.join(e.home,Yn.relative(mj.homedir(),r.globalConfigPath)):r.globalConfigPath,i=ETe(r,n,dee());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function TTe(e){let t,r;if(e.dir)t=Yn.resolve(e.dir),r="custom";else if(e.runtime){let o=lee(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=bvt(e);t=o.base,r=o.runtime}let n=_vt({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:Evt({runtime:r,home:e.home});return{skill:b0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Ms,mj,Yn,b0,wvt,ITe=P(()=>{"use strict";Ms=Me(require("fs")),mj=Me(require("os")),Yn=Me(require("path"));ATe();b0="pair-visa-agent";wvt=["openclaw","hermes"]});function Avt(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function OTe(e,t=PTe.spawn){try{let{cmd:r,args:n}=Avt(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var PTe,CTe=P(()=>{"use strict";PTe=require("node:child_process")});function BTe(e=process.env){return e[Svt]==="true"}function A_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gj(e){return typeof e=="string"&&Tvt.test(e)}function mee(e){return typeof e=="string"&&Ivt.test(e)}function hj(e){return typeof e=="string"&&Pvt.test(e)}function bj(e){return typeof e=="string"&&Kh.includes(e)}function jTe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=Cvt&&!Rvt.test(e)}function Bvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function jvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function UTe(e){if(e.length===0||e.length>Ovt)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&jvt(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Uvt(e){if(typeof e!="string")return!1;try{return UTe(e)===e}catch{return!1}}function MTe(e){return A_(e)&&e.protocolVersion===kt&&gj(e.attachId)&&mee(e.agentId)&&Uvt(e.authUrl)&&e.capability===k4&&bj(e.rail)&&e.currency==="USD"&&hj(e.aggregateCeilingMicros)&&hj(e.perTransactionMicros)&&jTe(e.instrumentLabel)&&Sr(e.serverNonce)&&Sr(e.identityKeyJkt)&&Sr(e.claimToken)&&Bvt(e.createdAt)}function hee(e,t=lT){if(!gj(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return fee.join(t,`${e}.json`)}function Mvt(e){iy.mkdirSync(e,{recursive:!0,mode:448});let t=iy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");iy.chmodSync(e,448),Za(e)}function qvt(e,t=lT){if(!MTe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Mvt(t),g0(hee(e.attachId,t),JSON.stringify(e,null,2))}function yee(e,t=lT){if(!gj(e))return null;let r=E_(hee(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!MTe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function RTe(e,t=lT){yee(e,t)&&Za(t)&&iy.rmSync(hee(e,t),{force:!0})}function yj(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function pee(e,t){return t?t.aborted?Promise.reject(yj(t)):new Promise((r,n)=>{let i=()=>n(yj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function gee(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${kTe}ms`)),kTe);s.unref?.();try{if(i.signal.aborted)throw yj(i.signal);let a=await pee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":xvt,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await pee(a.json(),i.signal)}catch{if(i.signal.aborted)throw yj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=A_(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function qTe(e,t){return Buffer.from(w4(e,Buffer.from(t,"utf8"))).toString("base64url")}function DTe(e,t,r){let n=pT(e,r);if(!n||!Qp(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||Gp(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function LTe(e){let t=e.attachDir??lT,r=pT(e.agentId,e.agentDir);if(!r||!Qp(r))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let n=UTe(e.authUrl??r.auth_url??td());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let i=await e.createCall(e.agentId,{protocolVersion:kt,capability:k4,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!A_(i)||i.protocolVersion!==kt||!gj(i.attachId)||i.agentId!==e.agentId||i.state!=="attach_initiated"||i.capability!==k4||!bj(i.rail)||i.currency!=="USD"||!hj(i.aggregateCeilingMicros)||!hj(i.perTransactionMicros)||!jTe(i.instrumentLabel??null)||!Sr(i.serverNonce))throw new Error("capability-attach server returned an invalid create response");let o={protocolVersion:kt,attachId:i.attachId,agentId:e.agentId,authUrl:n,capability:k4,rail:i.rail,currency:"USD",aggregateCeilingMicros:i.aggregateCeilingMicros,perTransactionMicros:i.perTransactionMicros,instrumentLabel:i.instrumentLabel??null,serverNonce:i.serverNonce,identityKeyJkt:r.identity_key.jkt,claimToken:LB(),createdAt:new Date().toISOString()};return qvt(o,t),o}function Dvt(e,t,r){let n=qTe(r,Mxe({protocolVersion:kt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:l0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:kt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function zTe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=DTe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await gee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dvt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!A_(i)||i.protocolVersion!==kt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function Lvt(e,t){if(!A_(e)||e.protocolVersion!==kt||e.attachId!==t.attachId||e.agentId!==t.agentId||!bj(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==l0(t.claimToken)||!mee(e.ownerPublicId)||!Sr(e.grantHash)||!Sr(e.ceremonyHash)||!Sr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:kt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:l0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return OQ(r),r}async function zvt(e,t,r,n){let{status:i,body:o}=await gee(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!A_(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!kvt.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),Nvt.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=Lvt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function Hvt(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await zvt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&RTe(t.attachId,e.attachDir),a}if(!n)return null;let i=DTe(t.agentId,t.identityKeyJkt,e.agentDir),o=qTe(i.seed,OQ(n)),{body:s}=await gee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:kt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!A_(s)||s.protocolVersion!==kt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!bj(s.rail)||s.rail!==t.rail||!mee(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return RTe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function bee(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await Hvt({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await pee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var iy,NTe,fee,xvt,lT,Svt,Tvt,Ivt,Pvt,Ovt,Cvt,Rvt,k4,kvt,Nvt,kTe,HTe=P(()=>{"use strict";iy=Me(require("node:fs")),NTe=Me(require("node:os")),fee=Me(require("node:path"));p_();p4();eT();cT();oy();xvt="4.1.0-rc.53",lT=fee.join(NTe.homedir(),".visa-cli","capability-attach"),Svt="VISA_V4_CAPABILITY_ATTACH_ENABLED";Tvt=/^ca_[A-Za-z0-9_-]{24}$/,Ivt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Pvt=/^(0|[1-9][0-9]{0,17})$/,Ovt=2048,Cvt=255,Rvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,k4="card",kvt=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),Nvt=new Set(["failed","expired"]);kTe=3e4});var i7e={};Ei(i7e,{agentFilePath:()=>B4,agentFormatIsJson:()=>x_,attachAgentCommand:()=>n5t,attachPollOptsFromFlags:()=>Aee,claimOptsFromFlags:()=>N4,decodeBindingClaims:()=>j4,enrollClaimEnvelope:()=>t7e,formatUsdMicros:()=>mT,isAgentCommandEnabled:()=>e7e,isAgentRecord:()=>See,isAgentRecordV2:()=>Qp,isStoredAgentRecord:()=>Tee,listAgentFiles:()=>Ej,listLegacyAgentRecords:()=>Sj,loginClaimEnvelope:()=>r7e,loginClaimOptsFromFlags:()=>n7e,newestAgentRecord:()=>xj,newestAgentRecordV2:()=>ef,parseUsdToCents:()=>Eee,readAgent:()=>pT,renderGrantActivated:()=>xee,writeAgent:()=>Iee});function See(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function Vvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function $vt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function Kvt(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&$vt(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function Wvt(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!Fvt.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function Gvt(e,t){try{let r=l_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function FTe(e){if(e.length===0||e.length>wee)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function VTe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function Jvt(e){let t=FTe(e.activation_credentials.binding_jwt),r=FTe(e.activation_credentials.registration_jwt);return!t||!r||!VTe(t)||!VTe(r)?!1:t.v===kt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function QTe(e){return typeof e=="string"&&(vee.test(e)||Sr(e))}function fT(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Qp(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!fT(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==kt||typeof t.agent_id!="string"||!vee.test(t.agent_id)||typeof t.owner_public_id!="string"||!vee.test(t.owner_public_id)||!Wvt(t.display_name)||!t.identity_key||!fT(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!fT(t.identity_key.public_jwk??{},["kty","crv","x"])||!fT(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Sr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Sr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Sr(t.identity_key.private_jwk.x)||!Sr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!Gvt(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!fT(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>wee||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>wee||!t.delivery_artifact||!Kvt(t.auth_url)||!Vvt(t.created_at)||!Jvt(t))return!1;try{let r=JSON.parse(ZS(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Tee(e){return Qp(e)||See(e)}function e7e(){return!0}function x_(e){return e==="json"}function t7e(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function r7e(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function N4(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Eee(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function mT(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Aee(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=N4({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function xee(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${mT(e.aggregateCeilingMicros)} ceiling.
|
|
37
37
|
Rail: ${e.rail}
|
|
38
38
|
Per transaction: ${mT(e.perTransactionMicros)}
|
|
39
39
|
Grant: ${e.grantId} (v${e.grantVersion})
|
|
@@ -177,7 +177,7 @@ Full request-key fingerprint to compare exactly: ${n.identityKeyJkt}
|
|
|
177
177
|
`:`Agent not found: ${r}
|
|
178
178
|
`),process.exitCode=1;return}if(Qp(n)){let o=j4(n.activation_credentials.binding_jwt);process.stdout.write([`agent id: ${n.agent_id}`,`name: ${n.display_name}`,`owner id: ${n.owner_public_id}`,`key fingerprint: ${n.identity_key.jkt} (Ed25519, runtime custody)`,`created: ${n.created_at}`,`auth server: ${n.auth_url}`,`pairing: ${n.pairing_id}`,`status: ${n.pairing_status}`,`key file: ${B4(n.agent_id)}`,"key custody: exportable owner-only runtime file (mode 0600; macOS/Linux)","key recovery: unavailable; copying transfers identity proof and loss blocks new proofs","binding claims (decoded locally, NOT verified):",o?JSON.stringify(o,null,2):" (stored binding is malformed)",""].join(`
|
|
179
179
|
`));return}let i=n.binding_jwt?j4(n.binding_jwt):null;process.stdout.write(["record: legacy v1 (key-addressed; no stable agent id)",`key jkt: ${n.agent_jkt}`,`name: ${n.name}`,`created: ${n.created_at}`,`auth server: ${n.auth_url}`,`pairing: ${n.pairing_id}`,`status: ${n.pairing_status}`,`public key: ${n.public_key_jwk.x} (Ed25519, OKP)`,"registration: stored",`key file: ${B4(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
|
|
180
|
-
`))})}var tf,XTe,sy,_ee,cy,vee,wee,Fvt,oy=P(()=>{"use strict";tf=Me(require("fs")),XTe=Me(require("os")),sy=Me(require("path")),_ee=require("node:readline/promises");p_();sQ();gB();cT();pj();pTe();ITe();CTe();Pj();HTe();WX();h4();cy=sy.join(XTe.homedir(),".visa-cli","agents");vee=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,wee=32768,Fvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var jee={};Ei(jee,{SUBWAY_PROTOCOL:()=>h7e,registerDirect:()=>y5t,resolveDirect:()=>g5t});function Ree(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function sd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function kee(e,t){return e<<3|t}function _T(e,t,r){e.push(kee(t,2)),Ree(e,r.length);for(let n of r)e.push(n)}function i5t(e,t){let r=[];return _T(r,1,Cee.encode(e)),t&&t.length>0&&_T(r,2,Cee.encode(t)),Uint8Array.from(r)}function o5t(e,t,r){let n=[];return r!==0n&&(n.push(kee(1,0)),Ree(n,r)),_T(n,2,i5t(e,t)),Uint8Array.from(n)}function s5t(e){let t=[];return _T(t,1,Cee.encode(e)),Uint8Array.from(t)}function a5t(e,t){let r=[];return t!==0n&&(r.push(kee(1,0)),Ree(r,t)),_T(r,3,s5t(e)),Uint8Array.from(r)}function c5t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=sd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.error=f7e.decode(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function u5t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.error=f7e.decode(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function Nee(e,t,r){if(r===0)return sd(e,t)[1];if(r===2){let[n,i]=sd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function m7e(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=sd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.registerNameResponse=c5t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=u5t(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function d5t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Bee(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function l5t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Bee(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:m7e(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function p5t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Bee(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:m7e(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Oee(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function h5t(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>o7e)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Bee(Oee(t).subarray(0,4)),n>o7e))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Oee(t).subarray(0,n)}return Oee(t)}async function y7e(e){return(0,s7e.createLibp2p)({...e?{privateKey:await(0,d7e.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,a7e.tcp)()],connectionEncrypters:[(0,c7e.noise)()],streamMuxers:[(0,u7e.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function g7e(e,t,r){let n=await e.dialProtocol((0,l7e.multiaddr)(t),h7e,{signal:AbortSignal.timeout(f5t)});n.send(d5t(r));let i;return Promise.race([h5t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),m5t)})]).finally(()=>clearTimeout(i))}async function y5t(e){let t=await y7e(e.seed);try{let r=await g7e(t,e.relayMultiaddr,o5t(e.name,e.binding,e.requestId??1n)),n=l5t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function g5t(e){let t=await y7e(e.seed);try{let r=await g7e(t,e.relayMultiaddr,a5t(e.name,e.requestId??1n)),n=p5t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,p7e.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var s7e,a7e,c7e,u7e,d7e,l7e,p7e,Cee,f7e,h7e,f5t,m5t,o7e,Uee=P(()=>{"use strict";kQ();s7e=require("libp2p"),a7e=require("@libp2p/tcp"),c7e=require("@chainsafe/libp2p-noise"),u7e=require("@chainsafe/libp2p-yamux"),d7e=require("@libp2p/crypto/keys"),l7e=require("@multiformats/multiaddr"),p7e=require("uint8arrays/to-string"),Cee=new TextEncoder,f7e=new TextDecoder;h7e="/subway/p2p/1.0.0",f5t=15e3,m5t=15e3,o7e=1<<20});var wT={};Ei(wT,{DEFAULT_VISA_RELAY_MULTIADDR:()=>b7e,MESH:()=>Eo,RELAY_URL:()=>zee,connectOrThrow:()=>kj,ensureMailbox:()=>Jee,hydrateInbox:()=>S7e,isSubwayEnabled:()=>Hee,listRegistered:()=>w5t,loadBindingFor:()=>$ee,loadRegistry:()=>T_,makeClient:()=>Rj,meshName:()=>rf,pairedVisaBinding:()=>E7e,pairedVisaBindingForIdentity:()=>A7e,persistInbox:()=>Gee,readInbox:()=>T5t,registerName:()=>Kee,resolveActingName:()=>b5t,resolveMeshName:()=>_5t,seedSubwayKeyFromExactIdentity:()=>w7e,seedSubwayKeyFromTapAgent:()=>v7e,sendMessage:()=>v5t,sendVia:()=>I5t,subwayKeyPath:()=>Vee,visaRelayMultiaddr:()=>Lee});function Lee(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??b7e}function rf(e){return e.includes(".")?e:`${e}.${Eo}`}function Hee(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function Fee(){qs.mkdirSync(U4,{recursive:!0,mode:448})}function _7e(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Vee(e){return vT.join(U4,`${_7e(e)}.key`)}function T_(){if(!qs.existsSync(Dee))return{};try{return JSON.parse(qs.readFileSync(Dee,"utf8"))}catch{return{}}}function Mee(e){Fee(),qs.writeFileSync(Dee,JSON.stringify(e,null,2),{mode:384})}function qee(){try{return Cj.userInfo().username}catch{return"local"}}function v7e(e){if(qs.existsSync(e))return null;let t=xj();if(!t)return null;try{let r=E4(t.private_key_jwk);return Fee(),qs.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function w7e(e,t){let r=E4(t.identityPrivateJwk);if(Gp(Gh(d_(r)))!==t.identityKeyJkt)throw new Wp("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(qs.existsSync(e)){if(Gp(Gh(d_(QS(e))))!==t.identityKeyJkt)throw new Wp("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return Fee(),qs.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function Rj(e,t={}){return new eTe({name:rf(e),url:zee,keyPath:Vee(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function $ee(e){if(Eo!=="visa")return;let t=T_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function kj(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${zee})`)),t))])}function b5t(e){if(e)return e;let t=Object.keys(T_());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function E7e(e,t=Date.now()){let r=xj();if(!r?.binding_jwt)return null;let n=j4(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function A7e(e,t,r=Date.now()){for(let n of Sj()){if(n.agent_jkt!==t)continue;let i=j4(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function Kee(e,t={}){let r=Vee(e),n=rf(e),i,o;if(t.exactIdentity){if(o=Eo==="visa"?A7e(n,t.exactIdentity.identityKeyJkt):null,Eo==="visa"&&!o)throw new Wp;i=w7e(r,t.exactIdentity)}else i=v7e(r),o=Eo==="visa"?E7e(n):null;let s,a={};if(o){if(!qs.existsSync(r))throw new Wp("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(Gp(Gh(d_(QS(r))))!==o.identityKeyJkt)throw new Wp("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Eo==="visa")throw new Wp;let c=Eo==="visa"?Lee():process.env.SUBWAY_RELAY_MULTIADDR;if(Eo==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(Uee(),jee)),l=await d({relayMultiaddr:c,seed:QS(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=T_();return p[e]={relayName:n,mesh:Eo,peerId:l.peerId,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(p),{relayName:n,mesh:Eo,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Eo==="visa"&&!process.env.SUBWAY_RELAY){let d=T_();return d[e]={relayName:n,mesh:Eo,peerId:null,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(d),{relayName:n,mesh:Eo,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=Rj(e,{autoReconnect:!1,binding:s});try{await kj(u);let d=T_();return d[e]={relayName:n,mesh:Eo,peerId:u.peerId,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(d),{relayName:n,mesh:Eo,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function _5t(e){let t=rf(e),r=Eo==="visa"?Lee():process.env.SUBWAY_RELAY_MULTIADDR;if(Eo==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Uee(),jee)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function v5t(e,t,r){let n=Rj(e,{autoReconnect:!1,binding:$ee(e)});try{await kj(n);let i=rf(t);return await n.sendSigned(i,"chat",r),{to:i,as:rf(e)}}finally{n.disconnect()}}function w5t(){let e=T_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function x7e(e,t=U4){return vT.join(t,`${_7e(e)}.inbox.json`)}function A5t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function S7e(e,t=U4){try{let r=JSON.parse(qs.readFileSync(x7e(e,t),"utf8"));return Array.isArray(r)?r.filter(A5t).slice(-Wee):[]}catch{return[]}}function Gee(e,t,r=U4){try{qs.mkdirSync(r,{recursive:!0,mode:448}),qs.writeFileSync(x7e(e,r),JSON.stringify(t.slice(-Wee),null,2),{mode:384})}catch{}}function x5t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Gee(e,t.buffer))},E5t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function S5t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Gee(e,t.buffer)}async function Jee(e){let t=Oj.get(e);if(t)return{relayName:rf(e),peerId:t.client.peerId};let r=Rj(e,{autoReconnect:!0,binding:$ee(e)}),n=S7e(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Wee&&n.shift(),x5t(e,i)}),Oj.set(e,i),await kj(r),{relayName:rf(e),peerId:r.peerId}}async function T5t(e,t=20,r=!1){await Jee(e);let n=Oj.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,S5t(e,n)),i}async function I5t(e,t,r){await Jee(e);let n=Oj.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=rf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:rf(e)}}var qs,Cj,vT,Eo,b7e,zee,U4,Dee,Oj,Wee,E5t,I_=P(()=>{"use strict";tTe();p_();qs=Me(require("fs")),Cj=Me(require("os")),vT=Me(require("path"));eT();oy();Eo=process.env.SUBWAY_MESH??"relay",b7e="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";zee=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";U4=vT.join(Cj.homedir(),".visa-cli","subway"),Dee=vT.join(U4,"registry.json");Oj=new Map,Wee=200,E5t=100});var z7e={};Ei(z7e,{PAIRING_DIR:()=>of,cancelPairing:()=>Pee,claimPairing:()=>S_,getPairingStatus:()=>Ij,initiatePairing:()=>bT,latestPendingHumanPairing:()=>vj,latestPendingRuntimePairing:()=>Dj,pairingFilePath:()=>qj,pollAndActivatePairing:()=>wj,readPendingPairing:()=>od,registerOnVisaMeshIfEnabled:()=>Tj,removePendingPairing:()=>gT,tryActivatePairing:()=>ite,verifyPairing:()=>ay,writePendingPairing:()=>nte});async function Tj(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await Kee(e),!0}catch(t){return Ne.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function Xa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Xee(e){return typeof e=="string"&&C5t.test(e)}function M4(e){return typeof e=="string"&&R5t.test(e)}function ET(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function k7e(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function Bj(e){if(typeof e!="string"||e.length===0||e.length>R7e)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&k7e(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function Mj(e){if(e.length===0||e.length>R7e)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&k7e(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Qee(e){if(typeof e!="string")return!1;try{return Mj(e)===e}catch{return!1}}function B5t(e){return Xa(e)&&nf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)}function j5t(e){return Xa(e)&&nf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)&&Sr(e.d)}function U5t(e,t){try{let r=l_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function Nj(e,t){if(typeof e!="string"||k5t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function N7e(e){if(!Xa(e)||!nf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=Nj(e.runtime,100),r=Nj(e.contextLabel,200),n=e.cliVersion===void 0?void 0:Nj(e.cliVersion,64),i=e.platform===void 0?void 0:Nj(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function M5t(e){if(!Xa(e))return!1;let t=N7e(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function B7e(e){return Xa(e)?nf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===kt&&M4(e.pairingId)&&Xee(e.agentId)&&Sr(e.verifier)&&Qee(e.authUrl)&&Bj(e.skillUrl)&&ET(e.expiresAt)&&ET(e.createdAt):!1}function j7e(e){return!Xa(e)||!nf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==kt||!M4(e.pairingId)||!Xee(e.agentId)||!Qee(e.authUrl)||!Sr(e.claimToken)||!Sr(e.serverNonce)||!Sr(e.identityKeyJkt)||!B5t(e.identityPublicJwk)||!j5t(e.identityPrivateJwk)||!M5t(e.runtime)||!ET(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&Gp(e.identityPublicJwk)===e.identityKeyJkt&&U5t(e.identityPrivateJwk,e.identityPublicJwk)}function q5t(e){return Xa(e)&&nf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===kt&&Sr(e.verifier)&&Qee(e.authUrl)&&ET(e.createdAt)}function AT(e,t,r){if(!Xa(e)||e.protocolVersion!==kt||!M4(e.pairingId)||!Xee(e.agentId)||typeof e.state!="string"||!N5t.has(e.state)||!ET(e.expiresAt)||e.skillUrl!==void 0&&!Bj(e.skillUrl)||e.authorizationUrl!==void 0&&!Bj(e.authorizationUrl)||e.serverNonce!==void 0&&!Sr(e.serverNonce)||e.authApiUrl!==void 0&&!Bj(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function qj(e,t,r=of){if(!M4(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return Uj.join(r,`${e}.${t}.json`)}function U7e(e){Il.mkdirSync(e,{recursive:!0,mode:448});let t=Il.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Il.chmodSync(e,448),Za(e)}function ete(e){return Uj.join(e,P5t)}function tte(e){let t=E_(ete(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!q5t(r))throw new Error("local pairing initiation state is invalid");return r}function D5t(e,t){U7e(t),g0(ete(t),JSON.stringify(e,null,2))}function T7e(e,t){let r=tte(t);if(!r)return;let n=od(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&rte(t)}function rte(e){tte(e)&&Za(e)&&Il.rmSync(ete(e),{force:!0})}function nte(e,t=of){if(!(e.role==="human"?B7e(e):j7e(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");U7e(t);let n=qj(e.pairingId,e.role,t);g0(n,JSON.stringify(e,null,2))}function gT(e,t,r=of){od(e,t,r)&&Za(r)&&Il.rmSync(qj(e,t,r),{force:!0})}function Yee(e,t=of){gT(e,"human",t),gT(e,"runtime",t),rte(t)}function od(e,t,r=of){if(!M4(e))return null;let n=E_(qj(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!B7e(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!j7e(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function M7e(e,t){return Za(t)?Il.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!M4(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return od(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function vj(e=of){return M7e("human",e)}function Dj(e=of){return M7e("runtime",e)}function jj(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Zee(e,t){return t?t.aborted?Promise.reject(jj(t)):new Promise((r,n)=>{let i=()=>n(jj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function P_(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${I7e}ms`)),I7e);s.unref?.();try{if(i.signal.aborted)throw jj(i.signal);let a=await Zee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":C7e,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Zee(a.json(),i.signal)}catch{if(i.signal.aborted)throw jj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=Xa(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function bT(e={}){let t=Mj(e.authUrl??td()),r=e.pairingDir??of,n=tte(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<O5t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:kt,verifier:Nxe(),authUrl:t,createdAt:new Date().toISOString()};o||D5t(s,r);let a=s.verifier,{body:c}=await P_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,cliChallenge:Bxe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(AT(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:kt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:YX(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return nte(u,r),e.retainInitiationDraft||rte(r),u}function q7e(e){return e.authorizationUrl?{...e,authorizationUrl:YX(e.authorizationUrl)}:e}async function ay(e){let{pairing:t}=e,{body:r}=await P_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return AT(r,t.pairingId,t.agentId),q7e(r)}async function Ij(e){let t=Mj(e.authUrl??td()),{body:r}=await P_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return AT(r,e.pairingId,e.expectedAgentId),q7e(r)}function D7e(e,t){return Buffer.from(w4(e,Buffer.from(t,"utf8"))).toString("base64url")}function L5t(e){let t=D7e(Buffer.from(e.identityPrivateJwk.d,"base64url"),PQ({protocolVersion:kt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:l0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:kt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function P7e(e,t,r){let{body:n}=await P_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L5t(e))},t,{signal:r}),i=n;if(!Xa(i)||!nf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==kt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==zB(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function S_(e){let t=Mj(e.authUrl??td()),r=e.fetchImpl??fetch,n=e.pairingDir??of,i=N7e({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:C7e});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=od(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return T7e(o.pairingId,n),P7e(o,r,e.signal)}let s=await Ij({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Sr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=Axe(),c=l_(a.secretKey),u=Gh(a.publicKey),d=Gp(u),l=i,p=LB();PQ({protocolVersion:kt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:l0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:kt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return nte(f,n),T7e(f.pairingId,n),P7e(f,r,e.signal)}async function L7e(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await P_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(AT(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw Yee(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!Xa(r)||!nf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==kt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!Xa(r.artifact)||!Sr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=ZS(r.artifact),o=JSON.parse(i),s=qxe(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=D7e(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),Uxe({protocolVersion:kt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:l0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await P_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:kt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!Xa(d)||!nf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==kt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!Xa(d.credentials)||!nf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:kt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Iee)(l,e.agentDir),Yee(e.pending.pairingId,e.pairingDir);let p=await Tj(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ne.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function ite(e){return L7e(e)}async function wj(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await L7e({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Zee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Pee(e){let{pairing:t}=e,{body:r}=await P_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return AT(r,t.pairingId,t.agentId),r.state==="cancelled"&&Yee(t.pairingId,e.pairingDir),r}var Il,O7e,Uj,C7e,of,P5t,O5t,C5t,R5t,k5t,N5t,R7e,I7e,Pj=P(()=>{"use strict";Il=Me(require("node:fs")),O7e=Me(require("node:os")),Uj=Me(require("node:path"));p_();p4();gB();xl();eT();I_();cT();oy();C7e="4.1.0-rc.52",of=Uj.join(O7e.homedir(),".visa-cli","pairings"),P5t=".initiation.v2.json",O5t=15*6e4,C5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,R5t=/^ap_[A-Za-z0-9_-]{24}$/,k5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,N5t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),R7e=2048;I7e=3e4});function H7e(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function z5t(e,t){return t?t.aborted?Promise.reject(H7e(t)):new Promise((r,n)=>{let i=()=>n(H7e(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function H5t(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function F7e(e,t){if(t!==void 0&&H5t(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function F5t(e){return{status:"activated",protocolVersion:kt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function hT(e={}){let t=Dj(e.pairingDir);if(t){F7e(t.authUrl,e.authUrl);let s=od(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await S_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await ay({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:kt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await bT({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await S_({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await ay({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:kt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function V5t(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function yT(e={}){let t=Dj(e.pairingDir);if(!t)return{status:"no_pending"};let r=od(t.pairingId,"human",e.pairingDir);try{F7e(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await ite({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return F5t(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await S_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await ay({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await z5t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:kt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:V5t(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function fTe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await Ya.saveSessionToken(e),!0}catch{return!1}}var pj=P(()=>{"use strict";p_();h4();Pj()});var pte={};Ei(pte,{CardDrawRefusedError:()=>C_,cardDrawIntentHash:()=>nIe,decimalUsdToCents:()=>lte,fetchCardDrawVerdict:()=>lwt,loadCardMandateCapability:()=>dwt,registerCardMandate:()=>pwt});function owt(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return(0,dte.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function swt(e){let{secretKey:t,publicKey:r}=xxe(e),n=l_(t),i=Gh(r);return{privateJwk:n,publicJwk:i,jkt:owt(i)}}async function tIe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:iwt},o=`${Q7e(i)}.${Q7e(n)}`,s=E4(e.privateJwk),a=w4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function rIe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!awt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:cwt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,dte.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function uwt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function lte(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function nIe(e,t){let r=lte(e.amount);return r===null?null:rIe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function dwt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(oy(),ie(i7e)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=uwt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=swt(E4(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function Fj(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${eIe}ms`)),eIe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function iIe(e){return e.replace(/\/+$/,"")}async function lwt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=iIe(e.authBaseUrl),i=nIe(e.draw,e.drawId);if(i===null)throw new C_(400,["invalid_amount"]);let o=await Fj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new C_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new C_(502,["challenge_malformed"]);let a=await tIe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await Fj(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new C_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function pwt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=iIe(e.authBaseUrl),i=lte(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=rIe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await Fj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await tIe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await Fj(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var dte,iwt,Q7e,awt,cwt,C_,eIe,fte=P(()=>{"use strict";dte=require("node:crypto");p_();iwt="visa-agent-pop+jwt",Q7e=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");awt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),cwt=1;C_=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},eIe=3e4});var EPe=g(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.formatCents=wPe;kl.formatUsd=y3t;kl.formatMicros=cU;kl.formatMicrosWire=g3t;kl.formatTxAmount=b3t;kl.formatDate=_3t;kl.formatRelativeTime=v3t;kl.formatTime=w3t;kl.formatAge=E3t;var vPe=1e6,h3t=100;function wPe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/h3t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function y3t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function cU(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/vPe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function g3t(e,t,r={}){return e&&/^-?\d+$/.test(e)?cU(e,r):t!=null&&Number.isFinite(t)?wPe(t,r):r.fallback??"\u2014"}function b3t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return cU(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?cU(n*vPe,t):t.fallback??"\u2014"}function _3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function v3t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?t8(n,i,a,"minute"):c<24?t8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?t8(n,i,u,"day"):d<4?t8(n,i,d,"week"):l<12?t8(n,i,l,"month"):t8(n,i,p,"year")}function t8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function w3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function E3t(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var r8=g(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.formatAge=Yt.formatTime=Yt.formatRelativeTime=Yt.formatDate=Yt.formatTxAmount=Yt.formatMicrosWire=Yt.formatMicros=Yt.formatUsd=Yt.formatCents=void 0;Yt.micros=A3t;Yt.fromCents=x3t;Yt.fromUsdc=S3t;Yt.fromUsd=T3t;Yt.toCents=I3t;Yt.toCentsForAcquirer=P3t;Yt.toUsdc=O3t;Yt.toWire=C3t;Yt.fromWire=R3t;Yt.toDisplay=k3t;Yt.toUsdRounded2dp=N3t;Yt.add=B3t;Yt.sub=j3t;Yt.clampNonNegative=U3t;Yt.isNonNegative=M3t;Yt.max=q3t;Yt.min=D3t;var S0=10000n,APe=1000000n;function A3t(e){return e}function x3t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*S0}function S3t(e){return e}function T3t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function I3t(e){if(e>=0n)return Number(e/S0);let t=e/S0,r=e%S0;return Number(r===0n?t:t-1n)}function P3t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/S0)}function O3t(e){return e}function C3t(e){return e.toString()}function R3t(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function k3t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/APe,a=o%APe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function N3t(e){let t=e<0n,r=t?-e:e,n=r/S0,o=r%S0*2n,s;o<S0?s=n:o>S0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function B3t(e,t){return e+t}function j3t(e,t){return e-t}function U3t(e){return e<0n?0n:e}function M3t(e){return e>=0n}function q3t(e,t){return e>t?e:t}function D3t(e,t){return e<t?e:t}var T0=EPe();Object.defineProperty(Yt,"formatCents",{enumerable:!0,get:function(){return T0.formatCents}});Object.defineProperty(Yt,"formatUsd",{enumerable:!0,get:function(){return T0.formatUsd}});Object.defineProperty(Yt,"formatMicros",{enumerable:!0,get:function(){return T0.formatMicros}});Object.defineProperty(Yt,"formatMicrosWire",{enumerable:!0,get:function(){return T0.formatMicrosWire}});Object.defineProperty(Yt,"formatTxAmount",{enumerable:!0,get:function(){return T0.formatTxAmount}});Object.defineProperty(Yt,"formatDate",{enumerable:!0,get:function(){return T0.formatDate}});Object.defineProperty(Yt,"formatRelativeTime",{enumerable:!0,get:function(){return T0.formatRelativeTime}});Object.defineProperty(Yt,"formatTime",{enumerable:!0,get:function(){return T0.formatTime}});Object.defineProperty(Yt,"formatAge",{enumerable:!0,get:function(){return T0.formatAge}})});var Ute=g(tc=>{"use strict";var L3t=tc&&tc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),z3t=tc&&tc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),SPe=tc&&tc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&L3t(r,t,n[i]);return z3t(r,t),r}})();Object.defineProperty(tc,"__esModule",{value:!0});tc.pruneResponsesDir=jte;tc.isTextualContentType=uU;tc.isValidUtf8=IPe;tc.spillFilename=PPe;tc.describePaidBody=Nte;tc.capturePaidResponse=W3t;var df=SPe(require("fs")),zT=SPe(require("path")),H3t=require("node:crypto"),TPe=16*1024,kte=2*1024,F3t=64*1024*1024,V3t=3e4,Bte=256*1024*1024;function jte(e,t=Bte,r){try{let n=r?zT.basename(r):null,i=df.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=df.statSync(zT.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{df.rmSync(zT.join(e,s.name),{force:!0})}catch{}}catch{}}var $3t=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function uU(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||$3t.has(t)}function IPe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var K3t={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function PPe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=K3t[o]??(uU(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function OPe(e,t,r){let n=PPe(t,r,new Date),i=zT.extname(n),o=n.slice(0,n.length-i.length);return zT.join(e,`${o}-${(0,H3t.randomBytes)(8).toString("hex")}${i}`)}function CPe(e){df.mkdirSync(e,{recursive:!0,mode:448})}function xPe(e,t){let r=0;for(;r<t.length;){let n=df.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function Nte(e,t,r,n,i){let o=r?uU(r):IPe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=TPe)return{...s,body:n.toString("utf-8")};CPe(i);let a=OPe(i,e,r);return df.writeFileSync(a,n,{flag:"wx",mode:384}),jte(i,Bte,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,kte).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function W3t(e,t,r,n={}){let i=n.maxBytes??F3t,o=n.timeoutMs??V3t;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return Nte(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(df.closeSync(p),p=null)},E=()=>{if(v(),m)try{df.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((O,M)=>{x=setTimeout(()=>M(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),C;try{C=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(C.done)break;let T=Buffer.from(C.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<kte){let O=T.subarray(0,Math.min(T.length,kte-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=TPe)continue;CPe(r),f=OPe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=df.openSync(m,"wx",384);for(let O of u)xPe(p,O);u.length=0,d=0}else xPe(p,T)}if(p===null){let A=Buffer.concat(u,d);return Nte(e,t.status,t.headers.get("content-type"),A,r)}v(),df.renameSync(m,f),m=null,jte(r,Bte,f);let _=t.headers.get("content-type"),w=_?uU(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var hy=g(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TURNKEY_API_BASE_URL_ENV=oo.CIRCLE_TESTNET_FAUCET_URL=oo.NETWORK_ENV=oo.NETWORKS=void 0;oo.resolveNetwork=G3t;oo.turnkeyApiBaseUrl=Y3t;oo.explorerTxUrl=Z3t;oo.explorerAddressUrl=X3t;oo.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};oo.NETWORK_ENV="VISA_V4_NETWORK";oo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var RPe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function G3t(e=process.env){let t=(e[oo.NETWORK_ENV]??"").trim();if(t==="")return oo.NETWORKS["base-mainnet"];let r=RPe[t.toLowerCase()];if(!r)throw new Error(`unknown ${oo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(RPe).join(", "));return oo.NETWORKS[r]}oo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var J3t="https://api.turnkey.com";function Y3t(e=process.env){let t=(e[oo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?J3t:t}function Z3t(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function X3t(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var kPe=g(dU=>{"use strict";Object.defineProperty(dU,"__esModule",{value:!0});dU.version=void 0;dU.version="1.2.3"});var G_=g(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0});lU.BaseError=void 0;var Q3t=kPe(),Mte=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Q3t.version}`].join(`
|
|
180
|
+
`))})}var tf,XTe,sy,_ee,cy,vee,wee,Fvt,oy=P(()=>{"use strict";tf=Me(require("fs")),XTe=Me(require("os")),sy=Me(require("path")),_ee=require("node:readline/promises");p_();sQ();gB();cT();pj();pTe();ITe();CTe();Pj();HTe();WX();h4();cy=sy.join(XTe.homedir(),".visa-cli","agents");vee=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,wee=32768,Fvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var jee={};Ei(jee,{SUBWAY_PROTOCOL:()=>h7e,registerDirect:()=>y5t,resolveDirect:()=>g5t});function Ree(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function sd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function kee(e,t){return e<<3|t}function _T(e,t,r){e.push(kee(t,2)),Ree(e,r.length);for(let n of r)e.push(n)}function i5t(e,t){let r=[];return _T(r,1,Cee.encode(e)),t&&t.length>0&&_T(r,2,Cee.encode(t)),Uint8Array.from(r)}function o5t(e,t,r){let n=[];return r!==0n&&(n.push(kee(1,0)),Ree(n,r)),_T(n,2,i5t(e,t)),Uint8Array.from(n)}function s5t(e){let t=[];return _T(t,1,Cee.encode(e)),Uint8Array.from(t)}function a5t(e,t){let r=[];return t!==0n&&(r.push(kee(1,0)),Ree(r,t)),_T(r,3,s5t(e)),Uint8Array.from(r)}function c5t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=sd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.error=f7e.decode(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function u5t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.error=f7e.decode(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function Nee(e,t,r){if(r===0)return sd(e,t)[1];if(r===2){let[n,i]=sd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function m7e(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=sd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=sd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.registerNameResponse=c5t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=sd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=u5t(e.subarray(u,d)),t=d}else t=Nee(e,t,s)}return r}function d5t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Bee(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function l5t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Bee(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:m7e(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function p5t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Bee(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:m7e(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Oee(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function h5t(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>o7e)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Bee(Oee(t).subarray(0,4)),n>o7e))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Oee(t).subarray(0,n)}return Oee(t)}async function y7e(e){return(0,s7e.createLibp2p)({...e?{privateKey:await(0,d7e.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,a7e.tcp)()],connectionEncrypters:[(0,c7e.noise)()],streamMuxers:[(0,u7e.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function g7e(e,t,r){let n=await e.dialProtocol((0,l7e.multiaddr)(t),h7e,{signal:AbortSignal.timeout(f5t)});n.send(d5t(r));let i;return Promise.race([h5t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),m5t)})]).finally(()=>clearTimeout(i))}async function y5t(e){let t=await y7e(e.seed);try{let r=await g7e(t,e.relayMultiaddr,o5t(e.name,e.binding,e.requestId??1n)),n=l5t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function g5t(e){let t=await y7e(e.seed);try{let r=await g7e(t,e.relayMultiaddr,a5t(e.name,e.requestId??1n)),n=p5t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,p7e.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var s7e,a7e,c7e,u7e,d7e,l7e,p7e,Cee,f7e,h7e,f5t,m5t,o7e,Uee=P(()=>{"use strict";kQ();s7e=require("libp2p"),a7e=require("@libp2p/tcp"),c7e=require("@chainsafe/libp2p-noise"),u7e=require("@chainsafe/libp2p-yamux"),d7e=require("@libp2p/crypto/keys"),l7e=require("@multiformats/multiaddr"),p7e=require("uint8arrays/to-string"),Cee=new TextEncoder,f7e=new TextDecoder;h7e="/subway/p2p/1.0.0",f5t=15e3,m5t=15e3,o7e=1<<20});var wT={};Ei(wT,{DEFAULT_VISA_RELAY_MULTIADDR:()=>b7e,MESH:()=>Eo,RELAY_URL:()=>zee,connectOrThrow:()=>kj,ensureMailbox:()=>Jee,hydrateInbox:()=>S7e,isSubwayEnabled:()=>Hee,listRegistered:()=>w5t,loadBindingFor:()=>$ee,loadRegistry:()=>T_,makeClient:()=>Rj,meshName:()=>rf,pairedVisaBinding:()=>E7e,pairedVisaBindingForIdentity:()=>A7e,persistInbox:()=>Gee,readInbox:()=>T5t,registerName:()=>Kee,resolveActingName:()=>b5t,resolveMeshName:()=>_5t,seedSubwayKeyFromExactIdentity:()=>w7e,seedSubwayKeyFromTapAgent:()=>v7e,sendMessage:()=>v5t,sendVia:()=>I5t,subwayKeyPath:()=>Vee,visaRelayMultiaddr:()=>Lee});function Lee(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??b7e}function rf(e){return e.includes(".")?e:`${e}.${Eo}`}function Hee(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function Fee(){qs.mkdirSync(U4,{recursive:!0,mode:448})}function _7e(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Vee(e){return vT.join(U4,`${_7e(e)}.key`)}function T_(){if(!qs.existsSync(Dee))return{};try{return JSON.parse(qs.readFileSync(Dee,"utf8"))}catch{return{}}}function Mee(e){Fee(),qs.writeFileSync(Dee,JSON.stringify(e,null,2),{mode:384})}function qee(){try{return Cj.userInfo().username}catch{return"local"}}function v7e(e){if(qs.existsSync(e))return null;let t=xj();if(!t)return null;try{let r=E4(t.private_key_jwk);return Fee(),qs.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function w7e(e,t){let r=E4(t.identityPrivateJwk);if(Gp(Gh(d_(r)))!==t.identityKeyJkt)throw new Wp("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(qs.existsSync(e)){if(Gp(Gh(d_(QS(e))))!==t.identityKeyJkt)throw new Wp("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return Fee(),qs.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function Rj(e,t={}){return new eTe({name:rf(e),url:zee,keyPath:Vee(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function $ee(e){if(Eo!=="visa")return;let t=T_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function kj(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${zee})`)),t))])}function b5t(e){if(e)return e;let t=Object.keys(T_());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function E7e(e,t=Date.now()){let r=xj();if(!r?.binding_jwt)return null;let n=j4(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function A7e(e,t,r=Date.now()){for(let n of Sj()){if(n.agent_jkt!==t)continue;let i=j4(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function Kee(e,t={}){let r=Vee(e),n=rf(e),i,o;if(t.exactIdentity){if(o=Eo==="visa"?A7e(n,t.exactIdentity.identityKeyJkt):null,Eo==="visa"&&!o)throw new Wp;i=w7e(r,t.exactIdentity)}else i=v7e(r),o=Eo==="visa"?E7e(n):null;let s,a={};if(o){if(!qs.existsSync(r))throw new Wp("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(Gp(Gh(d_(QS(r))))!==o.identityKeyJkt)throw new Wp("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Eo==="visa")throw new Wp;let c=Eo==="visa"?Lee():process.env.SUBWAY_RELAY_MULTIADDR;if(Eo==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(Uee(),jee)),l=await d({relayMultiaddr:c,seed:QS(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=T_();return p[e]={relayName:n,mesh:Eo,peerId:l.peerId,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(p),{relayName:n,mesh:Eo,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Eo==="visa"&&!process.env.SUBWAY_RELAY){let d=T_();return d[e]={relayName:n,mesh:Eo,peerId:null,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(d),{relayName:n,mesh:Eo,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=Rj(e,{autoReconnect:!1,binding:s});try{await kj(u);let d=T_();return d[e]={relayName:n,mesh:Eo,peerId:u.peerId,owner:qee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Mee(d),{relayName:n,mesh:Eo,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function _5t(e){let t=rf(e),r=Eo==="visa"?Lee():process.env.SUBWAY_RELAY_MULTIADDR;if(Eo==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Uee(),jee)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function v5t(e,t,r){let n=Rj(e,{autoReconnect:!1,binding:$ee(e)});try{await kj(n);let i=rf(t);return await n.sendSigned(i,"chat",r),{to:i,as:rf(e)}}finally{n.disconnect()}}function w5t(){let e=T_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function x7e(e,t=U4){return vT.join(t,`${_7e(e)}.inbox.json`)}function A5t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function S7e(e,t=U4){try{let r=JSON.parse(qs.readFileSync(x7e(e,t),"utf8"));return Array.isArray(r)?r.filter(A5t).slice(-Wee):[]}catch{return[]}}function Gee(e,t,r=U4){try{qs.mkdirSync(r,{recursive:!0,mode:448}),qs.writeFileSync(x7e(e,r),JSON.stringify(t.slice(-Wee),null,2),{mode:384})}catch{}}function x5t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Gee(e,t.buffer))},E5t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function S5t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Gee(e,t.buffer)}async function Jee(e){let t=Oj.get(e);if(t)return{relayName:rf(e),peerId:t.client.peerId};let r=Rj(e,{autoReconnect:!0,binding:$ee(e)}),n=S7e(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Wee&&n.shift(),x5t(e,i)}),Oj.set(e,i),await kj(r),{relayName:rf(e),peerId:r.peerId}}async function T5t(e,t=20,r=!1){await Jee(e);let n=Oj.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,S5t(e,n)),i}async function I5t(e,t,r){await Jee(e);let n=Oj.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=rf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:rf(e)}}var qs,Cj,vT,Eo,b7e,zee,U4,Dee,Oj,Wee,E5t,I_=P(()=>{"use strict";tTe();p_();qs=Me(require("fs")),Cj=Me(require("os")),vT=Me(require("path"));eT();oy();Eo=process.env.SUBWAY_MESH??"relay",b7e="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";zee=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";U4=vT.join(Cj.homedir(),".visa-cli","subway"),Dee=vT.join(U4,"registry.json");Oj=new Map,Wee=200,E5t=100});var z7e={};Ei(z7e,{PAIRING_DIR:()=>of,cancelPairing:()=>Pee,claimPairing:()=>S_,getPairingStatus:()=>Ij,initiatePairing:()=>bT,latestPendingHumanPairing:()=>vj,latestPendingRuntimePairing:()=>Dj,pairingFilePath:()=>qj,pollAndActivatePairing:()=>wj,readPendingPairing:()=>od,registerOnVisaMeshIfEnabled:()=>Tj,removePendingPairing:()=>gT,tryActivatePairing:()=>ite,verifyPairing:()=>ay,writePendingPairing:()=>nte});async function Tj(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await Kee(e),!0}catch(t){return Ne.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function Xa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Xee(e){return typeof e=="string"&&C5t.test(e)}function M4(e){return typeof e=="string"&&R5t.test(e)}function ET(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function k7e(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function Bj(e){if(typeof e!="string"||e.length===0||e.length>R7e)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&k7e(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function Mj(e){if(e.length===0||e.length>R7e)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&k7e(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Qee(e){if(typeof e!="string")return!1;try{return Mj(e)===e}catch{return!1}}function B5t(e){return Xa(e)&&nf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)}function j5t(e){return Xa(e)&&nf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)&&Sr(e.d)}function U5t(e,t){try{let r=l_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function Nj(e,t){if(typeof e!="string"||k5t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function N7e(e){if(!Xa(e)||!nf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=Nj(e.runtime,100),r=Nj(e.contextLabel,200),n=e.cliVersion===void 0?void 0:Nj(e.cliVersion,64),i=e.platform===void 0?void 0:Nj(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function M5t(e){if(!Xa(e))return!1;let t=N7e(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function B7e(e){return Xa(e)?nf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===kt&&M4(e.pairingId)&&Xee(e.agentId)&&Sr(e.verifier)&&Qee(e.authUrl)&&Bj(e.skillUrl)&&ET(e.expiresAt)&&ET(e.createdAt):!1}function j7e(e){return!Xa(e)||!nf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==kt||!M4(e.pairingId)||!Xee(e.agentId)||!Qee(e.authUrl)||!Sr(e.claimToken)||!Sr(e.serverNonce)||!Sr(e.identityKeyJkt)||!B5t(e.identityPublicJwk)||!j5t(e.identityPrivateJwk)||!M5t(e.runtime)||!ET(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&Gp(e.identityPublicJwk)===e.identityKeyJkt&&U5t(e.identityPrivateJwk,e.identityPublicJwk)}function q5t(e){return Xa(e)&&nf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===kt&&Sr(e.verifier)&&Qee(e.authUrl)&&ET(e.createdAt)}function AT(e,t,r){if(!Xa(e)||e.protocolVersion!==kt||!M4(e.pairingId)||!Xee(e.agentId)||typeof e.state!="string"||!N5t.has(e.state)||!ET(e.expiresAt)||e.skillUrl!==void 0&&!Bj(e.skillUrl)||e.authorizationUrl!==void 0&&!Bj(e.authorizationUrl)||e.serverNonce!==void 0&&!Sr(e.serverNonce)||e.authApiUrl!==void 0&&!Bj(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function qj(e,t,r=of){if(!M4(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return Uj.join(r,`${e}.${t}.json`)}function U7e(e){Il.mkdirSync(e,{recursive:!0,mode:448});let t=Il.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Il.chmodSync(e,448),Za(e)}function ete(e){return Uj.join(e,P5t)}function tte(e){let t=E_(ete(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!q5t(r))throw new Error("local pairing initiation state is invalid");return r}function D5t(e,t){U7e(t),g0(ete(t),JSON.stringify(e,null,2))}function T7e(e,t){let r=tte(t);if(!r)return;let n=od(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&rte(t)}function rte(e){tte(e)&&Za(e)&&Il.rmSync(ete(e),{force:!0})}function nte(e,t=of){if(!(e.role==="human"?B7e(e):j7e(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");U7e(t);let n=qj(e.pairingId,e.role,t);g0(n,JSON.stringify(e,null,2))}function gT(e,t,r=of){od(e,t,r)&&Za(r)&&Il.rmSync(qj(e,t,r),{force:!0})}function Yee(e,t=of){gT(e,"human",t),gT(e,"runtime",t),rte(t)}function od(e,t,r=of){if(!M4(e))return null;let n=E_(qj(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!B7e(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!j7e(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function M7e(e,t){return Za(t)?Il.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!M4(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return od(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function vj(e=of){return M7e("human",e)}function Dj(e=of){return M7e("runtime",e)}function jj(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Zee(e,t){return t?t.aborted?Promise.reject(jj(t)):new Promise((r,n)=>{let i=()=>n(jj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function P_(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${I7e}ms`)),I7e);s.unref?.();try{if(i.signal.aborted)throw jj(i.signal);let a=await Zee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":C7e,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Zee(a.json(),i.signal)}catch{if(i.signal.aborted)throw jj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=Xa(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function bT(e={}){let t=Mj(e.authUrl??td()),r=e.pairingDir??of,n=tte(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<O5t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:kt,verifier:Nxe(),authUrl:t,createdAt:new Date().toISOString()};o||D5t(s,r);let a=s.verifier,{body:c}=await P_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,cliChallenge:Bxe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(AT(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:kt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:YX(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return nte(u,r),e.retainInitiationDraft||rte(r),u}function q7e(e){return e.authorizationUrl?{...e,authorizationUrl:YX(e.authorizationUrl)}:e}async function ay(e){let{pairing:t}=e,{body:r}=await P_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return AT(r,t.pairingId,t.agentId),q7e(r)}async function Ij(e){let t=Mj(e.authUrl??td()),{body:r}=await P_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return AT(r,e.pairingId,e.expectedAgentId),q7e(r)}function D7e(e,t){return Buffer.from(w4(e,Buffer.from(t,"utf8"))).toString("base64url")}function L5t(e){let t=D7e(Buffer.from(e.identityPrivateJwk.d,"base64url"),PQ({protocolVersion:kt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:l0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:kt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function P7e(e,t,r){let{body:n}=await P_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L5t(e))},t,{signal:r}),i=n;if(!Xa(i)||!nf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==kt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==zB(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function S_(e){let t=Mj(e.authUrl??td()),r=e.fetchImpl??fetch,n=e.pairingDir??of,i=N7e({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:C7e});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=od(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return T7e(o.pairingId,n),P7e(o,r,e.signal)}let s=await Ij({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Sr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=Axe(),c=l_(a.secretKey),u=Gh(a.publicKey),d=Gp(u),l=i,p=LB();PQ({protocolVersion:kt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:l0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:kt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return nte(f,n),T7e(f.pairingId,n),P7e(f,r,e.signal)}async function L7e(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await P_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(AT(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw Yee(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!Xa(r)||!nf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==kt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!Xa(r.artifact)||!Sr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=ZS(r.artifact),o=JSON.parse(i),s=qxe(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=D7e(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),Uxe({protocolVersion:kt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:l0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await P_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:kt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!Xa(d)||!nf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==kt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!Xa(d.credentials)||!nf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:kt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Iee)(l,e.agentDir),Yee(e.pending.pairingId,e.pairingDir);let p=await Tj(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ne.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function ite(e){return L7e(e)}async function wj(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await L7e({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Zee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Pee(e){let{pairing:t}=e,{body:r}=await P_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:kt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return AT(r,t.pairingId,t.agentId),r.state==="cancelled"&&Yee(t.pairingId,e.pairingDir),r}var Il,O7e,Uj,C7e,of,P5t,O5t,C5t,R5t,k5t,N5t,R7e,I7e,Pj=P(()=>{"use strict";Il=Me(require("node:fs")),O7e=Me(require("node:os")),Uj=Me(require("node:path"));p_();p4();gB();xl();eT();I_();cT();oy();C7e="4.1.0-rc.53",of=Uj.join(O7e.homedir(),".visa-cli","pairings"),P5t=".initiation.v2.json",O5t=15*6e4,C5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,R5t=/^ap_[A-Za-z0-9_-]{24}$/,k5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,N5t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),R7e=2048;I7e=3e4});function H7e(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function z5t(e,t){return t?t.aborted?Promise.reject(H7e(t)):new Promise((r,n)=>{let i=()=>n(H7e(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function H5t(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function F7e(e,t){if(t!==void 0&&H5t(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function F5t(e){return{status:"activated",protocolVersion:kt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function hT(e={}){let t=Dj(e.pairingDir);if(t){F7e(t.authUrl,e.authUrl);let s=od(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await S_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await ay({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:kt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await bT({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await S_({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await ay({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:kt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function V5t(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function yT(e={}){let t=Dj(e.pairingDir);if(!t)return{status:"no_pending"};let r=od(t.pairingId,"human",e.pairingDir);try{F7e(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await ite({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return F5t(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await S_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await ay({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await z5t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:kt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:V5t(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function fTe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await Ya.saveSessionToken(e),!0}catch{return!1}}var pj=P(()=>{"use strict";p_();h4();Pj()});var pte={};Ei(pte,{CardDrawRefusedError:()=>C_,cardDrawIntentHash:()=>nIe,decimalUsdToCents:()=>lte,fetchCardDrawVerdict:()=>lwt,loadCardMandateCapability:()=>dwt,registerCardMandate:()=>pwt});function owt(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return(0,dte.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function swt(e){let{secretKey:t,publicKey:r}=xxe(e),n=l_(t),i=Gh(r);return{privateJwk:n,publicJwk:i,jkt:owt(i)}}async function tIe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:iwt},o=`${Q7e(i)}.${Q7e(n)}`,s=E4(e.privateJwk),a=w4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function rIe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!awt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:cwt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,dte.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function uwt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function lte(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function nIe(e,t){let r=lte(e.amount);return r===null?null:rIe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function dwt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(oy(),ie(i7e)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=uwt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=swt(E4(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function Fj(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${eIe}ms`)),eIe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function iIe(e){return e.replace(/\/+$/,"")}async function lwt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=iIe(e.authBaseUrl),i=nIe(e.draw,e.drawId);if(i===null)throw new C_(400,["invalid_amount"]);let o=await Fj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new C_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new C_(502,["challenge_malformed"]);let a=await tIe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await Fj(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new C_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function pwt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=iIe(e.authBaseUrl),i=lte(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=rIe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await Fj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await tIe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await Fj(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var dte,iwt,Q7e,awt,cwt,C_,eIe,fte=P(()=>{"use strict";dte=require("node:crypto");p_();iwt="visa-agent-pop+jwt",Q7e=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");awt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),cwt=1;C_=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},eIe=3e4});var EPe=g(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.formatCents=wPe;kl.formatUsd=y3t;kl.formatMicros=cU;kl.formatMicrosWire=g3t;kl.formatTxAmount=b3t;kl.formatDate=_3t;kl.formatRelativeTime=v3t;kl.formatTime=w3t;kl.formatAge=E3t;var vPe=1e6,h3t=100;function wPe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/h3t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function y3t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function cU(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/vPe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function g3t(e,t,r={}){return e&&/^-?\d+$/.test(e)?cU(e,r):t!=null&&Number.isFinite(t)?wPe(t,r):r.fallback??"\u2014"}function b3t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return cU(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?cU(n*vPe,t):t.fallback??"\u2014"}function _3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function v3t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?t8(n,i,a,"minute"):c<24?t8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?t8(n,i,u,"day"):d<4?t8(n,i,d,"week"):l<12?t8(n,i,l,"month"):t8(n,i,p,"year")}function t8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function w3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function E3t(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var r8=g(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.formatAge=Yt.formatTime=Yt.formatRelativeTime=Yt.formatDate=Yt.formatTxAmount=Yt.formatMicrosWire=Yt.formatMicros=Yt.formatUsd=Yt.formatCents=void 0;Yt.micros=A3t;Yt.fromCents=x3t;Yt.fromUsdc=S3t;Yt.fromUsd=T3t;Yt.toCents=I3t;Yt.toCentsForAcquirer=P3t;Yt.toUsdc=O3t;Yt.toWire=C3t;Yt.fromWire=R3t;Yt.toDisplay=k3t;Yt.toUsdRounded2dp=N3t;Yt.add=B3t;Yt.sub=j3t;Yt.clampNonNegative=U3t;Yt.isNonNegative=M3t;Yt.max=q3t;Yt.min=D3t;var S0=10000n,APe=1000000n;function A3t(e){return e}function x3t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*S0}function S3t(e){return e}function T3t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function I3t(e){if(e>=0n)return Number(e/S0);let t=e/S0,r=e%S0;return Number(r===0n?t:t-1n)}function P3t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/S0)}function O3t(e){return e}function C3t(e){return e.toString()}function R3t(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function k3t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/APe,a=o%APe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function N3t(e){let t=e<0n,r=t?-e:e,n=r/S0,o=r%S0*2n,s;o<S0?s=n:o>S0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function B3t(e,t){return e+t}function j3t(e,t){return e-t}function U3t(e){return e<0n?0n:e}function M3t(e){return e>=0n}function q3t(e,t){return e>t?e:t}function D3t(e,t){return e<t?e:t}var T0=EPe();Object.defineProperty(Yt,"formatCents",{enumerable:!0,get:function(){return T0.formatCents}});Object.defineProperty(Yt,"formatUsd",{enumerable:!0,get:function(){return T0.formatUsd}});Object.defineProperty(Yt,"formatMicros",{enumerable:!0,get:function(){return T0.formatMicros}});Object.defineProperty(Yt,"formatMicrosWire",{enumerable:!0,get:function(){return T0.formatMicrosWire}});Object.defineProperty(Yt,"formatTxAmount",{enumerable:!0,get:function(){return T0.formatTxAmount}});Object.defineProperty(Yt,"formatDate",{enumerable:!0,get:function(){return T0.formatDate}});Object.defineProperty(Yt,"formatRelativeTime",{enumerable:!0,get:function(){return T0.formatRelativeTime}});Object.defineProperty(Yt,"formatTime",{enumerable:!0,get:function(){return T0.formatTime}});Object.defineProperty(Yt,"formatAge",{enumerable:!0,get:function(){return T0.formatAge}})});var Ute=g(tc=>{"use strict";var L3t=tc&&tc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),z3t=tc&&tc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),SPe=tc&&tc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&L3t(r,t,n[i]);return z3t(r,t),r}})();Object.defineProperty(tc,"__esModule",{value:!0});tc.pruneResponsesDir=jte;tc.isTextualContentType=uU;tc.isValidUtf8=IPe;tc.spillFilename=PPe;tc.describePaidBody=Nte;tc.capturePaidResponse=W3t;var df=SPe(require("fs")),zT=SPe(require("path")),H3t=require("node:crypto"),TPe=16*1024,kte=2*1024,F3t=64*1024*1024,V3t=3e4,Bte=256*1024*1024;function jte(e,t=Bte,r){try{let n=r?zT.basename(r):null,i=df.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=df.statSync(zT.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{df.rmSync(zT.join(e,s.name),{force:!0})}catch{}}catch{}}var $3t=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function uU(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||$3t.has(t)}function IPe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var K3t={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function PPe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=K3t[o]??(uU(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function OPe(e,t,r){let n=PPe(t,r,new Date),i=zT.extname(n),o=n.slice(0,n.length-i.length);return zT.join(e,`${o}-${(0,H3t.randomBytes)(8).toString("hex")}${i}`)}function CPe(e){df.mkdirSync(e,{recursive:!0,mode:448})}function xPe(e,t){let r=0;for(;r<t.length;){let n=df.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function Nte(e,t,r,n,i){let o=r?uU(r):IPe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=TPe)return{...s,body:n.toString("utf-8")};CPe(i);let a=OPe(i,e,r);return df.writeFileSync(a,n,{flag:"wx",mode:384}),jte(i,Bte,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,kte).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function W3t(e,t,r,n={}){let i=n.maxBytes??F3t,o=n.timeoutMs??V3t;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return Nte(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(df.closeSync(p),p=null)},E=()=>{if(v(),m)try{df.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((O,M)=>{x=setTimeout(()=>M(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),C;try{C=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(C.done)break;let T=Buffer.from(C.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<kte){let O=T.subarray(0,Math.min(T.length,kte-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=TPe)continue;CPe(r),f=OPe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=df.openSync(m,"wx",384);for(let O of u)xPe(p,O);u.length=0,d=0}else xPe(p,T)}if(p===null){let A=Buffer.concat(u,d);return Nte(e,t.status,t.headers.get("content-type"),A,r)}v(),df.renameSync(m,f),m=null,jte(r,Bte,f);let _=t.headers.get("content-type"),w=_?uU(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var hy=g(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TURNKEY_API_BASE_URL_ENV=oo.CIRCLE_TESTNET_FAUCET_URL=oo.NETWORK_ENV=oo.NETWORKS=void 0;oo.resolveNetwork=G3t;oo.turnkeyApiBaseUrl=Y3t;oo.explorerTxUrl=Z3t;oo.explorerAddressUrl=X3t;oo.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};oo.NETWORK_ENV="VISA_V4_NETWORK";oo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var RPe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function G3t(e=process.env){let t=(e[oo.NETWORK_ENV]??"").trim();if(t==="")return oo.NETWORKS["base-mainnet"];let r=RPe[t.toLowerCase()];if(!r)throw new Error(`unknown ${oo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(RPe).join(", "));return oo.NETWORKS[r]}oo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var J3t="https://api.turnkey.com";function Y3t(e=process.env){let t=(e[oo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?J3t:t}function Z3t(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function X3t(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var kPe=g(dU=>{"use strict";Object.defineProperty(dU,"__esModule",{value:!0});dU.version=void 0;dU.version="1.2.3"});var G_=g(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0});lU.BaseError=void 0;var Q3t=kPe(),Mte=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Q3t.version}`].join(`
|
|
181
181
|
`);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};lU.BaseError=Mte});var NPe=g(qte=>{"use strict";Object.defineProperty(qte,"__esModule",{value:!0});qte.narrow=eEt;function eEt(e){return e}});var HT=g(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.isTupleRegex=I0.integerRegex=I0.bytesRegex=void 0;I0.execTyped=tEt;function tEt(e,t){return e.exec(t)?.groups}I0.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;I0.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;I0.isTupleRegex=/^\(.+?\).*?$/});var zte=g(Lte=>{"use strict";Object.defineProperty(Lte,"__esModule",{value:!0});Lte.formatAbiParameter=Dte;var rEt=HT(),BPe=/^tuple(?<array>(\[(\d*)\])*)$/;function Dte(e){let t=e.type;if(BPe.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=Dte(o),i<r-1&&(t+=", ")}let n=(0,rEt.execTyped)(BPe,e.type);return t+=`)${n?.array||""}`,Dte({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var Fte=g(Hte=>{"use strict";Object.defineProperty(Hte,"__esModule",{value:!0});Hte.formatAbiParameters=iEt;var nEt=zte();function iEt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,nEt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var $te=g(Vte=>{"use strict";Object.defineProperty(Vte,"__esModule",{value:!0});Vte.formatAbiItem=oEt;var FT=Fte();function oEt(e){return e.type==="function"?`function ${e.name}(${(0,FT.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,FT.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,FT.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,FT.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,FT.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var jPe=g(Kte=>{"use strict";Object.defineProperty(Kte,"__esModule",{value:!0});Kte.formatAbi=aEt;var sEt=$te();function aEt(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,sEt.formatAbiItem)(i);t.push(o)}return t}});var J_=g(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.functionModifiers=Ai.eventModifiers=Ai.modifiers=void 0;Ai.isErrorSignature=cEt;Ai.execErrorSignature=uEt;Ai.isEventSignature=dEt;Ai.execEventSignature=lEt;Ai.isFunctionSignature=pEt;Ai.execFunctionSignature=fEt;Ai.isStructSignature=mEt;Ai.execStructSignature=hEt;Ai.isConstructorSignature=yEt;Ai.execConstructorSignature=gEt;Ai.isFallbackSignature=bEt;Ai.execFallbackSignature=_Et;Ai.isReceiveSignature=wEt;var n8=HT(),UPe=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function cEt(e){return UPe.test(e)}function uEt(e){return(0,n8.execTyped)(UPe,e)}var MPe=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function dEt(e){return MPe.test(e)}function lEt(e){return(0,n8.execTyped)(MPe,e)}var qPe=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function pEt(e){return qPe.test(e)}function fEt(e){return(0,n8.execTyped)(qPe,e)}var DPe=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function mEt(e){return DPe.test(e)}function hEt(e){return(0,n8.execTyped)(DPe,e)}var LPe=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function yEt(e){return LPe.test(e)}function gEt(e){return(0,n8.execTyped)(LPe,e)}var zPe=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function bEt(e){return zPe.test(e)}function _Et(e){return(0,n8.execTyped)(zPe,e)}var vEt=/^receive\(\) external payable$/;function wEt(e){return vEt.test(e)}Ai.modifiers=new Set(["memory","indexed","storage","calldata"]);Ai.eventModifiers=new Set(["indexed"]);Ai.functionModifiers=new Set(["calldata","memory","storage"])});var VT=g(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});yy.UnknownSolidityTypeError=yy.UnknownTypeError=yy.InvalidAbiItemError=void 0;var Yte=G_(),Wte=class extends Yte.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};yy.InvalidAbiItemError=Wte;var Gte=class extends Yte.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};yy.UnknownTypeError=Gte;var Jte=class extends Yte.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};yy.UnknownSolidityTypeError=Jte});var i8=g(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.InvalidAbiTypeParameterError=Ls.InvalidFunctionModifierError=Ls.InvalidModifierError=Ls.SolidityProtectedKeywordError=Ls.InvalidParameterError=Ls.InvalidAbiParametersError=Ls.InvalidAbiParameterError=void 0;var Y_=G_(),Zte=class extends Y_.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};Ls.InvalidAbiParameterError=Zte;var Xte=class extends Y_.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};Ls.InvalidAbiParametersError=Xte;var Qte=class extends Y_.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};Ls.InvalidParameterError=Qte;var ere=class extends Y_.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};Ls.SolidityProtectedKeywordError=ere;var tre=class extends Y_.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};Ls.InvalidModifierError=tre;var rre=class extends Y_.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};Ls.InvalidFunctionModifierError=rre;var nre=class extends Y_.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};Ls.InvalidAbiTypeParameterError=nre});var pU=g(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});gy.InvalidStructSignatureError=gy.UnknownSignatureError=gy.InvalidSignatureError=void 0;var are=G_(),ire=class extends are.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};gy.InvalidSignatureError=ire;var ore=class extends are.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};gy.UnknownSignatureError=ore;var sre=class extends are.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};gy.InvalidStructSignatureError=sre});var ure=g(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0});fU.CircularReferenceError=void 0;var EEt=G_(),cre=class extends EEt.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};fU.CircularReferenceError=cre});var lre=g(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0});mU.InvalidParenthesisError=void 0;var AEt=G_(),dre=class extends AEt.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};mU.InvalidParenthesisError=dre});var HPe=g($T=>{"use strict";Object.defineProperty($T,"__esModule",{value:!0});$T.parameterCache=void 0;$T.getParameterCacheKey=xEt;function xEt(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}$T.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var X_=g(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.parseSignature=IEt;su.parseFunctionSignature=FPe;su.parseEventSignature=VPe;su.parseErrorSignature=$Pe;su.parseConstructorSignature=KPe;su.parseFallbackSignature=WPe;su.parseAbiParameter=Z_;su.splitParameters=fd;su.isSolidityType=GPe;su.isSolidityKeyword=JPe;su.isValidDataLocation=YPe;var o8=HT(),SEt=VT(),hU=i8(),s8=pU(),TEt=lre(),yU=HPe(),ya=J_();function IEt(e,t={}){if((0,ya.isFunctionSignature)(e))return FPe(e,t);if((0,ya.isEventSignature)(e))return VPe(e,t);if((0,ya.isErrorSignature)(e))return $Pe(e,t);if((0,ya.isConstructorSignature)(e))return KPe(e,t);if((0,ya.isFallbackSignature)(e))return WPe(e);if((0,ya.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new s8.UnknownSignatureError({signature:e})}function FPe(e,t={}){let r=(0,ya.execFunctionSignature)(e);if(!r)throw new s8.InvalidSignatureError({signature:e,type:"function"});let n=fd(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(Z_(n[a],{modifiers:ya.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=fd(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(Z_(a[u],{modifiers:ya.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function VPe(e,t={}){let r=(0,ya.execEventSignature)(e);if(!r)throw new s8.InvalidSignatureError({signature:e,type:"event"});let n=fd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Z_(n[s],{modifiers:ya.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function $Pe(e,t={}){let r=(0,ya.execErrorSignature)(e);if(!r)throw new s8.InvalidSignatureError({signature:e,type:"error"});let n=fd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Z_(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function KPe(e,t={}){let r=(0,ya.execConstructorSignature)(e);if(!r)throw new s8.InvalidSignatureError({signature:e,type:"constructor"});let n=fd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Z_(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function WPe(e){let t=(0,ya.execFallbackSignature)(e);if(!t)throw new s8.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var PEt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,OEt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,CEt=/^u?int$/;function Z_(e,t){let r=(0,yU.getParameterCacheKey)(e,t?.type,t?.structs);if(yU.parameterCache.has(r))return yU.parameterCache.get(r);let n=o8.isTupleRegex.test(e),i=(0,o8.execTyped)(n?OEt:PEt,e);if(!i)throw new hU.InvalidParameterError({param:e});if(i.name&&JPe(i.name))throw new hU.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=fd(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(Z_(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(CEt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!GPe(c))throw new SEt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new hU.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(ya.functionModifiers.has(i.modifier)&&!YPe(c,!!i.array))throw new hU.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return yU.parameterCache.set(r,d),d}function fd(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?fd(a,[...t,r.trim()]):fd(a,t,`${r}${s}`,n);case"(":return fd(a,t,`${r}${s}`,n+1);case")":return fd(a,t,`${r}${s}`,n-1);default:return fd(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new TEt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function GPe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||o8.bytesRegex.test(e)||o8.integerRegex.test(e)}var REt=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function JPe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||o8.bytesRegex.test(e)||o8.integerRegex.test(e)||REt.test(e)}function YPe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var KT=g(pre=>{"use strict";Object.defineProperty(pre,"__esModule",{value:!0});pre.parseStructs=jEt;var ZPe=HT(),kEt=VT(),NEt=i8(),XPe=pU(),BEt=ure(),QPe=J_(),eOe=X_();function jEt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,QPe.isStructSignature)(a))continue;let c=(0,QPe.execStructSignature)(a);if(!c)throw new XPe.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let p=0;p<l;p++){let m=u[p].trim();if(!m)continue;let h=(0,eOe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new XPe.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=tOe(c,t)}return n}var UEt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function tOe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(ZPe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,ZPe.execTyped)(UEt,s.type);if(!c?.type)throw new NEt.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new BEt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:tOe(t[d],t,new Set([...r,d]))})}else if((0,eOe.isSolidityType)(d))n.push(s);else throw new kEt.UnknownTypeError({type:d})}}return n}});var rOe=g(fre=>{"use strict";Object.defineProperty(fre,"__esModule",{value:!0});fre.parseAbi=LEt;var MEt=J_(),qEt=KT(),DEt=X_();function LEt(e){let t=(0,qEt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,MEt.isStructSignature)(o)||r.push((0,DEt.parseSignature)(o,t))}return r}});var iOe=g(mre=>{"use strict";Object.defineProperty(mre,"__esModule",{value:!0});mre.parseAbiItem=VEt;var zEt=VT(),HEt=J_(),FEt=KT(),nOe=X_();function VEt(e){let t;if(typeof e=="string")t=(0,nOe.parseSignature)(e);else{let r=(0,FEt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,HEt.isStructSignature)(o)){t=(0,nOe.parseSignature)(o,r);break}}}if(!t)throw new zEt.InvalidAbiItemError({signature:e});return t}});var sOe=g(yre=>{"use strict";Object.defineProperty(yre,"__esModule",{value:!0});yre.parseAbiParameter=WEt;var $Et=i8(),hre=J_(),KEt=KT(),oOe=X_();function WEt(e){let t;if(typeof e=="string")t=(0,oOe.parseAbiParameter)(e,{modifiers:hre.modifiers});else{let r=(0,KEt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,hre.isStructSignature)(o)){t=(0,oOe.parseAbiParameter)(o,{modifiers:hre.modifiers,structs:r});break}}}if(!t)throw new $Et.InvalidAbiParameterError({param:e});return t}});var uOe=g(bre=>{"use strict";Object.defineProperty(bre,"__esModule",{value:!0});bre.parseAbiParameters=YEt;var GEt=i8(),gre=J_(),JEt=KT(),aOe=X_(),cOe=X_();function YEt(e){let t=[];if(typeof e=="string"){let r=(0,aOe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,cOe.parseAbiParameter)(r[i],{modifiers:gre.modifiers}))}else{let r=(0,JEt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,gre.isStructSignature)(o))continue;let s=(0,aOe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,cOe.parseAbiParameter)(s[c],{modifiers:gre.modifiers,structs:r}))}}if(t.length===0)throw new GEt.InvalidAbiParametersError({params:e});return t}});var WT=g(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.CircularReferenceError=lt.InvalidParenthesisError=lt.UnknownSignatureError=lt.InvalidSignatureError=lt.InvalidStructSignatureError=lt.InvalidAbiParameterError=lt.InvalidAbiParametersError=lt.InvalidParameterError=lt.SolidityProtectedKeywordError=lt.InvalidModifierError=lt.InvalidFunctionModifierError=lt.InvalidAbiTypeParameterError=lt.UnknownSolidityTypeError=lt.InvalidAbiItemError=lt.UnknownTypeError=lt.parseAbiParameters=lt.parseAbiParameter=lt.parseAbiItem=lt.parseAbi=lt.formatAbiParameters=lt.formatAbiParameter=lt.formatAbiItem=lt.formatAbi=lt.narrow=lt.BaseError=void 0;var ZEt=G_();Object.defineProperty(lt,"BaseError",{enumerable:!0,get:function(){return ZEt.BaseError}});var XEt=NPe();Object.defineProperty(lt,"narrow",{enumerable:!0,get:function(){return XEt.narrow}});var QEt=jPe();Object.defineProperty(lt,"formatAbi",{enumerable:!0,get:function(){return QEt.formatAbi}});var eAt=$te();Object.defineProperty(lt,"formatAbiItem",{enumerable:!0,get:function(){return eAt.formatAbiItem}});var tAt=zte();Object.defineProperty(lt,"formatAbiParameter",{enumerable:!0,get:function(){return tAt.formatAbiParameter}});var rAt=Fte();Object.defineProperty(lt,"formatAbiParameters",{enumerable:!0,get:function(){return rAt.formatAbiParameters}});var nAt=rOe();Object.defineProperty(lt,"parseAbi",{enumerable:!0,get:function(){return nAt.parseAbi}});var iAt=iOe();Object.defineProperty(lt,"parseAbiItem",{enumerable:!0,get:function(){return iAt.parseAbiItem}});var oAt=sOe();Object.defineProperty(lt,"parseAbiParameter",{enumerable:!0,get:function(){return oAt.parseAbiParameter}});var sAt=uOe();Object.defineProperty(lt,"parseAbiParameters",{enumerable:!0,get:function(){return sAt.parseAbiParameters}});var _re=VT();Object.defineProperty(lt,"UnknownTypeError",{enumerable:!0,get:function(){return _re.UnknownTypeError}});Object.defineProperty(lt,"InvalidAbiItemError",{enumerable:!0,get:function(){return _re.InvalidAbiItemError}});Object.defineProperty(lt,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return _re.UnknownSolidityTypeError}});var Q_=i8();Object.defineProperty(lt,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return Q_.InvalidAbiTypeParameterError}});Object.defineProperty(lt,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return Q_.InvalidFunctionModifierError}});Object.defineProperty(lt,"InvalidModifierError",{enumerable:!0,get:function(){return Q_.InvalidModifierError}});Object.defineProperty(lt,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return Q_.SolidityProtectedKeywordError}});Object.defineProperty(lt,"InvalidParameterError",{enumerable:!0,get:function(){return Q_.InvalidParameterError}});Object.defineProperty(lt,"InvalidAbiParametersError",{enumerable:!0,get:function(){return Q_.InvalidAbiParametersError}});Object.defineProperty(lt,"InvalidAbiParameterError",{enumerable:!0,get:function(){return Q_.InvalidAbiParameterError}});var vre=pU();Object.defineProperty(lt,"InvalidStructSignatureError",{enumerable:!0,get:function(){return vre.InvalidStructSignatureError}});Object.defineProperty(lt,"InvalidSignatureError",{enumerable:!0,get:function(){return vre.InvalidSignatureError}});Object.defineProperty(lt,"UnknownSignatureError",{enumerable:!0,get:function(){return vre.UnknownSignatureError}});var aAt=lre();Object.defineProperty(lt,"InvalidParenthesisError",{enumerable:!0,get:function(){return aAt.InvalidParenthesisError}});var cAt=ure();Object.defineProperty(lt,"CircularReferenceError",{enumerable:!0,get:function(){return cAt.CircularReferenceError}})});var rr=g(wre=>{"use strict";Object.defineProperty(wre,"__esModule",{value:!0});wre.getAction=uAt;function uAt(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var lf=g(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0});gU.formatAbiItem=lAt;gU.formatAbiParams=Ere;var dAt=jn();function lAt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new dAt.InvalidDefinitionTypeError(e.type);return`${e.name}(${Ere(e.inputs,{includeName:t})})`}function Ere(e,{includeName:t=!1}={}){return e?e.map(r=>pAt(r,{includeName:t})).join(t?", ":","):""}function pAt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Ere(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var ns=g(Are=>{"use strict";Object.defineProperty(Are,"__esModule",{value:!0});Are.isHex=fAt;function fAt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var is=g(xre=>{"use strict";Object.defineProperty(xre,"__esModule",{value:!0});xre.size=hAt;var mAt=ns();function hAt(e){return(0,mAt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var dOe=g(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0});bU.version=void 0;bU.version="2.54.6"});var It=g(GT=>{"use strict";Object.defineProperty(GT,"__esModule",{value:!0});GT.BaseError=void 0;GT.setErrorConfig=yAt;var lOe=dOe(),_U={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${lOe.version}`};function yAt(e){_U=e}var Sre=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=_U.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],..._U.version?[`Version: ${_U.version}`]:[]].join(`
|
|
182
182
|
`);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=lOe.version}walk(t){return pOe(this,t)}};GT.BaseError=Sre;function pOe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?pOe(e.cause,t):t?null:e}});var jn=g(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.UnsupportedPackedAbiType=ut.InvalidDefinitionTypeError=ut.InvalidArrayError=ut.InvalidAbiDecodingTypeError=ut.InvalidAbiEncodingTypeError=ut.DecodeLogTopicsMismatch=ut.DecodeLogDataMismatch=ut.BytesSizeMismatchError=ut.AbiItemAmbiguityError=ut.AbiFunctionSignatureNotFoundError=ut.AbiFunctionOutputsNotFoundError=ut.AbiFunctionNotFoundError=ut.AbiEventNotFoundError=ut.AbiEventSignatureNotFoundError=ut.AbiEventSignatureEmptyTopicsError=ut.AbiErrorSignatureNotFoundError=ut.AbiErrorNotFoundError=ut.AbiErrorInputsNotFoundError=ut.AbiEncodingLengthMismatchError=ut.AbiEncodingBytesSizeMismatchError=ut.AbiEncodingArrayLengthMismatchError=ut.AbiDecodingZeroDataError=ut.AbiDecodingDataSizeTooSmallError=ut.AbiDecodingDataSizeInvalidError=ut.AbiConstructorParamsNotFoundError=ut.AbiConstructorNotFoundError=void 0;var JT=lf(),gAt=is(),an=It(),Tre=class extends an.BaseError{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
|
|
183
183
|
`),{docsPath:t,name:"AbiConstructorNotFoundError"})}};ut.AbiConstructorNotFoundError=Tre;var Ire=class extends an.BaseError{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
|
|
@@ -20825,7 +20825,7 @@ ${Object.entries(t).sort(([r],[n])=>Ymt(r,n)).map(([r,n])=>`${r}=${n}`).join(`
|
|
|
20825
20825
|
If building from source, run native/build-win.bat first.`);Yr.mkdirSync(Fh,{recursive:!0}),Yr.copyFileSync(e,c0);let t=SB(c0);return Yr.writeFileSync(x9e,t,{mode:384}),Yr.writeFileSync(A9e,E9e,{mode:384}),c0}async function Tbt(){return TB()?N9e():Sbt()}var Ibt="visa-cli",Pbt="attestation-key";async function Obt(e){let t=await Tbt(),r;try{r=(await xB(t,e,{timeout:6e4})).stdout}catch(n){r=n.stdout||"";let i=r.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(n.stderr?.toString().trim()||n.message||"Unknown error")}return xbt(r)}var S9e=!1;function Cbt(){if(!TB())return!1;try{return Yr.existsSync(c0)||k9e()!==null?!0:(S9e||(S9e=!0,Ne.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:c0,searchedPrebuiltPaths:R9e})),!1)}catch{return!1}}function B9e(){return bB()||Abt()?!0:TB()?Cbt():!1}async function j9e(){if(TB()){try{let e=await N9e();await xB(e,["delete-key"],{timeout:1e4})}catch{}return}if(await Hh())try{await xB("security",["delete-generic-password","-s",Ibt,"-a",Pbt],{timeout:5e3})}catch{}try{await Obt(["delete-key"])}catch{}}h4();xl();sQ();pj();oy();var yPe=require("child_process"),sU=Me(require("fs")),aU=Me(require("os")),gPe=Me(require("path"));var sf=Me(require("fs")),Lj=Me(require("os")),Pl=Me(require("path"));var $5t="# >>> visa-cli shell hud v2 >>>",K5t="# <<< visa-cli shell hud v2 <<<";function W5t(e){let t=e??process.env.SHELL;if(!t)return null;let r=Pl.basename(t.replace(/\\/g,"/")).toLowerCase();return r==="zsh"?"zsh":r==="bash"?"bash":r==="pwsh"||r==="pwsh.exe"||r==="powershell"||r==="powershell.exe"?"powershell":null}function G5t(e){let t=Q5t();if(e==="zsh")return Pl.join(t,".zshrc");if(e==="bash")return Pl.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return Pl.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function J5t(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function Y5t(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${V7e(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${V7e(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!J5t(a))return i;let l=d>0?e[d-1]:"";return o===`
|
|
20826
20826
|
`&&l!==`
|
|
20827
20827
|
`?`
|
|
20828
|
-
`:""})}function Z5t(e){return Y5t(e,$5t,K5t).trimEnd()}function X5t(e){return Z5t(e)!==e.trimEnd()}function zj(e=W5t()){if(!e)return!1;try{let t=G5t(e),r=sf.readFileSync(t,"utf-8");return X5t(r)}catch{return!1}}function V7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q5t(){let e=Lj.homedir();if(!e||!Pl.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Pl.resolve(e)}var GRr=1440*60*1e3;var ewt="# visa-cli-hud-v1";function $7e(e){return typeof e!="string"?!1:e.includes(ewt)?!0:e.includes("visa-cli")&&e.includes("statusline")}qX();p4();_B();var K7e="4.1.0-rc.52";function ote(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function twt(e,t,r){let n=process.env[e];if(n!==void 0)return{value:r==="opt-in"?n==="true":n!=="false",source:{kind:"env",var:e}};let i=KX(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function q4(e){return e==null?"\u2014":e?"yes":"no"}async function W7e(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(l){r=l?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=$X("auth.serverUrl"),s=td(),a=i!==void 0&&i!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};n.push({key:"auth.serverUrl",value:s,formatted:s,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),n.push({key:"account.enrolled",value:t?.enrolled??null,formatted:q4(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.login&&n.push({key:"account.principal",value:t.login,formatted:t.principalKind?`${t.login} (${t.principalKind})`:t.login,source:{kind:"server"},hint:"The identity your CLI session resolves on. Feature-flag access (checkout, mandate) is granted per this exact principal."}),t?.userId&&n.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=twt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:q4(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=dB(),d;if(process.env.VISA_CLI_NO_UPDATE_CHECK?d={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?d={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?d={kind:"env",var:"NODE_ENV"}:d={kind:"default"},n.push({key:"ui.updateCheck",value:!u,formatted:q4(!u),source:d}),n.push({key:"client.version",value:K7e,formatted:K7e,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=Dh();n.push({key:"dev.mockKeychain",value:p,formatted:q4(p),source:ote("VISA_MOCK_KEYCHAIN",!!l),hint:XX()});let f=process.env.VISA_MOCK_TOUCHID,m=bB();n.push({key:"dev.mockTouchid",value:m,formatted:q4(m),source:ote("VISA_MOCK_TOUCHID",!!f),hint:XX()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:q4(!!h),source:ote("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var hte=require("node:os"),TT=require("node:path"),IT=require("node:fs/promises"),sIe=require("node:fs"),aIe=require("node:url"),cIe=require("node:crypto");xl();var rwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function ste(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!rwt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var _0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function G7e(e){let t;try{t=new URL(e)}catch{throw new _0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new _0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}xl();var nwt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},J7e=300*1e3,ate={},cte=0,xT=null;function ute(){return xT||(xT=(async()=>{try{let e=await Ao.getFeatureFlags();ate=e&&e.flags||{},cte=Date.now()}catch(e){ate={},Ne.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{xT=null}})(),xT)}async function Y7e(){await ute()}function Z7e(){Date.now()-cte<J7e||ute()}async function O_(){Date.now()-cte<J7e||await ute()}function iu(e){let t=nwt[e];return t?ate[t]!==!0:!1}var X7e=require("node:crypto"),ST=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},Hj=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new ST(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??X7e.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function uIe(e){return[(0,TT.join)(e,"checkout-engine","index.js"),(0,TT.join)(e,"..","checkout-engine","index.js")]}function fwt(e,t=sIe.existsSync){return uIe(e).find(r=>t(r))??null}var Vj=null,dIe=async()=>{if(Vj)return Vj;let e=fwt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${uIe(__dirname).join(" and ")}).`);return Vj=(await import((0,aIe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await mwt(),cardMandateRegister:await hwt()}),Vj};async function mwt(){let e=await Promise.resolve().then(()=>(fte(),pte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function hwt(){let e=await Promise.resolve().then(()=>(fte(),pte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function yte(){return iu("pay_merchant")?(await O_(),iu("pay_merchant")):!1}var lIe=(0,TT.join)((0,hte.homedir)(),".visa-mcp","agent-credential.json"),pIe=(0,TT.join)((0,hte.homedir)(),".visa-mcp","contact.json"),fIe=new Hj;function PT(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var ywt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function mIe(e){return ywt.has(e)?e:null}async function $j(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?PT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0?e.amountMinor/100:null,payment_currency:mIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function oIe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?PT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:mIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function mte(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new _0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function hIe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=PT(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function yIe(e={},t={}){if(await(t.flagDisabled??yte)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??fIe).get(n);return o?hIe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function gIe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:GX()&&!process.env.VISA_VERIFY_WEB_URL?null:qh();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??yte)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??fIe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=G7e(e.url??"").toString(),c=mte(e.amount)}catch(C){if(C instanceof _0)return{success:!1,message:C.message};throw C}let d=t.credentialPath??lIe,l=t.contactPath??pIe;try{await(0,IT.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,IT.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(C);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??dIe,y;try{y=await h()}catch(C){let T=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(C=>Ao.emitTelemetry(C)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ne.info("pay_merchant:review",{host:_,currency:u});let C;try{C=await y.review(v)}catch(T){throw await $j({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await $j({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${ste(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async C=>{Ne.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...C?{onApprovalUrl:C}:{}})}catch(j){throw await $j({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",M=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await $j({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:O,errorMessage:O?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:M,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let U=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:O,action:"pay",reviewId:x,...T,paymentStatus:M,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${U}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${U}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,cIe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ne.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:C,run:async O=>{try{let M=await S(U=>{Ne.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(U)});return Ne.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:M.success===!0}),M}catch(M){throw Ne.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:PT(M instanceof Error?M.message:String(M))}),M}}});return hIe(T,"authorize")}catch(T){if(T instanceof ST)return Ne.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function bIe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:qh();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??yte)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=mte(e.ceiling)}catch(_){if(_ instanceof _0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=mte(e.perTransaction)}catch(_){if(_ instanceof _0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??lIe,u=t.contactPath??pIe;try{await(0,IT.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,IT.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??dIe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>Ao.emitTelemetry(_)),y=Date.now();Ne.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?PT(_.message):String(_);return Ne.warn("start_card_mandate:failed",{message:w}),await oIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ne.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await oIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${ste(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var dPe=require("node:crypto");var sPe=require("node:crypto");var Ur={};Ei(Ur,{BRAND:()=>Hwt,DIRTY:()=>R_,EMPTY_PATH:()=>vwt,INVALID:()=>yt,NEVER:()=>b4t,OK:()=>Ds,ParseStatus:()=>rs,Schema:()=>qt,ZodAny:()=>ly,ZodArray:()=>A0,ZodBigInt:()=>N_,ZodBoolean:()=>B_,ZodBranded:()=>CT,ZodCatch:()=>$_,ZodDate:()=>j_,ZodDefault:()=>V_,ZodDiscriminatedUnion:()=>Gj,ZodEffects:()=>ud,ZodEnum:()=>H_,ZodError:()=>Qa,ZodFirstPartyTypeKind:()=>Et,ZodFunction:()=>Yj,ZodIntersection:()=>D_,ZodIssueCode:()=>ye,ZodLazy:()=>L_,ZodLiteral:()=>z_,ZodMap:()=>V4,ZodNaN:()=>K4,ZodNativeEnum:()=>F_,ZodNever:()=>Ol,ZodNull:()=>M_,ZodNullable:()=>uf,ZodNumber:()=>k_,ZodObject:()=>ec,ZodOptional:()=>ad,ZodParsedType:()=>Be,ZodPipeline:()=>RT,ZodPromise:()=>py,ZodReadonly:()=>K_,ZodRecord:()=>Jj,ZodSchema:()=>qt,ZodSet:()=>$4,ZodString:()=>dy,ZodSymbol:()=>H4,ZodTransformer:()=>ud,ZodTuple:()=>cf,ZodType:()=>qt,ZodUndefined:()=>U_,ZodUnion:()=>q_,ZodUnknown:()=>E0,ZodVoid:()=>F4,addIssueToContext:()=>Se,any:()=>ld,array:()=>ue,bigint:()=>Kwt,boolean:()=>dd,coerce:()=>ou,custom:()=>TIe,date:()=>Wwt,datetimeRegex:()=>xIe,defaultErrorMap:()=>v0,discriminatedUnion:()=>e4t,effect:()=>d4t,enum:()=>pd,function:()=>o4t,getErrorMap:()=>D4,getParsedType:()=>af,instanceof:()=>Vwt,intersection:()=>t4t,isAborted:()=>Kj,isAsync:()=>L4,isDirty:()=>Wj,isValid:()=>uy,late:()=>Fwt,lazy:()=>s4t,literal:()=>a4t,makeIssue:()=>OT,map:()=>n4t,nan:()=>$wt,nativeEnum:()=>c4t,never:()=>Zwt,null:()=>W4,nullable:()=>p4t,number:()=>Tr,object:()=>fe,objectUtil:()=>gte,oboolean:()=>g4t,onumber:()=>y4t,optional:()=>l4t,ostring:()=>h4t,pipeline:()=>m4t,preprocess:()=>f4t,promise:()=>u4t,quotelessJson:()=>gwt,record:()=>Jt,set:()=>i4t,setErrorMap:()=>_wt,strictObject:()=>Qwt,string:()=>L,symbol:()=>Gwt,transformer:()=>d4t,tuple:()=>r4t,undefined:()=>Jwt,union:()=>G4,unknown:()=>Ywt,util:()=>Gt,void:()=>Xwt});var Gt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Gt||(Gt={}));var gte;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(gte||(gte={}));var Be=Gt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),af=e=>{switch(typeof e){case"undefined":return Be.undefined;case"string":return Be.string;case"number":return Number.isNaN(e)?Be.nan:Be.number;case"boolean":return Be.boolean;case"function":return Be.function;case"bigint":return Be.bigint;case"symbol":return Be.symbol;case"object":return Array.isArray(e)?Be.array:e===null?Be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Be.promise:typeof Map<"u"&&e instanceof Map?Be.map:typeof Set<"u"&&e instanceof Set?Be.set:typeof Date<"u"&&e instanceof Date?Be.date:Be.object;default:return Be.unknown}};var ye=Gt.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"]),gwt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Qa=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Qa.create=e=>new Qa(e);var bwt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Be.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Gt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Gt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gt.assertNever(e)}return{message:r}},v0=bwt;var _Ie=v0;function _wt(e){_Ie=e}function D4(){return _Ie}var OT=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},vwt=[];function Se(e,t){let r=D4(),n=OT({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===v0?void 0:v0].filter(i=>!!i)});e.common.issues.push(n)}var rs=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return yt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return yt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},yt=Object.freeze({status:"aborted"}),R_=e=>({status:"dirty",value:e}),Ds=e=>({status:"valid",value:e}),Kj=e=>e.status==="aborted",Wj=e=>e.status==="dirty",uy=e=>e.status==="valid",L4=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var cd=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}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}},vIe=(e,t)=>{if(uy(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Qa(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return af(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:af(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new rs,ctx:{common:t.parent.common,data:t.data,parsedType:af(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(L4(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)},i=this._parseSync({data:t,path:n.path,parent:n});return vIe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return uy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>uy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(L4(i)?i:Promise.resolve(i));return vIe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new ud({schema:this,typeName:Et.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ad.create(this,this._def)}nullable(){return uf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A0.create(this)}promise(){return py.create(this,this._def)}or(t){return q_.create([this,t],this._def)}and(t){return D_.create(this,t,this._def)}transform(t){return new ud({...Bt(this._def),schema:this,typeName:Et.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new V_({...Bt(this._def),innerType:this,defaultValue:r,typeName:Et.ZodDefault})}brand(){return new CT({typeName:Et.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new $_({...Bt(this._def),innerType:this,catchValue:r,typeName:Et.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return RT.create(this,t)}readonly(){return K_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wwt=/^c[^\s-]{8,}$/i,Ewt=/^[0-9a-z]+$/,Awt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xwt=/^[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,Swt=/^[a-z0-9_-]{21}$/i,Twt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Iwt=/^[-+]?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)?)??$/,Pwt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Owt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bte,Cwt=/^(?:(?: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])$/,Rwt=/^(?:(?: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])$/,kwt=/^(([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]))$/,Nwt=/^(([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])$/,Bwt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jwt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,EIe="((\\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])))",Uwt=new RegExp(`^${EIe}$`);function AIe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Mwt(e){return new RegExp(`^${AIe(e)}$`)}function xIe(e){let t=`${EIe}T${AIe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function qwt(e,t){return!!((t==="v4"||!t)&&Cwt.test(e)||(t==="v6"||!t)&&kwt.test(e))}function Dwt(e,t){if(!Twt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function Lwt(e,t){return!!((t==="v4"||!t)&&Rwt.test(e)||(t==="v6"||!t)&&Nwt.test(e))}var dy=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),yt}let n=new rs,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Se(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Se(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Pwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")bte||(bte=new RegExp(Owt,"u")),bte.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")xwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Swt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")wwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Ewt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Awt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Se(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?xIe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Uwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Mwt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Iwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?qwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Dwt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Lwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Bwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?jwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...et.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};dy.create=e=>new dy({checks:[],typeName:Et.ZodString,coerce:e?.coerce??!1,...Bt(e)});function zwt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var k_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Be.number){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),yt}let n,i=new rs;for(let o of this._def.checks)o.kind==="int"?Gt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?zwt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_finite,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Gt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};k_.create=e=>new k_({checks:[],typeName:Et.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var N_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Be.bigint)return this._getInvalidInput(t);let n,i=new rs;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Se(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),yt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};N_.create=e=>new N_({checks:[],typeName:Et.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var B_=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),yt}return Ds(t.data)}};B_.create=e=>new B_({typeName:Et.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var j_=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),yt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_date}),yt}let n=new rs,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};j_.create=e=>new j_({checks:[],coerce:e?.coerce||!1,typeName:Et.ZodDate,...Bt(e)});var H4=class extends qt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),yt}return Ds(t.data)}};H4.create=e=>new H4({typeName:Et.ZodSymbol,...Bt(e)});var U_=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),yt}return Ds(t.data)}};U_.create=e=>new U_({typeName:Et.ZodUndefined,...Bt(e)});var M_=class extends qt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),yt}return Ds(t.data)}};M_.create=e=>new M_({typeName:Et.ZodNull,...Bt(e)});var ly=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ds(t.data)}};ly.create=e=>new ly({typeName:Et.ZodAny,...Bt(e)});var E0=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ds(t.data)}};E0.create=e=>new E0({typeName:Et.ZodUnknown,...Bt(e)});var Ol=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Se(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),yt}};Ol.create=e=>new Ol({typeName:Et.ZodNever,...Bt(e)});var F4=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),yt}return Ds(t.data)}};F4.create=e=>new F4({typeName:Et.ZodVoid,...Bt(e)});var A0=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Se(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),yt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Se(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Se(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Se(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new cd(r,s,r.path,a)))).then(s=>rs.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new cd(r,s,r.path,a)));return rs.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};A0.create=(e,t)=>new A0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Et.ZodArray,...Bt(t)});function z4(e){if(e instanceof ec){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=ad.create(z4(n))}return new ec({...e._def,shape:()=>t})}else return e instanceof A0?new A0({...e._def,type:z4(e.element)}):e instanceof ad?ad.create(z4(e.unwrap())):e instanceof uf?uf.create(z4(e.unwrap())):e instanceof cf?cf.create(e.items.map(t=>z4(t))):e}var ec=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Gt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Be.object){let u=this._getOrReturnCtx(t);return Se(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),yt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ol&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new cd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Ol){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Se(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new cd(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>rs.mergeObjectSync(n,u)):rs.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Et.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Gt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Gt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return z4(this)}partial(t){let r={};for(let n of Gt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Gt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ad;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return SIe(Gt.objectKeys(this.shape))}};ec.create=(e,t)=>new ec({shape:()=>e,unknownKeys:"strip",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});ec.strictCreate=(e,t)=>new ec({shape:()=>e,unknownKeys:"strict",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});ec.lazycreate=(e,t)=>new ec({shape:e,unknownKeys:"strip",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});var q_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Qa(a.ctx.common.issues));return Se(r,{code:ye.invalid_union,unionErrors:s}),yt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new Qa(c));return Se(r,{code:ye.invalid_union,unionErrors:a}),yt}}get options(){return this._def.options}};q_.create=(e,t)=>new q_({options:e,typeName:Et.ZodUnion,...Bt(t)});var w0=e=>e instanceof L_?w0(e.schema):e instanceof ud?w0(e.innerType()):e instanceof z_?[e.value]:e instanceof H_?e.options:e instanceof F_?Gt.objectValues(e.enum):e instanceof V_?w0(e._def.innerType):e instanceof U_?[void 0]:e instanceof M_?[null]:e instanceof ad?[void 0,...w0(e.unwrap())]:e instanceof uf?[null,...w0(e.unwrap())]:e instanceof CT||e instanceof K_?w0(e.unwrap()):e instanceof $_?w0(e._def.innerType):[],Gj=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Se(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),yt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Se(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=w0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Et.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function _te(e,t){let r=af(e),n=af(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Gt.objectKeys(t),o=Gt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=_te(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Be.array&&n===Be.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=_te(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Be.date&&n===Be.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var D_=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Kj(o)||Kj(s))return yt;let a=_te(o.value,s.value);return a.valid?((Wj(o)||Wj(s))&&r.dirty(),{status:r.value,value:a.data}):(Se(n,{code:ye.invalid_intersection_types}),yt)};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(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};D_.create=(e,t,r)=>new D_({left:e,right:t,typeName:Et.ZodIntersection,...Bt(r)});var cf=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Se(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),yt;if(n.data.length<this._def.items.length)return Se(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yt;!this._def.rest&&n.data.length>this._def.items.length&&(Se(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new cd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>rs.mergeArray(r,s)):rs.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};cf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new cf({items:e,typeName:Et.ZodTuple,rest:null,...Bt(t)})};var Jj=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.object)return Se(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),yt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new cd(n,a,n.path,a)),value:s._parse(new cd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?rs.mergeObjectAsync(r,i):rs.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:Et.ZodRecord,...Bt(n)}):new e({keyType:dy.create(),valueType:t,typeName:Et.ZodRecord,...Bt(r)})}},V4=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.map)return Se(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),yt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new cd(n,a,n.path,[u,"key"])),value:o._parse(new cd(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};V4.create=(e,t,r)=>new V4({valueType:t,keyType:e,typeName:Et.ZodMap,...Bt(r)});var $4=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Se(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),yt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Se(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Se(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return yt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new cd(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};$4.create=(e,t)=>new $4({valueType:e,minSize:null,maxSize:null,typeName:Et.ZodSet,...Bt(t)});var Yj=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Se(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),yt;function n(a,c){return OT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,D4(),v0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return OT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,D4(),v0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof py){let a=this;return Ds(async function(...c){let u=new Qa([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Ds(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Qa([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Qa([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:cf.create(t).rest(E0.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||cf.create([]).rest(E0.create()),returns:r||E0.create(),typeName:Et.ZodFunction,...Bt(n)})}},L_=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};L_.create=(e,t)=>new L_({getter:e,typeName:Et.ZodLazy,...Bt(t)});var z_=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Se(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),yt}return{status:"valid",value:t.data}}get value(){return this._def.value}};z_.create=(e,t)=>new z_({value:e,typeName:Et.ZodLiteral,...Bt(t)});function SIe(e,t){return new H_({values:e,typeName:Et.ZodEnum,...Bt(t)})}var H_=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Se(r,{expected:Gt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Se(r,{received:r.data,code:ye.invalid_enum_value,options:n}),yt}return Ds(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};H_.create=SIe;var F_=class extends qt{_parse(t){let r=Gt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Gt.objectValues(r);return Se(n,{expected:Gt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(Gt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Gt.objectValues(r);return Se(n,{received:n.data,code:ye.invalid_enum_value,options:i}),yt}return Ds(t.data)}get enum(){return this._def.values}};F_.create=(e,t)=>new F_({values:e,typeName:Et.ZodNativeEnum,...Bt(t)});var py=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Se(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),yt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ds(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};py.create=(e,t)=>new py({type:e,typeName:Et.ZodPromise,...Bt(t)});var ud=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Et.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Se(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return yt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?yt:c.status==="dirty"?R_(c.value):r.value==="dirty"?R_(c.value):c});{if(r.value==="aborted")return yt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?yt:a.status==="dirty"?R_(a.value):r.value==="dirty"?R_(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);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 a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!uy(s))return yt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>uy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):yt);Gt.assertNever(i)}};ud.create=(e,t,r)=>new ud({schema:e,typeName:Et.ZodEffects,effect:t,...Bt(r)});ud.createWithPreprocess=(e,t,r)=>new ud({schema:t,effect:{type:"preprocess",transform:e},typeName:Et.ZodEffects,...Bt(r)});var ad=class extends qt{_parse(t){return this._getType(t)===Be.undefined?Ds(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ad.create=(e,t)=>new ad({innerType:e,typeName:Et.ZodOptional,...Bt(t)});var uf=class extends qt{_parse(t){return this._getType(t)===Be.null?Ds(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};uf.create=(e,t)=>new uf({innerType:e,typeName:Et.ZodNullable,...Bt(t)});var V_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Be.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};V_.create=(e,t)=>new V_({innerType:e,typeName:Et.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var $_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return L4(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qa(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Qa(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$_.create=(e,t)=>new $_({innerType:e,typeName:Et.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var K4=class extends qt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),yt}return{status:"valid",value:t.data}}};K4.create=e=>new K4({typeName:Et.ZodNaN,...Bt(e)});var Hwt=Symbol("zod_brand"),CT=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},RT=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?yt:o.status==="dirty"?(r.dirty(),R_(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?yt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Et.ZodPipeline})}},K_=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(uy(i)&&(i.value=Object.freeze(i.value)),i);return L4(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};K_.create=(e,t)=>new K_({innerType:e,typeName:Et.ZodReadonly,...Bt(t)});function wIe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function TIe(e,t={},r){return e?ly.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=wIe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=wIe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):ly.create()}var Fwt={object:ec.lazycreate},Et;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Et||(Et={}));var Vwt=(e,t={message:`Input not instance of ${e.name}`})=>TIe(r=>r instanceof e,t),L=dy.create,Tr=k_.create,$wt=K4.create,Kwt=N_.create,dd=B_.create,Wwt=j_.create,Gwt=H4.create,Jwt=U_.create,W4=M_.create,ld=ly.create,Ywt=E0.create,Zwt=Ol.create,Xwt=F4.create,ue=A0.create,fe=ec.create,Qwt=ec.strictCreate,G4=q_.create,e4t=Gj.create,t4t=D_.create,r4t=cf.create,Jt=Jj.create,n4t=V4.create,i4t=$4.create,o4t=Yj.create,s4t=L_.create,a4t=z_.create,pd=H_.create,c4t=F_.create,u4t=py.create,d4t=ud.create,l4t=ad.create,p4t=uf.create,f4t=ud.createWithPreprocess,m4t=RT.create,h4t=()=>L().optional(),y4t=()=>Tr().optional(),g4t=()=>dd().optional(),ou={string:(e=>dy.create({...e,coerce:!0})),number:(e=>k_.create({...e,coerce:!0})),boolean:(e=>B_.create({...e,coerce:!0})),bigint:(e=>N_.create({...e,coerce:!0})),date:(e=>j_.create({...e,coerce:!0}))};var b4t=yt;var v4t=pd(["enc","sig"]),w4t=pd(["markdown","plain"]),E4t=pd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),A4t=pd(["error","info","warning"]),Z4=pd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),x4t=pd(["completed","failed","pending"]),S4t=pd(["digital","pickup","shipping"]),T4t=pd(["fulfilled","partial","processing","removed"]),I4t=pd(["across","each"]),vte=pd(["pickup","shipping"]),P4t=fe({config:Jt(L(),ld()),config_schema:L(),id:L(),instrument_schemas:ue(L()),name:L(),spec:L(),version:L()}),O4t=fe({alg:L().optional(),crv:L().optional(),e:L().optional(),kid:L(),kty:L(),n:L().optional(),use:v4t.optional(),x:L().optional(),y:L().optional()}),C4t=fe({config:Jt(L(),ld()).optional(),extends:L().optional(),name:L(),schema:L(),spec:L(),version:L()}),R4t=fe({endpoint:L()}),k4t=fe({schema:L()}),IIe=fe({endpoint:L(),schema:L()}),N4t=IIe,B4t=IIe,ha=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional()}),no=fe({address_country:L().optional(),address_region:L().optional(),currency:L().optional(),eligibility:ue(L()).optional(),intent:L().optional(),language:L().optional(),postal_code:L().optional()}),wte=no,PIe=fe({id:L()}),j4t=PIe,U4t=PIe,kT=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional()}),Zj=fe({type:L()}),qi=fe({"dev.ucp.buyer_ip":L().optional(),"dev.ucp.user_agent":L().optional()}),Ete=qi,OIe=fe({id:L(),image_url:L().optional(),price:Tr(),title:L()}),Xj=fe({amount:Tr(),display_text:L().optional(),type:L()}),fy=fe({title:L().optional(),type:L(),url:L()}),x0=fe({code:L().optional(),content:L(),content_type:w4t.optional(),path:L().optional(),severity:E4t.optional(),type:A4t,image_url:L().optional(),presentation:L().optional(),url:L().optional()}),Ate=x0,X4=fe({id:L(),label:L().optional(),permalink_url:L()}),M4t=fe({amount:Tr(),display_text:L()}),q4t=fe({config:Jt(L(),ld()).optional(),extends:L().optional(),name:L(),schema:L().optional(),spec:L().optional(),version:L()}),xte=fe({id:L(),quantity:Tr()}),D4t=xte,L4t=xte,z4t=xte,H4t=fe({fulfilled:Tr(),original:Tr().optional(),total:Tr()}),F4t=fe({billing_address:kT.optional(),credential:Zj.optional(),display:Jt(L(),ld()).optional(),handler_id:L(),id:L(),type:L()}),V4t=fe({checkout_mandate:L()}),$4t=fe({merchant_authorization:L().optional(),checkout_mandate:L()}),K4t=fe({analytics:dd().optional(),marketing:dd().optional(),preferences:dd().optional(),sale_of_data:dd().optional()});var W4t=K4t;var CIe=fe({codes:ue(L()).optional()}),G4t=CIe,J4t=fe({amount:Tr(),path:L()}),Y4t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L().optional(),address:kT.optional(),name:L().optional()}),Z4t=fe({carrier:L().optional(),description:L().optional(),earliest_fulfillment_time:ou.date().optional(),id:L(),latest_fulfillment_time:ou.date().optional(),title:L(),totals:ue(Xj)}),X4t=fe({description:L().optional(),fulfillable_on:G4([W4(),L()]).optional(),line_item_ids:ue(L()),type:vte}),Q4t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L(),address:kT.optional(),name:L().optional()}),e8t=fe({max:Tr().optional(),min:Tr().optional()}),NT=fe({taxonomy:L().optional(),value:L()}),BT=fe({html:L().optional(),markdown:L().optional(),plain:L().optional()}),J4=fe({amount:Tr(),currency:L()}),jT=fe({alt_text:L().optional(),height:Tr().optional(),type:L(),url:L(),width:Tr().optional()}),t8t=fe({id:L().optional(),label:L()}),UT=fe({count:Tr().optional(),scale_max:Tr(),scale_min:Tr().optional(),value:Tr()}),RIe=fe({available:dd().optional(),status:L().optional()}),r8t=RIe,kIe=fe({type:L(),value:L()}),n8t=kIe,i8t=fe({id:L(),match:L().optional()}),Ste=fe({id:L().optional(),label:L(),name:L()}),NIe=Ste,BIe=fe({links:ue(fy).optional(),name:L().optional()}),o8t=BIe,jIe=fe({unit:L(),value:Tr()});var s8t=jIe,a8t=fe({cursor:L().optional(),limit:Tr().optional()}),c8t=fe({cursor:L().optional(),has_next_page:dd(),total_count:Tr().optional()}),u8t=fe({handlers:ue(P4t).optional()}),d8t=fe({a2a:R4t.optional(),embedded:k4t.optional(),mcp:N4t.optional(),rest:B4t.optional(),spec:L(),version:L()}),Q4=fe({item:j4t,quantity:Tr()}),l8t=fe({billing_address:kT.optional(),credential:Zj.optional(),display:Jt(L(),ld()).optional(),handler_id:L(),id:L(),type:L(),selected:dd().optional()}),MT=fe({id:L().optional(),item:U4t,parent_id:L().optional(),quantity:Tr()}),Qj=fe({instruments:ue(l8t).optional()}),p8t=Qj,qT=Qj,e8=Qj,eU=Qj,W_=fe({id:L(),item:OIe,parent_id:L().optional(),quantity:Tr(),totals:ue(Xj)}),my=fe({amount:Tr(),display_text:L().optional(),type:L(),lines:ue(M4t).optional()}),Cl=fe({capabilities:Jt(L(),ue(q4t)),version:L()}),f8t=fe({description:L().optional(),id:L(),line_items:ue(D4t).optional(),occurred_at:ou.date(),status:x4t,totals:ue(Xj).optional(),type:L()}),m8t=fe({carrier:L().optional(),description:L().optional(),id:L(),line_items:ue(L4t),occurred_at:ou.date(),tracking_number:L().optional(),tracking_url:L().optional(),type:L()}),h8t=fe({description:L().optional(),destination:kT,fulfillable_on:L().optional(),id:L(),line_items:ue(z4t),method_type:S4t}),y8t=fe({id:L(),item:OIe,parent_id:L().optional(),quantity:H4t,status:T4t,totals:ue(Xj)}),Dkr=fe({payment_data:F4t}),Lkr=fe({ap2:V4t.optional()}),zkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,ap2:$4t.optional()}),Tte=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),consent:W4t.optional()}),g8t=Tte,b8t=Tte,UIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional(),discounts:G4t.optional()}),_8t=fe({allocations:ue(J4t).optional(),amount:Tr(),automatic:dd().optional(),code:L().optional(),eligibility:L().optional(),method:I4t.optional(),priority:Tr().optional(),provisional:dd().optional(),title:L()}),MIe=fe({id:L(),line_item_ids:ue(L()),options:ue(Z4t).optional(),selected_option_id:G4([W4(),L()]).optional()}),v8t=fe({destinations:ue(Q4t).optional(),groups:ue(MIe).optional(),id:L(),line_item_ids:ue(L()),selected_destination_id:G4([W4(),L()]).optional(),type:vte}),Hkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),signals:qi.optional()}),Fkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),id:L(),line_items:ue(MT),signals:qi.optional()}),Vkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy).optional(),messages:ue(x0).optional(),signals:qi.optional(),totals:ue(my),ucp:Cl}),w8t=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional()}),qIe=w8t,$kr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,cart_id:L().optional()}),Ite=fe({categories:ue(L()).optional(),price:e8t.optional()}),Y4=fe({max:J4,min:J4}),Pte=fe({name:L(),values:ue(t8t)}),DIe=fe({amount:Tr(),currency:L(),measure:jIe,reference:s8t}),E8t=DIe,Kkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),id:L(),preferences:ue(L()).optional(),selected:ue(NIe).optional(),signals:Ete.optional()}),Wkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),pagination:a8t.optional(),query:L().optional(),signals:Ete.optional()}),A8t=fe({capabilities:ue(C4t),services:Jt(L(),d8t),version:L()}),Gkr=fe({attribution:Jt(L(),L()).optional(),payment:p8t,signals:qi.optional()}),LIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl}),x8t=fe({events:ue(m8t).optional(),expectations:ue(h8t).optional()}),zIe=fe({attribution:Jt(L(),L()).optional(),buyer:Tte.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional()}),HIe=fe({attribution:Jt(L(),L()).optional(),buyer:b8t.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional()}),FIe=fe({attribution:Jt(L(),L()).optional(),buyer:g8t.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl}),VIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),discounts:CIe.optional()}),S8t=fe({applied:ue(_8t).optional(),codes:ue(L()).optional()}),T8t=fe({destinations:ue(Y4t).optional(),groups:ue(MIe).optional(),line_item_ids:ue(L()).optional(),selected_destination_id:G4([W4(),L()]).optional(),type:vte}),I8t=fe({available_methods:ue(X4t).optional(),methods:ue(v8t).optional()}),$Ie=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),cart_id:L().optional()}),Jkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),ids:ue(L()),signals:Ete.optional()}),P8t=fe({availability:RIe.optional(),barcodes:ue(kIe).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price:J4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Ste).optional(),price:J4,rating:UT.optional(),seller:BIe.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:DIe.optional(),url:L().optional(),inputs:ue(i8t)}),KIe=fe({availability:r8t.optional(),barcodes:ue(n8t).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price:J4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Ste).optional(),price:J4,rating:UT.optional(),seller:o8t.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:E8t.optional(),url:L().optional()}),O8t=fe({categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Pte).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(KIe)}),Ykr=fe({payment:u8t.optional(),signing_keys:ue(O4t).optional(),ucp:A8t}),WIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional()}),C8t=fe({adjustments:ue(f8t).optional(),attribution:Jt(L(),L()).optional(),checkout_id:L(),currency:L(),fulfillment:x8t,id:L(),label:L().optional(),line_items:ue(y8t),messages:ue(x0).optional(),permalink_url:L(),totals:ue(my),ucp:Cl}),GIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,discounts:S8t.optional()}),JIe=fe({methods:ue(T8t).optional()}),YIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional(),fulfillment:JIe.optional()}),ZIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,fulfillment:I8t.optional()}),R8t=fe({categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Pte).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(P8t)}),k8t=fe({options:ue(Pte).optional(),selected:ue(NIe).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(KIe)}),Zkr=fe({messages:ue(Ate).optional(),pagination:c8t.optional(),products:ue(O8t),ucp:Cl}),XIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),fulfillment:JIe.optional()}),Xkr=fe({messages:ue(Ate).optional(),products:ue(R8t),ucp:Cl}),Qkr=fe({messages:ue(Ate).optional(),product:k8t,ucp:Cl});var nNr=Zj.extend({token:Ur.string().optional()}),N8t=Ur.object({webhook_url:Ur.string().url().optional()}),QIe=LIe.extend(ZIe.pick({fulfillment:!0}).shape).extend(GIe.pick({discounts:!0}).shape).extend(FIe.pick({buyer:!0}).shape).extend({platform:N8t.optional()}),ePe=WIe.extend(XIe.pick({fulfillment:!0}).shape).extend(VIe.pick({discounts:!0}).shape).extend(zIe.pick({buyer:!0}).shape).extend($Ie.pick({cart_id:!0}).shape),tPe=qIe.extend(YIe.pick({fulfillment:!0}).shape).extend(UIe.pick({discounts:!0}).shape).extend(HIe.pick({buyer:!0}).shape);xl();async function tU(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function rU(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var B8t=3e4,rPe=2*1024*1024,Rl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function nPe(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function iPe(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?ePe:tPe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function j8t(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function oPe(e,t,r,n){try{e[t](r,n)}catch{}}function U8t(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var nU=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=nPe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=nPe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??B8t,this.boundaryLogger=t.logger??Ne}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:iPe(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:iPe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=rU(this.timeoutMs,this.signal),o=(0,sPe.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await tU(u,rPe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Rl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>rPe)throw new Rl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Rl("UCP MCP response is not valid JSON",void 0,u.status)}if(!j8t(l))throw new Rl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Rl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Rl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Rl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Rl("UCP MCP response is missing result.structuredContent");if(!QIe.safeParse(U8t(p.structuredContent)).success)throw new Rl("UCP checkout response failed schema validation");return oPe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw oPe(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var cPe=require("node:crypto");xl();var oU="2026-04-08",M8t="dev.ucp.shopping",q8t="dev.ucp.shopping.checkout",D8t=1024*1024,L8t=1e4,z8t="https://ucp.dev",DT=Ur.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),H8t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:DT,schema:DT,transport:Ur.enum(["rest","mcp","a2a","embedded"]),endpoint:DT.optional()}).passthrough(),F8t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:DT,schema:DT,extends:Ur.union([Ur.string(),Ur.array(Ur.string()).min(1)]).optional()}).passthrough(),V8t=Ur.object({ucp:Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Ur.record(Ur.array(H8t)),capabilities:Ur.record(Ur.array(F8t)),payment_handlers:Ur.record(Ur.array(Ur.unknown())).optional()}).passthrough(),signing_keys:Ur.array(Ur.unknown()).optional()}).passthrough();function $8t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function iU(e,t){if(new URL(e).origin!==z8t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function aPe(e,t,r,n){try{e[t](r,n)}catch{}}async function K8t(e,t={}){let r=$8t(e,"UCP business URL"),n=rU(t.timeoutMs??L8t,t.signal),i=t.logger??Ne,o=(0,cPe.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await tU(c,D8t,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=V8t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return aPe(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw aPe(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function W8t(e){if(e.ucp.version!==oU)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[q8t]?.find(i=>i.version===oU);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");iU(t.spec,"Checkout capability spec"),iU(t.schema,"Checkout capability schema");let r=e.ucp.services[M8t]?.find(i=>i.version===oU&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");iU(r.spec,"Shopping service spec"),iU(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function uPe(e,t={}){let r=await K8t(e,t);return{...r,endpoint:W8t(r.profile),version:oU}}var G8t="https://app.visacli.sh/.well-known/ucp";function J8t(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function Y8t(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Ote(e,t=new Set){if(Array.isArray(e))for(let r of e)Ote(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?Y8t(n,t):Ote(n,t);return t}function Z8t(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Ote(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function lPe(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function X8t(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function pPe(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??uPe)(e.business),i=await(t.getCheckout??(async(o,s)=>await new nU({endpoint:o.endpoint,platformProfileUrl:J8t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??G8t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function fPe(e,t={}){let{service:r,checkout:n}=await pPe(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=lPe(n),s=Z8t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,dPe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:X8t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function Q8t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function mPe(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await pPe(e,t),n=lPe(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=Q8t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}p4();function Cte(){return td()}var Ao=new m4(()=>Ya.getSessionToken()),e3t="4.1.0-rc.52",MNr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
|
|
20828
|
+
`:""})}function Z5t(e){return Y5t(e,$5t,K5t).trimEnd()}function X5t(e){return Z5t(e)!==e.trimEnd()}function zj(e=W5t()){if(!e)return!1;try{let t=G5t(e),r=sf.readFileSync(t,"utf-8");return X5t(r)}catch{return!1}}function V7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q5t(){let e=Lj.homedir();if(!e||!Pl.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Pl.resolve(e)}var GRr=1440*60*1e3;var ewt="# visa-cli-hud-v1";function $7e(e){return typeof e!="string"?!1:e.includes(ewt)?!0:e.includes("visa-cli")&&e.includes("statusline")}qX();p4();_B();var K7e="4.1.0-rc.53";function ote(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function twt(e,t,r){let n=process.env[e];if(n!==void 0)return{value:r==="opt-in"?n==="true":n!=="false",source:{kind:"env",var:e}};let i=KX(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function q4(e){return e==null?"\u2014":e?"yes":"no"}async function W7e(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(l){r=l?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=$X("auth.serverUrl"),s=td(),a=i!==void 0&&i!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};n.push({key:"auth.serverUrl",value:s,formatted:s,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),n.push({key:"account.enrolled",value:t?.enrolled??null,formatted:q4(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.login&&n.push({key:"account.principal",value:t.login,formatted:t.principalKind?`${t.login} (${t.principalKind})`:t.login,source:{kind:"server"},hint:"The identity your CLI session resolves on. Feature-flag access (checkout, mandate) is granted per this exact principal."}),t?.userId&&n.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=twt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:q4(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=dB(),d;if(process.env.VISA_CLI_NO_UPDATE_CHECK?d={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?d={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?d={kind:"env",var:"NODE_ENV"}:d={kind:"default"},n.push({key:"ui.updateCheck",value:!u,formatted:q4(!u),source:d}),n.push({key:"client.version",value:K7e,formatted:K7e,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=Dh();n.push({key:"dev.mockKeychain",value:p,formatted:q4(p),source:ote("VISA_MOCK_KEYCHAIN",!!l),hint:XX()});let f=process.env.VISA_MOCK_TOUCHID,m=bB();n.push({key:"dev.mockTouchid",value:m,formatted:q4(m),source:ote("VISA_MOCK_TOUCHID",!!f),hint:XX()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:q4(!!h),source:ote("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var hte=require("node:os"),TT=require("node:path"),IT=require("node:fs/promises"),sIe=require("node:fs"),aIe=require("node:url"),cIe=require("node:crypto");xl();var rwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function ste(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!rwt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var _0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function G7e(e){let t;try{t=new URL(e)}catch{throw new _0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new _0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}xl();var nwt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},J7e=300*1e3,ate={},cte=0,xT=null;function ute(){return xT||(xT=(async()=>{try{let e=await Ao.getFeatureFlags();ate=e&&e.flags||{},cte=Date.now()}catch(e){ate={},Ne.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{xT=null}})(),xT)}async function Y7e(){await ute()}function Z7e(){Date.now()-cte<J7e||ute()}async function O_(){Date.now()-cte<J7e||await ute()}function iu(e){let t=nwt[e];return t?ate[t]!==!0:!1}var X7e=require("node:crypto"),ST=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},Hj=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new ST(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??X7e.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function uIe(e){return[(0,TT.join)(e,"checkout-engine","index.js"),(0,TT.join)(e,"..","checkout-engine","index.js")]}function fwt(e,t=sIe.existsSync){return uIe(e).find(r=>t(r))??null}var Vj=null,dIe=async()=>{if(Vj)return Vj;let e=fwt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${uIe(__dirname).join(" and ")}).`);return Vj=(await import((0,aIe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await mwt(),cardMandateRegister:await hwt()}),Vj};async function mwt(){let e=await Promise.resolve().then(()=>(fte(),pte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function hwt(){let e=await Promise.resolve().then(()=>(fte(),pte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function yte(){return iu("pay_merchant")?(await O_(),iu("pay_merchant")):!1}var lIe=(0,TT.join)((0,hte.homedir)(),".visa-mcp","agent-credential.json"),pIe=(0,TT.join)((0,hte.homedir)(),".visa-mcp","contact.json"),fIe=new Hj;function PT(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var ywt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function mIe(e){return ywt.has(e)?e:null}async function $j(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?PT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0?e.amountMinor/100:null,payment_currency:mIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function oIe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?PT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:mIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function mte(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new _0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function hIe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=PT(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function yIe(e={},t={}){if(await(t.flagDisabled??yte)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??fIe).get(n);return o?hIe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function gIe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:GX()&&!process.env.VISA_VERIFY_WEB_URL?null:qh();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??yte)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??fIe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=G7e(e.url??"").toString(),c=mte(e.amount)}catch(C){if(C instanceof _0)return{success:!1,message:C.message};throw C}let d=t.credentialPath??lIe,l=t.contactPath??pIe;try{await(0,IT.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,IT.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(C);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??dIe,y;try{y=await h()}catch(C){let T=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(C=>Ao.emitTelemetry(C)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ne.info("pay_merchant:review",{host:_,currency:u});let C;try{C=await y.review(v)}catch(T){throw await $j({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await $j({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${ste(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async C=>{Ne.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...C?{onApprovalUrl:C}:{}})}catch(j){throw await $j({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",M=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await $j({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:O,errorMessage:O?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:M,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let U=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:O,action:"pay",reviewId:x,...T,paymentStatus:M,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${U}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${U}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,cIe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ne.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:C,run:async O=>{try{let M=await S(U=>{Ne.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(U)});return Ne.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:M.success===!0}),M}catch(M){throw Ne.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:PT(M instanceof Error?M.message:String(M))}),M}}});return hIe(T,"authorize")}catch(T){if(T instanceof ST)return Ne.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function bIe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:qh();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??yte)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=mte(e.ceiling)}catch(_){if(_ instanceof _0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=mte(e.perTransaction)}catch(_){if(_ instanceof _0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??lIe,u=t.contactPath??pIe;try{await(0,IT.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,IT.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??dIe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>Ao.emitTelemetry(_)),y=Date.now();Ne.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?PT(_.message):String(_);return Ne.warn("start_card_mandate:failed",{message:w}),await oIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ne.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await oIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${ste(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var dPe=require("node:crypto");var sPe=require("node:crypto");var Ur={};Ei(Ur,{BRAND:()=>Hwt,DIRTY:()=>R_,EMPTY_PATH:()=>vwt,INVALID:()=>yt,NEVER:()=>b4t,OK:()=>Ds,ParseStatus:()=>rs,Schema:()=>qt,ZodAny:()=>ly,ZodArray:()=>A0,ZodBigInt:()=>N_,ZodBoolean:()=>B_,ZodBranded:()=>CT,ZodCatch:()=>$_,ZodDate:()=>j_,ZodDefault:()=>V_,ZodDiscriminatedUnion:()=>Gj,ZodEffects:()=>ud,ZodEnum:()=>H_,ZodError:()=>Qa,ZodFirstPartyTypeKind:()=>Et,ZodFunction:()=>Yj,ZodIntersection:()=>D_,ZodIssueCode:()=>ye,ZodLazy:()=>L_,ZodLiteral:()=>z_,ZodMap:()=>V4,ZodNaN:()=>K4,ZodNativeEnum:()=>F_,ZodNever:()=>Ol,ZodNull:()=>M_,ZodNullable:()=>uf,ZodNumber:()=>k_,ZodObject:()=>ec,ZodOptional:()=>ad,ZodParsedType:()=>Be,ZodPipeline:()=>RT,ZodPromise:()=>py,ZodReadonly:()=>K_,ZodRecord:()=>Jj,ZodSchema:()=>qt,ZodSet:()=>$4,ZodString:()=>dy,ZodSymbol:()=>H4,ZodTransformer:()=>ud,ZodTuple:()=>cf,ZodType:()=>qt,ZodUndefined:()=>U_,ZodUnion:()=>q_,ZodUnknown:()=>E0,ZodVoid:()=>F4,addIssueToContext:()=>Se,any:()=>ld,array:()=>ue,bigint:()=>Kwt,boolean:()=>dd,coerce:()=>ou,custom:()=>TIe,date:()=>Wwt,datetimeRegex:()=>xIe,defaultErrorMap:()=>v0,discriminatedUnion:()=>e4t,effect:()=>d4t,enum:()=>pd,function:()=>o4t,getErrorMap:()=>D4,getParsedType:()=>af,instanceof:()=>Vwt,intersection:()=>t4t,isAborted:()=>Kj,isAsync:()=>L4,isDirty:()=>Wj,isValid:()=>uy,late:()=>Fwt,lazy:()=>s4t,literal:()=>a4t,makeIssue:()=>OT,map:()=>n4t,nan:()=>$wt,nativeEnum:()=>c4t,never:()=>Zwt,null:()=>W4,nullable:()=>p4t,number:()=>Tr,object:()=>fe,objectUtil:()=>gte,oboolean:()=>g4t,onumber:()=>y4t,optional:()=>l4t,ostring:()=>h4t,pipeline:()=>m4t,preprocess:()=>f4t,promise:()=>u4t,quotelessJson:()=>gwt,record:()=>Jt,set:()=>i4t,setErrorMap:()=>_wt,strictObject:()=>Qwt,string:()=>L,symbol:()=>Gwt,transformer:()=>d4t,tuple:()=>r4t,undefined:()=>Jwt,union:()=>G4,unknown:()=>Ywt,util:()=>Gt,void:()=>Xwt});var Gt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Gt||(Gt={}));var gte;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(gte||(gte={}));var Be=Gt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),af=e=>{switch(typeof e){case"undefined":return Be.undefined;case"string":return Be.string;case"number":return Number.isNaN(e)?Be.nan:Be.number;case"boolean":return Be.boolean;case"function":return Be.function;case"bigint":return Be.bigint;case"symbol":return Be.symbol;case"object":return Array.isArray(e)?Be.array:e===null?Be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Be.promise:typeof Map<"u"&&e instanceof Map?Be.map:typeof Set<"u"&&e instanceof Set?Be.set:typeof Date<"u"&&e instanceof Date?Be.date:Be.object;default:return Be.unknown}};var ye=Gt.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"]),gwt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Qa=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Qa.create=e=>new Qa(e);var bwt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Be.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Gt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Gt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gt.assertNever(e)}return{message:r}},v0=bwt;var _Ie=v0;function _wt(e){_Ie=e}function D4(){return _Ie}var OT=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},vwt=[];function Se(e,t){let r=D4(),n=OT({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===v0?void 0:v0].filter(i=>!!i)});e.common.issues.push(n)}var rs=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return yt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return yt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},yt=Object.freeze({status:"aborted"}),R_=e=>({status:"dirty",value:e}),Ds=e=>({status:"valid",value:e}),Kj=e=>e.status==="aborted",Wj=e=>e.status==="dirty",uy=e=>e.status==="valid",L4=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var cd=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}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}},vIe=(e,t)=>{if(uy(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Qa(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return af(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:af(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new rs,ctx:{common:t.parent.common,data:t.data,parsedType:af(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(L4(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)},i=this._parseSync({data:t,path:n.path,parent:n});return vIe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return uy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>uy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:af(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(L4(i)?i:Promise.resolve(i));return vIe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new ud({schema:this,typeName:Et.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ad.create(this,this._def)}nullable(){return uf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A0.create(this)}promise(){return py.create(this,this._def)}or(t){return q_.create([this,t],this._def)}and(t){return D_.create(this,t,this._def)}transform(t){return new ud({...Bt(this._def),schema:this,typeName:Et.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new V_({...Bt(this._def),innerType:this,defaultValue:r,typeName:Et.ZodDefault})}brand(){return new CT({typeName:Et.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new $_({...Bt(this._def),innerType:this,catchValue:r,typeName:Et.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return RT.create(this,t)}readonly(){return K_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wwt=/^c[^\s-]{8,}$/i,Ewt=/^[0-9a-z]+$/,Awt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xwt=/^[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,Swt=/^[a-z0-9_-]{21}$/i,Twt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Iwt=/^[-+]?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)?)??$/,Pwt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Owt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bte,Cwt=/^(?:(?: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])$/,Rwt=/^(?:(?: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])$/,kwt=/^(([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]))$/,Nwt=/^(([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])$/,Bwt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jwt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,EIe="((\\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])))",Uwt=new RegExp(`^${EIe}$`);function AIe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Mwt(e){return new RegExp(`^${AIe(e)}$`)}function xIe(e){let t=`${EIe}T${AIe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function qwt(e,t){return!!((t==="v4"||!t)&&Cwt.test(e)||(t==="v6"||!t)&&kwt.test(e))}function Dwt(e,t){if(!Twt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function Lwt(e,t){return!!((t==="v4"||!t)&&Rwt.test(e)||(t==="v6"||!t)&&Nwt.test(e))}var dy=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),yt}let n=new rs,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Se(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Se(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Pwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")bte||(bte=new RegExp(Owt,"u")),bte.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")xwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Swt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")wwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Ewt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Awt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Se(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?xIe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Uwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Mwt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Iwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?qwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Dwt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Lwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Bwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?jwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Se(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...et.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};dy.create=e=>new dy({checks:[],typeName:Et.ZodString,coerce:e?.coerce??!1,...Bt(e)});function zwt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var k_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Be.number){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),yt}let n,i=new rs;for(let o of this._def.checks)o.kind==="int"?Gt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?zwt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_finite,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Gt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};k_.create=e=>new k_({checks:[],typeName:Et.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var N_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Be.bigint)return this._getInvalidInput(t);let n,i=new rs;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Se(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Se(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),yt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};N_.create=e=>new N_({checks:[],typeName:Et.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var B_=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),yt}return Ds(t.data)}};B_.create=e=>new B_({typeName:Et.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var j_=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),yt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Se(o,{code:ye.invalid_date}),yt}let n=new rs,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Se(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};j_.create=e=>new j_({checks:[],coerce:e?.coerce||!1,typeName:Et.ZodDate,...Bt(e)});var H4=class extends qt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),yt}return Ds(t.data)}};H4.create=e=>new H4({typeName:Et.ZodSymbol,...Bt(e)});var U_=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),yt}return Ds(t.data)}};U_.create=e=>new U_({typeName:Et.ZodUndefined,...Bt(e)});var M_=class extends qt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),yt}return Ds(t.data)}};M_.create=e=>new M_({typeName:Et.ZodNull,...Bt(e)});var ly=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ds(t.data)}};ly.create=e=>new ly({typeName:Et.ZodAny,...Bt(e)});var E0=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ds(t.data)}};E0.create=e=>new E0({typeName:Et.ZodUnknown,...Bt(e)});var Ol=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Se(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),yt}};Ol.create=e=>new Ol({typeName:Et.ZodNever,...Bt(e)});var F4=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),yt}return Ds(t.data)}};F4.create=e=>new F4({typeName:Et.ZodVoid,...Bt(e)});var A0=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Se(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),yt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Se(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Se(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Se(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new cd(r,s,r.path,a)))).then(s=>rs.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new cd(r,s,r.path,a)));return rs.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};A0.create=(e,t)=>new A0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Et.ZodArray,...Bt(t)});function z4(e){if(e instanceof ec){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=ad.create(z4(n))}return new ec({...e._def,shape:()=>t})}else return e instanceof A0?new A0({...e._def,type:z4(e.element)}):e instanceof ad?ad.create(z4(e.unwrap())):e instanceof uf?uf.create(z4(e.unwrap())):e instanceof cf?cf.create(e.items.map(t=>z4(t))):e}var ec=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Gt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Be.object){let u=this._getOrReturnCtx(t);return Se(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),yt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ol&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new cd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Ol){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Se(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new cd(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>rs.mergeObjectSync(n,u)):rs.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Et.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Gt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Gt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return z4(this)}partial(t){let r={};for(let n of Gt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Gt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ad;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return SIe(Gt.objectKeys(this.shape))}};ec.create=(e,t)=>new ec({shape:()=>e,unknownKeys:"strip",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});ec.strictCreate=(e,t)=>new ec({shape:()=>e,unknownKeys:"strict",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});ec.lazycreate=(e,t)=>new ec({shape:e,unknownKeys:"strip",catchall:Ol.create(),typeName:Et.ZodObject,...Bt(t)});var q_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Qa(a.ctx.common.issues));return Se(r,{code:ye.invalid_union,unionErrors:s}),yt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new Qa(c));return Se(r,{code:ye.invalid_union,unionErrors:a}),yt}}get options(){return this._def.options}};q_.create=(e,t)=>new q_({options:e,typeName:Et.ZodUnion,...Bt(t)});var w0=e=>e instanceof L_?w0(e.schema):e instanceof ud?w0(e.innerType()):e instanceof z_?[e.value]:e instanceof H_?e.options:e instanceof F_?Gt.objectValues(e.enum):e instanceof V_?w0(e._def.innerType):e instanceof U_?[void 0]:e instanceof M_?[null]:e instanceof ad?[void 0,...w0(e.unwrap())]:e instanceof uf?[null,...w0(e.unwrap())]:e instanceof CT||e instanceof K_?w0(e.unwrap()):e instanceof $_?w0(e._def.innerType):[],Gj=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Se(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),yt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Se(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=w0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Et.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function _te(e,t){let r=af(e),n=af(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Gt.objectKeys(t),o=Gt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=_te(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Be.array&&n===Be.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=_te(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Be.date&&n===Be.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var D_=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Kj(o)||Kj(s))return yt;let a=_te(o.value,s.value);return a.valid?((Wj(o)||Wj(s))&&r.dirty(),{status:r.value,value:a.data}):(Se(n,{code:ye.invalid_intersection_types}),yt)};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(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};D_.create=(e,t,r)=>new D_({left:e,right:t,typeName:Et.ZodIntersection,...Bt(r)});var cf=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Se(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),yt;if(n.data.length<this._def.items.length)return Se(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yt;!this._def.rest&&n.data.length>this._def.items.length&&(Se(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new cd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>rs.mergeArray(r,s)):rs.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};cf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new cf({items:e,typeName:Et.ZodTuple,rest:null,...Bt(t)})};var Jj=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.object)return Se(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),yt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new cd(n,a,n.path,a)),value:s._parse(new cd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?rs.mergeObjectAsync(r,i):rs.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:Et.ZodRecord,...Bt(n)}):new e({keyType:dy.create(),valueType:t,typeName:Et.ZodRecord,...Bt(r)})}},V4=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.map)return Se(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),yt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new cd(n,a,n.path,[u,"key"])),value:o._parse(new cd(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};V4.create=(e,t,r)=>new V4({valueType:t,keyType:e,typeName:Et.ZodMap,...Bt(r)});var $4=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Se(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),yt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Se(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Se(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return yt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new cd(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};$4.create=(e,t)=>new $4({valueType:e,minSize:null,maxSize:null,typeName:Et.ZodSet,...Bt(t)});var Yj=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Se(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),yt;function n(a,c){return OT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,D4(),v0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return OT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,D4(),v0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof py){let a=this;return Ds(async function(...c){let u=new Qa([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Ds(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Qa([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Qa([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:cf.create(t).rest(E0.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||cf.create([]).rest(E0.create()),returns:r||E0.create(),typeName:Et.ZodFunction,...Bt(n)})}},L_=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};L_.create=(e,t)=>new L_({getter:e,typeName:Et.ZodLazy,...Bt(t)});var z_=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Se(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),yt}return{status:"valid",value:t.data}}get value(){return this._def.value}};z_.create=(e,t)=>new z_({value:e,typeName:Et.ZodLiteral,...Bt(t)});function SIe(e,t){return new H_({values:e,typeName:Et.ZodEnum,...Bt(t)})}var H_=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Se(r,{expected:Gt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Se(r,{received:r.data,code:ye.invalid_enum_value,options:n}),yt}return Ds(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};H_.create=SIe;var F_=class extends qt{_parse(t){let r=Gt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Gt.objectValues(r);return Se(n,{expected:Gt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(Gt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Gt.objectValues(r);return Se(n,{received:n.data,code:ye.invalid_enum_value,options:i}),yt}return Ds(t.data)}get enum(){return this._def.values}};F_.create=(e,t)=>new F_({values:e,typeName:Et.ZodNativeEnum,...Bt(t)});var py=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Se(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),yt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ds(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};py.create=(e,t)=>new py({type:e,typeName:Et.ZodPromise,...Bt(t)});var ud=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Et.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Se(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return yt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?yt:c.status==="dirty"?R_(c.value):r.value==="dirty"?R_(c.value):c});{if(r.value==="aborted")return yt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?yt:a.status==="dirty"?R_(a.value):r.value==="dirty"?R_(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);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 a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!uy(s))return yt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>uy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):yt);Gt.assertNever(i)}};ud.create=(e,t,r)=>new ud({schema:e,typeName:Et.ZodEffects,effect:t,...Bt(r)});ud.createWithPreprocess=(e,t,r)=>new ud({schema:t,effect:{type:"preprocess",transform:e},typeName:Et.ZodEffects,...Bt(r)});var ad=class extends qt{_parse(t){return this._getType(t)===Be.undefined?Ds(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ad.create=(e,t)=>new ad({innerType:e,typeName:Et.ZodOptional,...Bt(t)});var uf=class extends qt{_parse(t){return this._getType(t)===Be.null?Ds(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};uf.create=(e,t)=>new uf({innerType:e,typeName:Et.ZodNullable,...Bt(t)});var V_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Be.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};V_.create=(e,t)=>new V_({innerType:e,typeName:Et.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var $_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return L4(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qa(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Qa(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$_.create=(e,t)=>new $_({innerType:e,typeName:Et.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var K4=class extends qt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Se(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),yt}return{status:"valid",value:t.data}}};K4.create=e=>new K4({typeName:Et.ZodNaN,...Bt(e)});var Hwt=Symbol("zod_brand"),CT=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},RT=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?yt:o.status==="dirty"?(r.dirty(),R_(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?yt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Et.ZodPipeline})}},K_=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(uy(i)&&(i.value=Object.freeze(i.value)),i);return L4(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};K_.create=(e,t)=>new K_({innerType:e,typeName:Et.ZodReadonly,...Bt(t)});function wIe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function TIe(e,t={},r){return e?ly.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=wIe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=wIe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):ly.create()}var Fwt={object:ec.lazycreate},Et;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Et||(Et={}));var Vwt=(e,t={message:`Input not instance of ${e.name}`})=>TIe(r=>r instanceof e,t),L=dy.create,Tr=k_.create,$wt=K4.create,Kwt=N_.create,dd=B_.create,Wwt=j_.create,Gwt=H4.create,Jwt=U_.create,W4=M_.create,ld=ly.create,Ywt=E0.create,Zwt=Ol.create,Xwt=F4.create,ue=A0.create,fe=ec.create,Qwt=ec.strictCreate,G4=q_.create,e4t=Gj.create,t4t=D_.create,r4t=cf.create,Jt=Jj.create,n4t=V4.create,i4t=$4.create,o4t=Yj.create,s4t=L_.create,a4t=z_.create,pd=H_.create,c4t=F_.create,u4t=py.create,d4t=ud.create,l4t=ad.create,p4t=uf.create,f4t=ud.createWithPreprocess,m4t=RT.create,h4t=()=>L().optional(),y4t=()=>Tr().optional(),g4t=()=>dd().optional(),ou={string:(e=>dy.create({...e,coerce:!0})),number:(e=>k_.create({...e,coerce:!0})),boolean:(e=>B_.create({...e,coerce:!0})),bigint:(e=>N_.create({...e,coerce:!0})),date:(e=>j_.create({...e,coerce:!0}))};var b4t=yt;var v4t=pd(["enc","sig"]),w4t=pd(["markdown","plain"]),E4t=pd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),A4t=pd(["error","info","warning"]),Z4=pd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),x4t=pd(["completed","failed","pending"]),S4t=pd(["digital","pickup","shipping"]),T4t=pd(["fulfilled","partial","processing","removed"]),I4t=pd(["across","each"]),vte=pd(["pickup","shipping"]),P4t=fe({config:Jt(L(),ld()),config_schema:L(),id:L(),instrument_schemas:ue(L()),name:L(),spec:L(),version:L()}),O4t=fe({alg:L().optional(),crv:L().optional(),e:L().optional(),kid:L(),kty:L(),n:L().optional(),use:v4t.optional(),x:L().optional(),y:L().optional()}),C4t=fe({config:Jt(L(),ld()).optional(),extends:L().optional(),name:L(),schema:L(),spec:L(),version:L()}),R4t=fe({endpoint:L()}),k4t=fe({schema:L()}),IIe=fe({endpoint:L(),schema:L()}),N4t=IIe,B4t=IIe,ha=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional()}),no=fe({address_country:L().optional(),address_region:L().optional(),currency:L().optional(),eligibility:ue(L()).optional(),intent:L().optional(),language:L().optional(),postal_code:L().optional()}),wte=no,PIe=fe({id:L()}),j4t=PIe,U4t=PIe,kT=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional()}),Zj=fe({type:L()}),qi=fe({"dev.ucp.buyer_ip":L().optional(),"dev.ucp.user_agent":L().optional()}),Ete=qi,OIe=fe({id:L(),image_url:L().optional(),price:Tr(),title:L()}),Xj=fe({amount:Tr(),display_text:L().optional(),type:L()}),fy=fe({title:L().optional(),type:L(),url:L()}),x0=fe({code:L().optional(),content:L(),content_type:w4t.optional(),path:L().optional(),severity:E4t.optional(),type:A4t,image_url:L().optional(),presentation:L().optional(),url:L().optional()}),Ate=x0,X4=fe({id:L(),label:L().optional(),permalink_url:L()}),M4t=fe({amount:Tr(),display_text:L()}),q4t=fe({config:Jt(L(),ld()).optional(),extends:L().optional(),name:L(),schema:L().optional(),spec:L().optional(),version:L()}),xte=fe({id:L(),quantity:Tr()}),D4t=xte,L4t=xte,z4t=xte,H4t=fe({fulfilled:Tr(),original:Tr().optional(),total:Tr()}),F4t=fe({billing_address:kT.optional(),credential:Zj.optional(),display:Jt(L(),ld()).optional(),handler_id:L(),id:L(),type:L()}),V4t=fe({checkout_mandate:L()}),$4t=fe({merchant_authorization:L().optional(),checkout_mandate:L()}),K4t=fe({analytics:dd().optional(),marketing:dd().optional(),preferences:dd().optional(),sale_of_data:dd().optional()});var W4t=K4t;var CIe=fe({codes:ue(L()).optional()}),G4t=CIe,J4t=fe({amount:Tr(),path:L()}),Y4t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L().optional(),address:kT.optional(),name:L().optional()}),Z4t=fe({carrier:L().optional(),description:L().optional(),earliest_fulfillment_time:ou.date().optional(),id:L(),latest_fulfillment_time:ou.date().optional(),title:L(),totals:ue(Xj)}),X4t=fe({description:L().optional(),fulfillable_on:G4([W4(),L()]).optional(),line_item_ids:ue(L()),type:vte}),Q4t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L(),address:kT.optional(),name:L().optional()}),e8t=fe({max:Tr().optional(),min:Tr().optional()}),NT=fe({taxonomy:L().optional(),value:L()}),BT=fe({html:L().optional(),markdown:L().optional(),plain:L().optional()}),J4=fe({amount:Tr(),currency:L()}),jT=fe({alt_text:L().optional(),height:Tr().optional(),type:L(),url:L(),width:Tr().optional()}),t8t=fe({id:L().optional(),label:L()}),UT=fe({count:Tr().optional(),scale_max:Tr(),scale_min:Tr().optional(),value:Tr()}),RIe=fe({available:dd().optional(),status:L().optional()}),r8t=RIe,kIe=fe({type:L(),value:L()}),n8t=kIe,i8t=fe({id:L(),match:L().optional()}),Ste=fe({id:L().optional(),label:L(),name:L()}),NIe=Ste,BIe=fe({links:ue(fy).optional(),name:L().optional()}),o8t=BIe,jIe=fe({unit:L(),value:Tr()});var s8t=jIe,a8t=fe({cursor:L().optional(),limit:Tr().optional()}),c8t=fe({cursor:L().optional(),has_next_page:dd(),total_count:Tr().optional()}),u8t=fe({handlers:ue(P4t).optional()}),d8t=fe({a2a:R4t.optional(),embedded:k4t.optional(),mcp:N4t.optional(),rest:B4t.optional(),spec:L(),version:L()}),Q4=fe({item:j4t,quantity:Tr()}),l8t=fe({billing_address:kT.optional(),credential:Zj.optional(),display:Jt(L(),ld()).optional(),handler_id:L(),id:L(),type:L(),selected:dd().optional()}),MT=fe({id:L().optional(),item:U4t,parent_id:L().optional(),quantity:Tr()}),Qj=fe({instruments:ue(l8t).optional()}),p8t=Qj,qT=Qj,e8=Qj,eU=Qj,W_=fe({id:L(),item:OIe,parent_id:L().optional(),quantity:Tr(),totals:ue(Xj)}),my=fe({amount:Tr(),display_text:L().optional(),type:L(),lines:ue(M4t).optional()}),Cl=fe({capabilities:Jt(L(),ue(q4t)),version:L()}),f8t=fe({description:L().optional(),id:L(),line_items:ue(D4t).optional(),occurred_at:ou.date(),status:x4t,totals:ue(Xj).optional(),type:L()}),m8t=fe({carrier:L().optional(),description:L().optional(),id:L(),line_items:ue(L4t),occurred_at:ou.date(),tracking_number:L().optional(),tracking_url:L().optional(),type:L()}),h8t=fe({description:L().optional(),destination:kT,fulfillable_on:L().optional(),id:L(),line_items:ue(z4t),method_type:S4t}),y8t=fe({id:L(),item:OIe,parent_id:L().optional(),quantity:H4t,status:T4t,totals:ue(Xj)}),Dkr=fe({payment_data:F4t}),Lkr=fe({ap2:V4t.optional()}),zkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,ap2:$4t.optional()}),Tte=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),consent:W4t.optional()}),g8t=Tte,b8t=Tte,UIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional(),discounts:G4t.optional()}),_8t=fe({allocations:ue(J4t).optional(),amount:Tr(),automatic:dd().optional(),code:L().optional(),eligibility:L().optional(),method:I4t.optional(),priority:Tr().optional(),provisional:dd().optional(),title:L()}),MIe=fe({id:L(),line_item_ids:ue(L()),options:ue(Z4t).optional(),selected_option_id:G4([W4(),L()]).optional()}),v8t=fe({destinations:ue(Q4t).optional(),groups:ue(MIe).optional(),id:L(),line_item_ids:ue(L()),selected_destination_id:G4([W4(),L()]).optional(),type:vte}),Hkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),signals:qi.optional()}),Fkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),id:L(),line_items:ue(MT),signals:qi.optional()}),Vkr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy).optional(),messages:ue(x0).optional(),signals:qi.optional(),totals:ue(my),ucp:Cl}),w8t=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional()}),qIe=w8t,$kr=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,cart_id:L().optional()}),Ite=fe({categories:ue(L()).optional(),price:e8t.optional()}),Y4=fe({max:J4,min:J4}),Pte=fe({name:L(),values:ue(t8t)}),DIe=fe({amount:Tr(),currency:L(),measure:jIe,reference:s8t}),E8t=DIe,Kkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),id:L(),preferences:ue(L()).optional(),selected:ue(NIe).optional(),signals:Ete.optional()}),Wkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),pagination:a8t.optional(),query:L().optional(),signals:Ete.optional()}),A8t=fe({capabilities:ue(C4t),services:Jt(L(),d8t),version:L()}),Gkr=fe({attribution:Jt(L(),L()).optional(),payment:p8t,signals:qi.optional()}),LIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl}),x8t=fe({events:ue(m8t).optional(),expectations:ue(h8t).optional()}),zIe=fe({attribution:Jt(L(),L()).optional(),buyer:Tte.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional()}),HIe=fe({attribution:Jt(L(),L()).optional(),buyer:b8t.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional()}),FIe=fe({attribution:Jt(L(),L()).optional(),buyer:g8t.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl}),VIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),discounts:CIe.optional()}),S8t=fe({applied:ue(_8t).optional(),codes:ue(L()).optional()}),T8t=fe({destinations:ue(Y4t).optional(),groups:ue(MIe).optional(),line_item_ids:ue(L()).optional(),selected_destination_id:G4([W4(),L()]).optional(),type:vte}),I8t=fe({available_methods:ue(X4t).optional(),methods:ue(v8t).optional()}),$Ie=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),cart_id:L().optional()}),Jkr=fe({attribution:Jt(L(),L()).optional(),context:wte.optional(),filters:Ite.optional(),ids:ue(L()),signals:Ete.optional()}),P8t=fe({availability:RIe.optional(),barcodes:ue(kIe).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price:J4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Ste).optional(),price:J4,rating:UT.optional(),seller:BIe.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:DIe.optional(),url:L().optional(),inputs:ue(i8t)}),KIe=fe({availability:r8t.optional(),barcodes:ue(n8t).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price:J4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Ste).optional(),price:J4,rating:UT.optional(),seller:o8t.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:E8t.optional(),url:L().optional()}),O8t=fe({categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Pte).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(KIe)}),Ykr=fe({payment:u8t.optional(),signing_keys:ue(O4t).optional(),ucp:A8t}),WIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional()}),C8t=fe({adjustments:ue(f8t).optional(),attribution:Jt(L(),L()).optional(),checkout_id:L(),currency:L(),fulfillment:x8t,id:L(),label:L().optional(),line_items:ue(y8t),messages:ue(x0).optional(),permalink_url:L(),totals:ue(my),ucp:Cl}),GIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,discounts:S8t.optional()}),JIe=fe({methods:ue(T8t).optional()}),YIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(MT),payment:eU.optional(),signals:qi.optional(),fulfillment:JIe.optional()}),ZIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),continue_url:L().optional(),currency:L(),expires_at:ou.date().optional(),id:L(),line_items:ue(W_),links:ue(fy),messages:ue(x0).optional(),order:X4.optional(),payment:e8.optional(),signals:qi.optional(),status:Z4,totals:ue(my),ucp:Cl,fulfillment:I8t.optional()}),R8t=fe({categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),options:ue(Pte).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(P8t)}),k8t=fe({options:ue(Pte).optional(),selected:ue(NIe).optional(),categories:ue(NT).optional(),description:BT,handle:L().optional(),id:L(),list_price_range:Y4.optional(),media:ue(jT).optional(),metadata:Jt(L(),ld()).optional(),price_range:Y4,rating:UT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(KIe)}),Zkr=fe({messages:ue(Ate).optional(),pagination:c8t.optional(),products:ue(O8t),ucp:Cl}),XIe=fe({attribution:Jt(L(),L()).optional(),buyer:ha.optional(),context:no.optional(),line_items:ue(Q4),payment:qT.optional(),signals:qi.optional(),fulfillment:JIe.optional()}),Xkr=fe({messages:ue(Ate).optional(),products:ue(R8t),ucp:Cl}),Qkr=fe({messages:ue(Ate).optional(),product:k8t,ucp:Cl});var nNr=Zj.extend({token:Ur.string().optional()}),N8t=Ur.object({webhook_url:Ur.string().url().optional()}),QIe=LIe.extend(ZIe.pick({fulfillment:!0}).shape).extend(GIe.pick({discounts:!0}).shape).extend(FIe.pick({buyer:!0}).shape).extend({platform:N8t.optional()}),ePe=WIe.extend(XIe.pick({fulfillment:!0}).shape).extend(VIe.pick({discounts:!0}).shape).extend(zIe.pick({buyer:!0}).shape).extend($Ie.pick({cart_id:!0}).shape),tPe=qIe.extend(YIe.pick({fulfillment:!0}).shape).extend(UIe.pick({discounts:!0}).shape).extend(HIe.pick({buyer:!0}).shape);xl();async function tU(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function rU(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var B8t=3e4,rPe=2*1024*1024,Rl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function nPe(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function iPe(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?ePe:tPe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function j8t(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function oPe(e,t,r,n){try{e[t](r,n)}catch{}}function U8t(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var nU=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=nPe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=nPe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??B8t,this.boundaryLogger=t.logger??Ne}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:iPe(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:iPe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=rU(this.timeoutMs,this.signal),o=(0,sPe.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await tU(u,rPe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Rl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>rPe)throw new Rl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Rl("UCP MCP response is not valid JSON",void 0,u.status)}if(!j8t(l))throw new Rl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Rl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Rl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Rl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Rl("UCP MCP response is missing result.structuredContent");if(!QIe.safeParse(U8t(p.structuredContent)).success)throw new Rl("UCP checkout response failed schema validation");return oPe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw oPe(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var cPe=require("node:crypto");xl();var oU="2026-04-08",M8t="dev.ucp.shopping",q8t="dev.ucp.shopping.checkout",D8t=1024*1024,L8t=1e4,z8t="https://ucp.dev",DT=Ur.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),H8t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:DT,schema:DT,transport:Ur.enum(["rest","mcp","a2a","embedded"]),endpoint:DT.optional()}).passthrough(),F8t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:DT,schema:DT,extends:Ur.union([Ur.string(),Ur.array(Ur.string()).min(1)]).optional()}).passthrough(),V8t=Ur.object({ucp:Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Ur.record(Ur.array(H8t)),capabilities:Ur.record(Ur.array(F8t)),payment_handlers:Ur.record(Ur.array(Ur.unknown())).optional()}).passthrough(),signing_keys:Ur.array(Ur.unknown()).optional()}).passthrough();function $8t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function iU(e,t){if(new URL(e).origin!==z8t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function aPe(e,t,r,n){try{e[t](r,n)}catch{}}async function K8t(e,t={}){let r=$8t(e,"UCP business URL"),n=rU(t.timeoutMs??L8t,t.signal),i=t.logger??Ne,o=(0,cPe.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await tU(c,D8t,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=V8t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return aPe(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw aPe(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function W8t(e){if(e.ucp.version!==oU)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[q8t]?.find(i=>i.version===oU);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");iU(t.spec,"Checkout capability spec"),iU(t.schema,"Checkout capability schema");let r=e.ucp.services[M8t]?.find(i=>i.version===oU&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");iU(r.spec,"Shopping service spec"),iU(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function uPe(e,t={}){let r=await K8t(e,t);return{...r,endpoint:W8t(r.profile),version:oU}}var G8t="https://app.visacli.sh/.well-known/ucp";function J8t(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function Y8t(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Ote(e,t=new Set){if(Array.isArray(e))for(let r of e)Ote(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?Y8t(n,t):Ote(n,t);return t}function Z8t(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Ote(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function lPe(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function X8t(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function pPe(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??uPe)(e.business),i=await(t.getCheckout??(async(o,s)=>await new nU({endpoint:o.endpoint,platformProfileUrl:J8t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??G8t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function fPe(e,t={}){let{service:r,checkout:n}=await pPe(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=lPe(n),s=Z8t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,dPe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:X8t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function Q8t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function mPe(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await pPe(e,t),n=lPe(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=Q8t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}p4();function Cte(){return td()}var Ao=new m4(()=>Ya.getSessionToken()),e3t="4.1.0-rc.53",MNr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
|
|
20829
20829
|
`);function t3t(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=KS(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(n9e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=$S();if(r.headless)return Ne.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[Cte(),qh()].filter(s=>!!s).map(s=>q9e(t,s)).find(Boolean)??null;if(!i)return Ne.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=L9e(i);return o?((0,yPe.execFile)(o.cmd,o.args,s=>{s&&Ne.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Ne.info(`No browser command for platform "${aU.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function r3t(){let e=!1,t;try{let n=gPe.join(aU.homedir(),".claude","settings.json");if(sU.existsSync(n)){let i=JSON.parse(sU.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=$7e(o)}}catch{}let r=zj();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function n3t(e){let t=await Ao.getStatus(e);t.hud=r3t(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable the Visa HUD with `visa-cli config hud enable`."),t.version=e3t;try{let r=ef();if(r){let n=await Ao.getAgentTapStatus(r.identity_key.jkt);n&&(t.tap={status:n.status,registeredAt:n.registeredAt})}}catch(r){Ne.warn({component:"get-status-tap",msg:"tap_status_unavailable",error:r?.message})}return t}async function i3t(e,t){return await Ao.feedback(e.message,e.transaction_id,t)}async function o3t(e){let t=await W7e({api:Ao,includeDev:!!e.includeDev});return{config:t.entries.map(r=>({key:r.key,value:r.value,source:r.source,hint:r.hint})),statusError:t.statusError}}var Rte=new Set(["auth.serverUrl"]);function LT(){return Object.keys(FS).filter(e=>!Rte.has(e)).sort()}function bPe(e,t){let r=t==="set"?`visa-cli config set ${e}=<value>`:`visa-cli config unset ${e}`;return{success:!1,error:`${e} cannot be changed via MCP. Run \`${r}\` directly from a shell instead.`,code:"MCP_FORBIDDEN_KEY",reason:"auth-trust-boundary key \u2014 a prompt-injected agent could redirect bearer-auth API calls to an attacker host (codex CLI-001 #752).",settableKeys:LT()}}async function s3t(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};if(Rte.has(e.key))return Ne.warn("config:set:rejected:mcp-forbidden",{key:e.key}),bPe(e.key,"set");Ne.info("config:set",{key:e.key});try{let t=t9e(e.key,e.value);return Ne.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let r=t instanceof s0?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof s0?`Unknown setting "${e.key}". MCP-settable keys: ${LT().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ne.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:LT()}}}async function a3t(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};if(Rte.has(e.key))return Ne.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),bPe(e.key,"unset");Ne.info("config:unset",{key:e.key});try{let t=r9e(e.key);return Ne.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let r=t instanceof s0?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof s0?`Unknown setting "${e.key}". MCP-settable keys: ${LT().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ne.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:LT()}}}async function c3t(e=Cte(),t=!1){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};if(!t){let r=ef();if(r){let n=r.display_name,i;if(process.env.SUBWAY_MESH==="visa"&&n){let{registerOnVisaMeshIfEnabled:s}=await Promise.resolve().then(()=>(Pj(),z7e));i=await s(n)}Ne.info("agent:enroll_already_connected",{keyBound:!0,meshRegistered:i});let o=i===void 0?"":i?` Registered ${n??"this device"} on the .visa mesh.`:` Could not reach the .visa mesh \u2014 run \`visa register ${n??"<name>"}\` to join it.`;return{success:!0,alreadyConnected:!0,...n?{name:n}:{},keyBound:!0,...i!==void 0?{meshRegistered:i}:{},message:`This device is already connected${n?` as ${n}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).`+o+' Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.'}}}try{let r=await hT({authUrl:e,runtime:"visa-cli-mcp",contextLabel:"Pair this MCP runtime"});Ne.info("agent:pairing_open",{pairingId:r.pairingId,agentId:r.agentId});let n=t3t(r.authorizationUrl),i=n.url??r.authorizationUrl;return{success:!0,protocolVersion:r.protocolVersion,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:r.requestKeyFingerprint,opened:n.opened,requiresBrowser:!n.opened,browserUrl:i,expiresAt:r.expiresAt,message:n.opened?`Opened the authorization page for agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, approve the runtime, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`:`Open ${i} to approve agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`}}catch(r){return{success:!1,message:r instanceof Error?r.message:String(r)}}}async function u3t(e=Cte()){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};let t=await yT({authUrl:e});switch(Ne.info("agent:enroll_claim",{status:t.status}),t.status){case"activated":return{success:!0,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,displayName:t.displayName,identityKeyJkt:t.identityKeyJkt,message:`Agent ${t.displayName} (${t.agentId}) is paired to this runtime. Its exportable Ed25519 private identity key remains in an owner-only local file. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet. Payment methods and communication channels are configured separately.`};case"no_pending":return{success:!1,message:'No pairing is in progress on this device \u2014 call enroll_agent with {"action":"start"} first.'};case"not_ready":return{success:!1,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:t.likelyExpired,message:t.likelyExpired?"This pairing has likely expired. Start a fresh pairing ceremony.":`Authorization is not complete for agent ${t.agentId}. Approve the browser request, then claim again.`};case"error":return{success:!1,message:t.message}}}async function hPe(){if(await Ya.clearAll(),!!B9e())try{await j9e()}catch(e){Ne.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function d3t(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Ne.info("reset:attempt"),e.localOnly)return await hPe(),Ne.info("reset:success",{localOnly:!0}),{success:!0,message:"Device account state reset locally. The account session credential and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."};try{await Ao.logout(void 0,t)}catch{}return await hPe(),Ne.info("reset:success"),{success:!0,message:"Device account state reset. The server session, local account credential, and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."}}async function l3t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(I_(),wT)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{VisaBindingRequiredError:r}=await Promise.resolve().then(()=>(eT(),zxe));return t instanceof r?{success:!1,binding_required:!0,reason:t.reason,recovery_tool:null,error:t.message,message:`${t.message} Pairing alone does not provision a .visa name or TAP/channel binding.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function p3t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(I_(),wT));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function f3t(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:r}=await Promise.resolve().then(()=>(I_(),wT)),n=e.as??r(void 0);return{success:!0,...await t(n,e.to,e.text)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function m3t(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(I_(),wT)),i=e.as??r(void 0),o=await t(i,e.limit??20,!!e.clear);return{success:!0,as:n(i),count:o.length,messages:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}var io=class{static async subwayRegister(t){return l3t(t||{})}static async subwayFind(t){return p3t(t||{})}static async subwaySend(t){return f3t(t||{})}static async subwayInbox(t){return m3t(t||{})}static async getStatus(t){return n3t(t)}static async feedback(t,r){return i3t(t,r)}static async configList(t){return o3t(t||{})}static async configSet(t){return s3t(t||{})}static async configUnset(t){return a3t(t||{})}static async reset(t,r){return d3t(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?c3t(void 0,t?.force===!0):n==="claim"?u3t():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens identity-pairing approval) or "claim" (activates the approved identity on this runtime).`}}static async payMerchant(t={},r){return gIe(t)}static async ucpCheckoutHandoff(t,r){return iu("ucp_checkout_handoff")&&(await O_(),iu("ucp_checkout_handoff"))?{success:!1,message:"ucp_checkout_handoff requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."}:fPe(t)}static async ucpCheckoutReconcile(t,r){if(iu("ucp_checkout_reconcile")&&(await O_(),iu("ucp_checkout_reconcile")))return{success:!1,message:"ucp_checkout_reconcile requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=Date.now(),i=(()=>{try{return new URL(t.business).hostname}catch{return"invalid"}})();Ne.info("ucp_checkout_reconcile:start",{businessHost:i});try{let o=await mPe(t);return Ne.info("ucp_checkout_reconcile:complete",{businessHost:i,checkoutStatus:o.checkoutStatus,reconciliationStatus:o.status,durationMs:Date.now()-n}),o}catch(o){throw Ne.warn("ucp_checkout_reconcile:failed",{businessHost:i,durationMs:Date.now()-n,errorName:o instanceof Error?o.name:"unknown"}),o}}static async payMerchantStatus(t={},r){return yIe(t)}static async startCardMandate(t={},r){return bIe(t)}static async submitFeedback(t,r,n){Ne.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await Ao.submitFeedback(t,r,n);return Ne.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Ne.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Ne.info("feedback:list",{limit:t||20});try{let n=await Ao.getFeedback(t,r);return Ne.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Ne.error("feedback:error",{error:i}),n}}};function _Pe(e){return e==="pay_merchant"}xl();var Qyt="VISA_V4_WALLET_EXPERIMENT",iOr=null;function oOr(){return iOr??!0}var sOr=new Set(["1","true","on","yes"]),aOr=new Set(["0","false","off","no"]),egt=!1;function TAe(e,t){return egt||(egt=!0,Ne.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function OX(){let e=(process.env[Qyt]??"").trim().toLowerCase();if(sOr.has(e))return TAe(!0,"env-on");if(aOr.has(e))return TAe(!1,"env-off");e!==""&&Ne.warn("wallet-experiment:unrecognized-env-value",{env:Qyt,fallback:"bundled-runtime"});let t=oOr();return TAe(t,t?"bundled-runtime":"runtime-unavailable")}var tgt=null;function rgt(){return tgt??=SAe(),tgt}var cOr={user_context:{type:"string",description:"The exact verbatim request the user made that prompted this tool call. Always include the user's full original message."}};function uOr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...cOr},required:[...e.inputSchema.required||[],"user_context"]}}}function IAe(){return OX()?rgt().WALLET_TOOL_DEFS.map(uOr):[]}function ngt(e){return OX()?rgt().WALLET_TOOL_NAMES.includes(e):!1}async function igt(e,t,r={}){let i=await(await Promise.resolve().then(()=>Me(SAe()))).dispatchWalletTool(e,t,{logger:Ne,merchantDirectorySearch:r.merchantDirectorySearch});if(r.emitTelemetry&&(e==="wallet_pay"||e==="wallet_directory_pay"))try{let o=dOr(e,t,i);o&&await r.emitTelemetry([o])}catch(o){Ne.warn("wallet-experiment:telemetry-failed",{tool:e,error:o instanceof Error?o.message:String(o)})}return i}function dOr(e,t,r){if(e!=="wallet_pay"&&e!=="wallet_directory_pay")return null;let n=r.payment&&typeof r.payment=="object"&&!Array.isArray(r.payment)?r.payment:null,i=r.receipt&&typeof r.receipt=="object"&&!Array.isArray(r.receipt)?r.receipt:null,o=r.status==="reconciling"&&r.settled===!1&&r.authorizationDisclosed===!0&&r.reservationRecorded===!0&&n?.status==="indeterminate",s=r.settled===!1&&r.authorizationDisclosed===!0&&n?.status==="indeterminate";if(!o&&!i&&!s)return null;let a=o?n:i??n,c=typeof a.exposureUsd=="string"?a.exposureUsd:typeof a.amountUsd=="string"?a.amountUsd:"",u=Number(c.replace(/[$,\s]/g,""));if(!Number.isFinite(u)||u<=0)return null;let d=r.directory&&typeof r.directory=="object"&&!Array.isArray(r.directory)?r.directory:null,l=d?.selection&&typeof d.selection=="object"&&!Array.isArray(d.selection)?d.selection:null,p=typeof t.url=="string"?t.url:typeof l?.url=="string"?l.url:"",f="Pay-per-use service";try{f=new URL(p).hostname.toLowerCase()}catch{}let m=typeof a.timestamp=="string"?a.timestamp:new Date().toISOString(),h=typeof a.network=="string"?a.network:null,y=typeof a.scheme=="string"?a.scheme:null,v=typeof a.merchantReportedTxHash=="string"?a.merchantReportedTxHash:typeof a.txHash=="string"?a.txHash:null,E=typeof a.authorizationRef=="string"?a.authorizationRef:typeof a.settlementHash=="string"?a.settlementHash:null,_=r.response&&typeof r.response=="object"&&!Array.isArray(r.response)?r.response:null,w=typeof _?.status=="number"&&Number.isInteger(_.status)?_.status:null;return{timestamp:m,tool_name:e,user_prompt:"",tool_params:JSON.stringify({merchant_host:f,network:h,scheme:y}),result_success:!0,result_error:null,result_json:JSON.stringify(o?{status:"reconciling",settled:!1,authorizationDisclosed:!0,reservationRecorded:!0,payment:{status:"indeterminate",network:h,scheme:y,...E?{authorizationRef:E}:{},...v?{merchantReportedTxHash:v}:{}}}:{status:"unverified",authorizationDisclosed:!0,reservationRecorded:!1,payment:{status:"legacy_unverified",network:h,scheme:y,...E?{authorizationRef:E}:{},...v?{merchantReportedTxHash:v}:{}}}),payment_rail:"stablecoin",payment_amount:u,payment_currency:"USDC",merchant_name:f,transaction_id:null,tx_hash:null,protocol:"x402",http_status:w,duration_ms:0,source:"cli",endpoint:"/v4/wallet",resolved_model:null,session_budget_id:null}}xl();var PAe=["pay_merchant"],lOr={pay_merchant:"merchant checkout"};function pOr(e){return lOr[e]||e}var ogt={};function sgt(e){let t=ogt[e]??0;return ogt[e]=t+1,t}function agt(e,t,r){return PAe.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${pOr(e)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:r}}:t%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:r}}:{}:{}}var RX=Me(require("crypto")),kX=Me(require("tty")),a4=Me(require("fs")),CAe=Me(require("os")),CX=Me(require("path"));ZX();h4();var fOr=new Set(["connect","disconnect","connections"]);function mOr(e){return e!==void 0&&fOr.has(e)}function hOr(e){return/-rc\.|-beta\./.test(e)}function OAe(e){return RX.createHash("sha256").update(e.trim()).digest("hex")}function cgt(e){return a0==="SKIP"?!0:RX.timingSafeEqual(Buffer.from(OAe(e)),Buffer.from(a0))}function yOr(){return CX.join(CAe.homedir(),".visa-mcp","agent-credential.json")}function gOr(){let e=process.env.VISA_V4_HOME||CX.join(CAe.homedir(),".visa-v4");return CX.join(e,"turnkey.json")}function bOr(){try{let e=a4.readFileSync(yOr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=a4.readFileSync(gOr(),"utf8"),t=JSON.parse(e);return typeof t?.organizationId=="string"&&t.organizationId.length>0&&typeof t?.walletId=="string"&&t.walletId.length>0&&typeof t?.address=="string"&&/^0x[0-9a-f]{40}$/i.test(t.address)}catch{return!1}}function _Or(){try{let e=a4.openSync("/dev/tty","r+"),t=new kX.ReadStream(e),r=new kX.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{a4.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function vOr(e){return new Promise((t,r)=>{let n;try{n=_Or()}catch(d){r(d);return}let{input:i,output:o,cleanupStreams:s}=n,a=()=>{i.off("data",u);try{i.setRawMode?.(!1)}catch{}s()};o.write(e),i.setRawMode?.(!0),i.resume(),i.setEncoding("utf8");let c="",u=d=>{d==="\r"||d===`
|
|
20830
20830
|
`?(o.write(`
|
|
20831
20831
|
`),a(),t(c)):d===""?(o.write(`
|