@visa/cli 4.1.0-rc.41 → 4.1.0-rc.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";var l_t=Object.create;var YB=Object.defineProperty;var p_t=Object.getOwnPropertyDescriptor;var f_t=Object.getOwnPropertyNames;var m_t=Object.getPrototypeOf,h_t=Object.prototype.hasOwnProperty;var R=(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}},Pi=(e,t)=>{for(var r in t)YB(e,r,{get:t[r],enumerable:!0})},mxe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of f_t(t))!h_t.call(e,i)&&i!==r&&YB(e,i,{get:()=>t[i],enumerable:!(n=p_t(t,i))||n.enumerable});return e};var _e=(e,t,r)=>(r=e!=null?l_t(m_t(e)):{},mxe(t||!e||!e.__esModule?YB(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>mxe(YB({},"__esModule",{value:!0}),e);var y0,JQ=R(()=>{"use strict";y0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function YQ(e){return`${e}-${bxe.randomBytes(24).toString("base64url")}`}function vxe(e=process.env){return e.NODE_ENV==="test"||e[_xe]==="true"}function Yh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&vxe(e)}function hT(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&vxe(e)}function ZQ(){return`Set ${_xe}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function wxe(){return hxe??=YQ("mock-session"),hxe}function Exe(e=process.env){return e.NODE_ENV==="test"?y0:(yxe??=YQ("mock-rc"),yxe)}function Axe(){return gxe??=YQ("mock-signature"),gxe}var bxe,_xe,hxe,yxe,gxe,ZB=R(()=>{"use strict";bxe=_e(require("crypto"));JQ();_xe="VISA_ALLOW_INSECURE_MOCKS"});function g_t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
|
|
2
|
-
`)}function nee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=g_t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function tf(){return process.platform!=="darwin"?Promise.resolve(!1):(xxe??=(async()=>{try{return await Ol("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return nee(e)}})(),xxe)}async function b_t(){if(!await tf())return null;try{let{stdout:e}=await Ol("security",["find-generic-password","-s",cd,"-a",Zh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(nee(e))throw new QB("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 __t(e){if(!await tf())return!1;try{try{await Ol("security",["delete-generic-password","-s",cd,"-a",Zh],{timeout:5e3})}catch{}return await Ol("security",["add-generic-password","-s",cd,"-a",Zh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function v_t(){if(await tf())try{await Ol("security",["delete-generic-password","-s",cd,"-a",Zh],{timeout:5e3})}catch{}}async function w_t(){if(!iee())return null;try{let{stdout:e}=await Ol("secret-tool",["lookup","service",cd,"account",Zh],{timeout:5e3});return e.trim()||null}catch{return null}}async function E_t(e){if(!iee())return!1;try{let t=(0,ej.execFile)("secret-tool",["store","--label",`${cd} ${Zh}`,"service",cd,"account",Zh]);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"))},y_t))]),!0):!1}catch{return!1}}async function A_t(){if(iee())try{await Ol("secret-tool",["clear","service",cd,"account",Zh],{timeout:5e3})}catch{}}function iee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function x_t(){if(!await tf())return null;try{let{stdout:e}=await Ol("security",["find-generic-password","-s",cd,"-a",XB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function S_t(e){if(await tf())try{try{await Ol("security",["delete-generic-password","-s",cd,"-a",XB],{timeout:5e3})}catch{}await Ol("security",["add-generic-password","-s",cd,"-a",XB,"-w",e],{timeout:5e3})}catch{}}async function T_t(){if(await tf())try{await Ol("security",["delete-generic-password","-s",cd,"-a",XB],{timeout:5e3})}catch{}}function QQ(){try{return Xh.readFileSync(yT,"utf-8").trim()||null}catch(e){if(nee(e))throw new QB(`Unable to read Visa CLI credentials from ${yT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Txe(e){Xh.mkdirSync(ree,{recursive:!0,mode:448}),Xh.writeFileSync(yT,e,{mode:384}),process.platform==="win32"&&I_t(yT)}function eee(){try{Xh.unlinkSync(yT)}catch{}}function I_t(e){try{let t=tj.userInfo().username;(0,ej.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 XQ(){switch(process.platform){case"darwin":return{get:b_t,store:__t,delete:v_t};case"linux":return{get:w_t,store:E_t,delete:A_t};default:return{get:async()=>QQ(),store:async e=>{try{return Txe(e),!0}catch{return!1}},delete:async()=>eee(),storesInSessionFile:!0}}}var ej,Sxe,Xh,tj,tee,Ol,ree,yT,cd,Zh,XB,y_t,QB,xxe,ei,Qh=R(()=>{"use strict";ej=require("child_process"),Sxe=require("util"),Xh=_e(require("fs")),tj=_e(require("os")),tee=_e(require("path"));ZB();Ol=(0,Sxe.promisify)(ej.execFile),ree=tee.join(tj.homedir(),".visa-mcp"),yT=tee.join(ree,"session-token"),cd="visa-cli",Zh="session-token",XB="rc-access",y_t=5e3,QB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};xxe=null;ei=class{static async getSessionToken(){if(Yh())return Promise.resolve(wxe());let t=XQ(),r=await t.get();if(r)return r;let n=QQ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(Yh())return;let r=XQ();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||eee();return}await r.delete()}if(Txe(t),QQ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ree} is writable.`))}static async getRcAccessToken(){return Yh()?Exe():x_t()}static async saveRcAccessToken(t){Yh()||await S_t(t)}static async deleteSessionToken(){if(Yh())return;await XQ().delete(),eee()}static async clearAll(){await this.deleteSessionToken(),await T_t()}}});var rj=g((ANr,P_t)=>{P_t.exports={name:"@visa/cli",version:"4.1.0-rc.
|
|
2
|
+
`)}function nee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=g_t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function tf(){return process.platform!=="darwin"?Promise.resolve(!1):(xxe??=(async()=>{try{return await Ol("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return nee(e)}})(),xxe)}async function b_t(){if(!await tf())return null;try{let{stdout:e}=await Ol("security",["find-generic-password","-s",cd,"-a",Zh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(nee(e))throw new QB("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 __t(e){if(!await tf())return!1;try{try{await Ol("security",["delete-generic-password","-s",cd,"-a",Zh],{timeout:5e3})}catch{}return await Ol("security",["add-generic-password","-s",cd,"-a",Zh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function v_t(){if(await tf())try{await Ol("security",["delete-generic-password","-s",cd,"-a",Zh],{timeout:5e3})}catch{}}async function w_t(){if(!iee())return null;try{let{stdout:e}=await Ol("secret-tool",["lookup","service",cd,"account",Zh],{timeout:5e3});return e.trim()||null}catch{return null}}async function E_t(e){if(!iee())return!1;try{let t=(0,ej.execFile)("secret-tool",["store","--label",`${cd} ${Zh}`,"service",cd,"account",Zh]);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"))},y_t))]),!0):!1}catch{return!1}}async function A_t(){if(iee())try{await Ol("secret-tool",["clear","service",cd,"account",Zh],{timeout:5e3})}catch{}}function iee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function x_t(){if(!await tf())return null;try{let{stdout:e}=await Ol("security",["find-generic-password","-s",cd,"-a",XB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function S_t(e){if(await tf())try{try{await Ol("security",["delete-generic-password","-s",cd,"-a",XB],{timeout:5e3})}catch{}await Ol("security",["add-generic-password","-s",cd,"-a",XB,"-w",e],{timeout:5e3})}catch{}}async function T_t(){if(await tf())try{await Ol("security",["delete-generic-password","-s",cd,"-a",XB],{timeout:5e3})}catch{}}function QQ(){try{return Xh.readFileSync(yT,"utf-8").trim()||null}catch(e){if(nee(e))throw new QB(`Unable to read Visa CLI credentials from ${yT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Txe(e){Xh.mkdirSync(ree,{recursive:!0,mode:448}),Xh.writeFileSync(yT,e,{mode:384}),process.platform==="win32"&&I_t(yT)}function eee(){try{Xh.unlinkSync(yT)}catch{}}function I_t(e){try{let t=tj.userInfo().username;(0,ej.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 XQ(){switch(process.platform){case"darwin":return{get:b_t,store:__t,delete:v_t};case"linux":return{get:w_t,store:E_t,delete:A_t};default:return{get:async()=>QQ(),store:async e=>{try{return Txe(e),!0}catch{return!1}},delete:async()=>eee(),storesInSessionFile:!0}}}var ej,Sxe,Xh,tj,tee,Ol,ree,yT,cd,Zh,XB,y_t,QB,xxe,ei,Qh=R(()=>{"use strict";ej=require("child_process"),Sxe=require("util"),Xh=_e(require("fs")),tj=_e(require("os")),tee=_e(require("path"));ZB();Ol=(0,Sxe.promisify)(ej.execFile),ree=tee.join(tj.homedir(),".visa-mcp"),yT=tee.join(ree,"session-token"),cd="visa-cli",Zh="session-token",XB="rc-access",y_t=5e3,QB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};xxe=null;ei=class{static async getSessionToken(){if(Yh())return Promise.resolve(wxe());let t=XQ(),r=await t.get();if(r)return r;let n=QQ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(Yh())return;let r=XQ();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||eee();return}await r.delete()}if(Txe(t),QQ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ree} is writable.`))}static async getRcAccessToken(){return Yh()?Exe():x_t()}static async saveRcAccessToken(t){Yh()||await S_t(t)}static async deleteSessionToken(){if(Yh())return;await XQ().delete(),eee()}static async clearAll(){await this.deleteSessionToken(),await T_t()}}});var rj=g((ANr,P_t)=>{P_t.exports={name:"@visa/cli",version:"4.1.0-rc.42",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:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0","@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 gT(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 L_t(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(`
|
|
3
3
|
`)}function bT(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 Bxe(e,t){let r=bT(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 jxe(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 Uxe(e,t=process.platform){let r=bT(e);return r?jxe(r,t):null}function kxe(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function __(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=bT(e),s=t.spawn??((u,d,l)=>{(0,Nxe.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 L_t(o??e).split(`
|
|
4
4
|
`))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=gT(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=jxe(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?kxe(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){kxe(r,l instanceof Error?l:new Error(String(l))),u()}})}var Nxe,sj=R(()=>{"use strict";Nxe=require("child_process")});var wj,ISe,PSe,vee,ST,OSe=R(()=>{"use strict";wj=_e(require("fs")),ISe=_e(require("path")),PSe=_e(require("os")),vee=ISe.join(PSe.homedir(),".visa-mcp"),ST=class{static ensureConfigDir(){wj.existsSync(vee)||wj.mkdirSync(vee,{recursive:!0,mode:448})}static getConfigDir(){return vee}}});function P6t(){nc.existsSync(Eee)||nc.mkdirSync(Eee,{recursive:!0,mode:448})}function O6t(){if(!wee){if(P6t(),nc.existsSync(TT)&&nc.statSync(TT).size>I6t){let t=TT+".1";nc.existsSync(t)&&nc.unlinkSync(t),nc.renameSync(TT,t)}wee=nc.createWriteStream(TT,{flags:"a"})}return wee}function C6t(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function Ej(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}
|
|
5
5
|
`;C6t(e)&&process.stderr.write(i),O6t().write(i)}var nc,Aee,CSe,Eee,TT,I6t,wee,Me,ud=R(()=>{"use strict";nc=_e(require("fs")),Aee=_e(require("path")),CSe=_e(require("os")),Eee=Aee.join(CSe.homedir(),".visa-mcp"),TT=Aee.join(Eee,"mcp-server.log"),I6t=5*1024*1024,wee=null;Me={debug:(...e)=>Ej("DEBUG",...e),info:(...e)=>Ej("INFO",...e),warn:(...e)=>Ej("WARN",...e),error:(...e)=>Ej("ERROR",...e)}});function RSe(e){let t=kSe.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Aj(){return NSe.join(ST.getConfigDir(),R6t)}function BSe(e){if((0,See.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function N6t(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 BSe(i)}function B6t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,See.isIP)(t);return r===4?BSe(t):r===6?t==="::1"||N6t(t):!1}function xee(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:"&&B6t(r.hostname)))throw new Error(`${t} ${k6t}`)}function xj(){let e=Aj();if(!ry.existsSync(e))return{};try{let t=ry.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Me.warn("settings:corrupt",{path:RSe(e),reason:"not_object"}),{}):r}catch(t){return Me.warn("settings:corrupt",{path:RSe(e),error:t?.message||String(t)}),{}}}function jSe(e){ST.ensureConfigDir();let t=Aj(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
|
|
6
|
-
`;ry.writeFileSync(r,n,{mode:384}),ry.renameSync(r,t)}function Tee(e){let t=xj()[e];return typeof t=="string"?t:void 0}function Iee(e){let t=xj()[e];return typeof t=="boolean"?t:void 0}function Sj(e,t){let r=T_[e];if(!r)throw new Cl(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=xj();return i[e]=n,jSe(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Aj()}}function Tj(e){let t=T_[e];if(!t)throw new Cl(e);let r=xj(),n=e in r;return n&&(delete r[e],jSe(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Aj()}}function M6t(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function q6t(){try{let e=rj();return M6t(e.version)}catch{return!1}}function D6t(e){return e.envVar!==void 0&&e.envVar!==""?(xee(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(xee(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?U6t:j6t}function du(){return D6t({envVar:process.env.VISA_AUTH_URL,settingValue:Tee("auth.serverUrl"),isPrerelease:q6t()})}function USe(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Iee("ui.suppressBrowser")??!1}var ry,See,kSe,NSe,R6t,k6t,T_,Cl,j6t,U6t,I_=R(()=>{"use strict";ry=_e(require("fs")),See=require("node:net"),kSe=_e(require("os")),NSe=_e(require("path"));OSe();ud();R6t="settings.json",k6t="must use https unless it points at localhost/loopback for local development";T_={"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");xee(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Cl=class extends Error{constructor(t){let r=Object.keys(T_).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};j6t="https://auth.visacli.sh",U6t="https://auth-visa-code-preview.up.railway.app"});function Pee(e=V6t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function Oee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function P_(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return Oee(t||K6t)}function MSe(e){return`${Oee(e)}${W6t}`}async function qSe(e,t=fetch){let r=`${Oee(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 V6t,K6t,W6t,Cee=R(()=>{"use strict";V6t="4.1.0-rc.41",K6t="https://app.visacli.sh",W6t="/agent/enroll"});function Avt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function UTe(e,t,r=""){let n=Avt(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 dTe(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 xvt(e,t){UTe(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 $ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Uee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Svt(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 Pvt(e,t=!1){return t?{h:Number(e&Nj),l:Number(e>>lTe&Nj)}:{h:Number(e>>lTe&Nj)|0,l:Number(e&Nj)|0}}function Ovt(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}=Pvt(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function E0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function zvt(){return _vt.randomSecretKey()}function B_(e){return mvt(e)}function qTe(){let e=zvt();return{secretKey:e,publicKey:B_(e)}}function DTe(e){if(e.length!==hTe)throw new Error(`Ed25519 seed must be ${hTe} bytes, got ${e.length}`);return{secretKey:e,publicKey:B_(e)}}function Vj(e,t){return gvt(t,e)}function Hvt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Fvt(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 Fj(e){return Hvt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function zTe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Fvt(r)}function $vt(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function j_(e){let t=B_(e);return{kty:"OKP",crv:"Ed25519",x:Fj(t),d:Fj(e)}}function sy(e){return{kty:"OKP",crv:"Ed25519",x:Fj(e)}}function $4(e){if($vt(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return zTe(e.d)}function gTe(e,t){return e<t?-1:e>t?1:0}function qee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ti(e){if(typeof e!="string"||!Wvt.test(e))return!1;try{let t=zTe(e);return t.byteLength===32&&Fj(t)===e}catch{return!1}}function Dee(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 e5t(e,t){if(typeof t!="string"||!Kvt.test(t))throw new Error(`${e} must be a UUID`)}function PT(e,t){return e5t(e,t),t.toLowerCase()}function bTe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=Jvt.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 Uj(e,t,r=!1){if(typeof t!="string"||!Gvt.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)>Zvt)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function t5t(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>Yvt)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function _Te(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(HTe.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>Xvt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function r5t(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(HTe.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 Lee(e,t){return typeof e=="string"&&t.includes(e)}function n5t(e){if(!qee(e))throw new Error("agent authority grant must be an object");if(Dee("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==z4)throw new Error("grant.v must be 2");let t=PT("grantId",e.grantId),r=PT("agentId",e.agentId),n=t5t("version",e.version),i=PT("budgetEpochId",e.budgetEpochId);if(!Lee(e.budgetEpochMode,Vvt))throw new Error("budgetEpochMode must be new or continue");if(!Lee(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!==Mee)throw new Error(`valuationPolicy must be '${Mee}'`);let o=Uj("totalMicros",e.totalMicros),s=Uj("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(!qee(l))throw new Error("grant scope must be an object");if(Dee("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!Lee(l.scope,Dj))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:Uj("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:Uj("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=r5t("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>yTe)throw new Error(`payeeConstraints must contain between 1 and ${yTe} entries`);if(c=e.payeeConstraints.map(p=>{if(!qee(p))throw new Error("payee constraint must be an object");if(Dee("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:_Te("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=_Te("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!Qvt.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=bTe("effectiveAt",e.effectiveAt),d=bTe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&PT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:z4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:Mee,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>gTe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>gTe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:PT("supersedesGrantId",e.supersedesGrantId)}:{}}}function KTe(e,t){return e<t?-1:e>t?1:0}function of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A0(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 p5t(e){if(typeof e!="string")throw new Error("displayName must be a string");if(Kj.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>s5t)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function f5t(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(Kj.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!o5t.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function Mj(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Kj.test(t)||VTe.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 m5t(e){if(!of(e))throw new Error("runtime context v2 must be an object");A0("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=Mj("runtime",e.runtime,c5t),r=Mj("contextLabel",e.contextLabel,u5t),n=e.cliVersion===void 0?void 0:Mj("cliVersion",e.cliVersion,d5t),i=e.platform===void 0?void 0:Mj("platform",e.platform,l5t);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function Qee(e){if(typeof e!="string"||!$Te.test(e))throw new Error("pairingId must be a server-generated pairing id")}function WTe(e){if(e!==Pr)throw new Error("protocolVersion must be 2")}function OT(e,t){if(typeof t!="string"||!a5t.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function sf(e,t){if(!ti(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function ETe(e,t){if(typeof t!="string"||t.length===0||t.length>wTe||Kj.test(t)||VTe.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>wTe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function GTe(){return RT.default.randomBytes(32).toString("base64url")}function JTe(e){if(!ti(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return BT(e)}function h5t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function y5t(e){let t=h5t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function YTe(){return RT.default.randomBytes(32).toString("base64url")}function kT(e){if(!ti(e))throw new Error("claim token must be 32 unpadded base64url bytes");return BT(`visa-agent-pairing-claim-token:v1:${e}`)}function Wj(e,t){kT(t);let r=RT.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<i5t;i+=1)n+=Xee[r[i]&FTe];return y5t(n)}function ZTe(e){if(!of(e))throw new Error("pairing terms v2 must be an object");if(A0("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==z4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!$Te.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!vTe.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(!ti(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!vTe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=p5t(e.displayName),i=e.dotVisaAddress===void 0?void 0:f5t(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:z4})}if(!of(e.authority))throw new Error("pairing authority must be an object or null");if(A0("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>Dj.length)throw new Error(`pairing authority scopes must contain between 1 and ${Dj.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!of(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(A0("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!Dj.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!ti(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=n5t({v:z4,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:z4})}function g5t(e){return BT(`visa-agent-pairing-terms:v2:${ZTe(e)}`)}function ete(e){if(!of(e))throw new Error("pairing claim v2 must be an object");A0("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),WTe(e.protocolVersion),Qee(e.pairingId),OT("agentId",e.agentId),sf("serverNonce",e.serverNonce),sf("claimTokenHash",e.claimTokenHash),sf("identityKeyJkt",e.identityKeyJkt);let t=m5t(e.runtime);return e7e("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 XTe(e){if(!of(e))throw new Error("pairing activation v2 must be an object");return A0("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),WTe(e.protocolVersion),Qee(e.pairingId),OT("agentId",e.agentId),OT("ownerPublicId",e.ownerPublicId),sf("claimTokenHash",e.claimTokenHash),sf("identityKeyJkt",e.identityKeyJkt),sf("ceremonyHash",e.ceremonyHash),sf("deliveryArtifactHash",e.deliveryArtifactHash),e7e("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 NT(e){if(!of(e))throw new Error("pairing delivery artifact v2 must be an object");if(A0("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==Pr)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(Qee(e.pairingId),OT("agentId",e.agentId),OT("ownerPublicId",e.ownerPublicId),sf("ceremonyHash",e.ceremonyHash),!of(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(A0("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),sf("identityKey.jkt",e.identityKey.jkt),!of(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(A0("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");sf("identityKey.publicJwk.x",t.x);let r=BT(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(!of(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=ZTe(e.terms);if(g5t(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=ETe("issuer",e.issuer),o=ETe("activationAudience",e.activationAudience);return Vee({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:Pr})}function QTe(e){return BT(`visa-agent-pairing-delivery-artifact:v2:${NT(e)}`)}function BT(e){return RT.default.createHash("sha256").update(e,"utf8").digest("base64url")}function e7e(e,t){return`${e}
|
|
6
|
+
`;ry.writeFileSync(r,n,{mode:384}),ry.renameSync(r,t)}function Tee(e){let t=xj()[e];return typeof t=="string"?t:void 0}function Iee(e){let t=xj()[e];return typeof t=="boolean"?t:void 0}function Sj(e,t){let r=T_[e];if(!r)throw new Cl(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=xj();return i[e]=n,jSe(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Aj()}}function Tj(e){let t=T_[e];if(!t)throw new Cl(e);let r=xj(),n=e in r;return n&&(delete r[e],jSe(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Aj()}}function M6t(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function q6t(){try{let e=rj();return M6t(e.version)}catch{return!1}}function D6t(e){return e.envVar!==void 0&&e.envVar!==""?(xee(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(xee(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?U6t:j6t}function du(){return D6t({envVar:process.env.VISA_AUTH_URL,settingValue:Tee("auth.serverUrl"),isPrerelease:q6t()})}function USe(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Iee("ui.suppressBrowser")??!1}var ry,See,kSe,NSe,R6t,k6t,T_,Cl,j6t,U6t,I_=R(()=>{"use strict";ry=_e(require("fs")),See=require("node:net"),kSe=_e(require("os")),NSe=_e(require("path"));OSe();ud();R6t="settings.json",k6t="must use https unless it points at localhost/loopback for local development";T_={"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");xee(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Cl=class extends Error{constructor(t){let r=Object.keys(T_).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};j6t="https://auth.visacli.sh",U6t="https://auth-visa-code-preview.up.railway.app"});function Pee(e=V6t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function Oee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function P_(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return Oee(t||K6t)}function MSe(e){return`${Oee(e)}${W6t}`}async function qSe(e,t=fetch){let r=`${Oee(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 V6t,K6t,W6t,Cee=R(()=>{"use strict";V6t="4.1.0-rc.42",K6t="https://app.visacli.sh",W6t="/agent/enroll"});function Avt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function UTe(e,t,r=""){let n=Avt(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 dTe(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 xvt(e,t){UTe(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 $ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Uee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Svt(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 Pvt(e,t=!1){return t?{h:Number(e&Nj),l:Number(e>>lTe&Nj)}:{h:Number(e>>lTe&Nj)|0,l:Number(e&Nj)|0}}function Ovt(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}=Pvt(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function E0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function zvt(){return _vt.randomSecretKey()}function B_(e){return mvt(e)}function qTe(){let e=zvt();return{secretKey:e,publicKey:B_(e)}}function DTe(e){if(e.length!==hTe)throw new Error(`Ed25519 seed must be ${hTe} bytes, got ${e.length}`);return{secretKey:e,publicKey:B_(e)}}function Vj(e,t){return gvt(t,e)}function Hvt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Fvt(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 Fj(e){return Hvt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function zTe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Fvt(r)}function $vt(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function j_(e){let t=B_(e);return{kty:"OKP",crv:"Ed25519",x:Fj(t),d:Fj(e)}}function sy(e){return{kty:"OKP",crv:"Ed25519",x:Fj(e)}}function $4(e){if($vt(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return zTe(e.d)}function gTe(e,t){return e<t?-1:e>t?1:0}function qee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ti(e){if(typeof e!="string"||!Wvt.test(e))return!1;try{let t=zTe(e);return t.byteLength===32&&Fj(t)===e}catch{return!1}}function Dee(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 e5t(e,t){if(typeof t!="string"||!Kvt.test(t))throw new Error(`${e} must be a UUID`)}function PT(e,t){return e5t(e,t),t.toLowerCase()}function bTe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=Jvt.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 Uj(e,t,r=!1){if(typeof t!="string"||!Gvt.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)>Zvt)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function t5t(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>Yvt)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function _Te(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(HTe.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>Xvt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function r5t(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(HTe.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 Lee(e,t){return typeof e=="string"&&t.includes(e)}function n5t(e){if(!qee(e))throw new Error("agent authority grant must be an object");if(Dee("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==z4)throw new Error("grant.v must be 2");let t=PT("grantId",e.grantId),r=PT("agentId",e.agentId),n=t5t("version",e.version),i=PT("budgetEpochId",e.budgetEpochId);if(!Lee(e.budgetEpochMode,Vvt))throw new Error("budgetEpochMode must be new or continue");if(!Lee(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!==Mee)throw new Error(`valuationPolicy must be '${Mee}'`);let o=Uj("totalMicros",e.totalMicros),s=Uj("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(!qee(l))throw new Error("grant scope must be an object");if(Dee("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!Lee(l.scope,Dj))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:Uj("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:Uj("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=r5t("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>yTe)throw new Error(`payeeConstraints must contain between 1 and ${yTe} entries`);if(c=e.payeeConstraints.map(p=>{if(!qee(p))throw new Error("payee constraint must be an object");if(Dee("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:_Te("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=_Te("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!Qvt.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=bTe("effectiveAt",e.effectiveAt),d=bTe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&PT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:z4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:Mee,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>gTe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>gTe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:PT("supersedesGrantId",e.supersedesGrantId)}:{}}}function KTe(e,t){return e<t?-1:e>t?1:0}function of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A0(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 p5t(e){if(typeof e!="string")throw new Error("displayName must be a string");if(Kj.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>s5t)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function f5t(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(Kj.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!o5t.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function Mj(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Kj.test(t)||VTe.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 m5t(e){if(!of(e))throw new Error("runtime context v2 must be an object");A0("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=Mj("runtime",e.runtime,c5t),r=Mj("contextLabel",e.contextLabel,u5t),n=e.cliVersion===void 0?void 0:Mj("cliVersion",e.cliVersion,d5t),i=e.platform===void 0?void 0:Mj("platform",e.platform,l5t);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function Qee(e){if(typeof e!="string"||!$Te.test(e))throw new Error("pairingId must be a server-generated pairing id")}function WTe(e){if(e!==Pr)throw new Error("protocolVersion must be 2")}function OT(e,t){if(typeof t!="string"||!a5t.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function sf(e,t){if(!ti(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function ETe(e,t){if(typeof t!="string"||t.length===0||t.length>wTe||Kj.test(t)||VTe.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>wTe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function GTe(){return RT.default.randomBytes(32).toString("base64url")}function JTe(e){if(!ti(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return BT(e)}function h5t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function y5t(e){let t=h5t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function YTe(){return RT.default.randomBytes(32).toString("base64url")}function kT(e){if(!ti(e))throw new Error("claim token must be 32 unpadded base64url bytes");return BT(`visa-agent-pairing-claim-token:v1:${e}`)}function Wj(e,t){kT(t);let r=RT.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<i5t;i+=1)n+=Xee[r[i]&FTe];return y5t(n)}function ZTe(e){if(!of(e))throw new Error("pairing terms v2 must be an object");if(A0("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==z4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!$Te.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!vTe.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(!ti(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!vTe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=p5t(e.displayName),i=e.dotVisaAddress===void 0?void 0:f5t(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:z4})}if(!of(e.authority))throw new Error("pairing authority must be an object or null");if(A0("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>Dj.length)throw new Error(`pairing authority scopes must contain between 1 and ${Dj.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!of(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(A0("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!Dj.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!ti(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=n5t({v:z4,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:z4})}function g5t(e){return BT(`visa-agent-pairing-terms:v2:${ZTe(e)}`)}function ete(e){if(!of(e))throw new Error("pairing claim v2 must be an object");A0("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),WTe(e.protocolVersion),Qee(e.pairingId),OT("agentId",e.agentId),sf("serverNonce",e.serverNonce),sf("claimTokenHash",e.claimTokenHash),sf("identityKeyJkt",e.identityKeyJkt);let t=m5t(e.runtime);return e7e("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 XTe(e){if(!of(e))throw new Error("pairing activation v2 must be an object");return A0("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),WTe(e.protocolVersion),Qee(e.pairingId),OT("agentId",e.agentId),OT("ownerPublicId",e.ownerPublicId),sf("claimTokenHash",e.claimTokenHash),sf("identityKeyJkt",e.identityKeyJkt),sf("ceremonyHash",e.ceremonyHash),sf("deliveryArtifactHash",e.deliveryArtifactHash),e7e("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 NT(e){if(!of(e))throw new Error("pairing delivery artifact v2 must be an object");if(A0("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==Pr)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(Qee(e.pairingId),OT("agentId",e.agentId),OT("ownerPublicId",e.ownerPublicId),sf("ceremonyHash",e.ceremonyHash),!of(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(A0("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),sf("identityKey.jkt",e.identityKey.jkt),!of(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(A0("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");sf("identityKey.publicJwk.x",t.x);let r=BT(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(!of(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=ZTe(e.terms);if(g5t(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=ETe("issuer",e.issuer),o=ETe("activationAudience",e.activationAudience);return Vee({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:Pr})}function QTe(e){return BT(`visa-agent-pairing-delivery-artifact:v2:${NT(e)}`)}function BT(e){return RT.default.createHash("sha256").update(e,"utf8").digest("base64url")}function e7e(e,t){return`${e}
|
|
7
7
|
${Object.entries(t).sort(([r],[n])=>KTe(r,n)).map(([r,n])=>`${r}=${n}`).join(`
|
|
8
8
|
`)}`}function Vee(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Vee).join(",")}]`;let t=e;return`{${Object.keys(t).sort(KTe).map(r=>`${JSON.stringify(r)}:${Vee(t[r])}`).join(",")}}`}var RT,ATe,Lj,qj,nTe,iTe,Nee,Bee,ivt,H4,ovt,ss,svt,avt,cvt,af,$j,Kee,xTe,Wee,w0,oTe,Gee,STe,uvt,F4,TTe,zj,C_,En,sTe,Ve,ITe,PTe,OTe,CTe,jee,zee,CT,N_,k_,RTe,kTe,nf,dvt,aTe,lvt,Hee,pvt,Jee,NTe,fvt,Yee,mvt,hvt,yvt,gvt,Zee,BTe,bvt,_vt,Hj,vvt,jTe,Fee,wvt,cTe,uTe,Evt,Tvt,Ivt,zs,Nj,lTe,pTe,fTe,D4,L4,Bj,jj,Cvt,Rvt,kvt,Nvt,Bvt,jvt,MTe,Uvt,Mvt,iy,oy,qvt,Dvt,Lvt,mTe,hTe,aBr,LTe,cBr,uBr,dBr,lBr,z4,Vvt,Mee,Dj,Kvt,Wvt,Gvt,Jvt,HTe,Yvt,Zvt,yTe,Xvt,Qvt,pBr,Pr,Xee,i5t,FTe,$Te,vTe,Kj,o5t,s5t,a5t,c5t,u5t,d5t,l5t,wTe,VTe,V4=R(()=>{"use strict";RT=_e(require("node:crypto"),1),ATe=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Lj,n:qj,Gx:nTe,Gy:iTe,a:Nee,d:Bee,h:ivt}=ATe,H4=32,ovt=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ss=(e="")=>{let t=new Error(e);throw ovt(t,ss),t},svt=e=>typeof e=="bigint",avt=e=>typeof e=="string",cvt=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,af=(e,t,r="")=>{let n=cvt(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},$j=e=>new Uint8Array(e),Kee=e=>Uint8Array.from(e),xTe=(e,t)=>e.toString(16).padStart(t,"0"),Wee=e=>Array.from(af(e)).map(t=>xTe(t,2)).join(""),w0={_0:48,_9:57,A:65,F:70,a:97,f:102},oTe=e=>{if(e>=w0._0&&e<=w0._9)return e-w0._0;if(e>=w0.A&&e<=w0.F)return e-(w0.A-10);if(e>=w0.a&&e<=w0.f)return e-(w0.a-10)},Gee=e=>{let t="hex invalid";if(!avt(e))return ss(t);let r=e.length,n=r/2;if(r%2)return ss(t);let i=$j(n);for(let o=0,s=0;o<n;o++,s+=2){let a=oTe(e.charCodeAt(s)),c=oTe(e.charCodeAt(s+1));if(a===void 0||c===void 0)return ss(t);i[o]=a*16+c}return i},STe=()=>globalThis?.crypto,uvt=()=>STe()?.subtle??ss("crypto.subtle must be defined, consider polyfill"),F4=(...e)=>{let t=0;for(let i of e)t+=af(i).length;let r=$j(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},TTe=(e=H4)=>STe().getRandomValues($j(e)),zj=BigInt,C_=(e,t,r,n="bad number: out of range")=>{if(!svt(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},En=(e,t=Lj)=>{let r=e%t;return r>=0n?r:t+r},sTe=(1n<<255n)-1n,Ve=e=>{e<0n&&ss("negative coordinate");let t=(e>>255n)*19n+(e&sTe);return t=(t>>255n)*19n+(t&sTe),t%Lj},ITe=e=>En(e,qj),PTe=(e,t)=>{(e===0n||t<=0n)&&ss("no inverse n="+e+" mod="+t);let r=En(e,t),n=t,i=0n,o=1n,s=1n,a=0n;for(;r!==0n;){let c=n/r,u=n%r,d=i-s*c,l=o-a*c;n=r,r=u,i=s,o=a,s=d,a=l}return n===1n?En(i,t):ss("no inverse")},OTe=e=>{let t=BTe[e];return typeof t!="function"&&ss("hashes."+e+" not set"),t},CTe=e=>af(e,64,"digest"),jee=e=>e instanceof CT?e:ss("Point expected"),zee=2n**256n,CT=class R_{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=zee;this.X=C_(t,0n,o),this.Y=C_(r,0n,o),this.Z=C_(n,1n,o),this.T=C_(i,0n,o),Object.freeze(this)}static CURVE(){return ATe}static fromAffine(t){return new R_(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=Bee,i=Kee(af(t,H4)),o=t[31];i[31]=o&-129;let s=kTe(i);C_(s,0n,r?zee:Lj);let c=Ve(s*s),u=En(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=lvt(u,d);l||ss("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&ss("bad point: x==0, isLastByteOdd"),m!==f&&(p=En(-p)),new R_(p,s,1n,Ve(p*s))}static fromHex(t,r){return R_.fromBytes(Gee(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Nee,r=Bee,n=this;if(n.is0())return ss("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ve(i*i),u=Ve(o*o),d=Ve(s*s),l=Ve(d*d),p=Ve(c*t),f=Ve(d*(p+u)),m=En(l+Ve(r*Ve(c*u)));if(f!==m)return ss("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?ss("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=jee(t),c=Ve(r*a),u=Ve(o*i),d=Ve(n*a),l=Ve(s*i);return c===u&&d===l}is0(){return this.equals(k_)}negate(){return new R_(En(-this.X),this.Y,this.Z,En(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=Nee,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=En(t+r),d=En(Ve(u*u)-o-s),l=En(c+s),p=En(l-a),f=En(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),v=Ve(p*l);return new R_(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=jee(t),d=Nee,l=Bee,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=En(Ve(En(r+n)*En(s+a))-p-f),v=En(h-m),E=En(h+m),_=En(f-Ve(d*p)),w=Ve(y*v),A=Ve(E*_),x=Ve(y*_),S=Ve(v*E);return new R_(w,A,S,x)}subtract(t){return this.add(jee(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(C_(t,1n,qj),!r&&this.is0()))return k_;if(t===1n)return this;if(this.equals(N_))return Evt(t).p;let n=k_,i=N_;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?n=n.add(o):r&&(i=i.add(o));return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(k_))return{x:0n,y:1n};let i=PTe(n,Lj);Ve(n*i)!==1n&&ss("invalid inverse");let o=Ve(t*i),s=Ve(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=RTe(r);return n[31]|=t&1n?128:0,n}toHex(){return Wee(this.toBytes())}clearCofactor(){return this.multiply(zj(ivt),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(qj/2n,!1).double();return qj%2n&&(t=t.add(this)),t.is0()}},N_=new CT(nTe,iTe,1n,En(nTe*iTe)),k_=new CT(0n,1n,1n,0n);CT.BASE=N_;CT.ZERO=k_;RTe=e=>Gee(xTe(C_(e,0n,zee),64)).reverse(),kTe=e=>zj("0x"+Wee(Kee(af(e)).reverse())),nf=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},dvt=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(nf(r,2n)*r),i=Ve(nf(n,1n)*e),o=Ve(nf(i,5n)*i),s=Ve(nf(o,10n)*o),a=Ve(nf(s,20n)*s),c=Ve(nf(a,40n)*a),u=Ve(nf(c,80n)*c),d=Ve(nf(u,80n)*c),l=Ve(nf(d,10n)*o);return{pow_p_5_8:Ve(nf(l,2n)*e),b2:r}},aTe=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,lvt=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=dvt(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*aTe),u=s===e,d=s===En(-e),l=s===En(-e*aTe);return u&&(o=a),(d||l)&&(o=c),(En(o)&1n)===1n&&(o=En(-o)),{isValid:u||d,value:o}},Hee=e=>ITe(kTe(e)),pvt=(...e)=>Promise.resolve(OTe("sha512Async")(F4(...e))).then(CTe),Jee=(...e)=>CTe(OTe("sha512")(F4(...e))),NTe=e=>{let t=Kee(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=Hee(r),o=N_.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},fvt=e=>pvt(af(e,H4)).then(NTe),Yee=e=>NTe(Jee(af(e,H4))),mvt=e=>Yee(e).pointBytes,hvt=e=>e.finish(Jee(e.hashable)),yvt=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=Hee(t),s=N_.multiply(o).toBytes();return{hashable:F4(s,n,r),finish:u=>{let d=ITe(o+Hee(u)*i);return af(F4(s,RTe(d)),64)}}},gvt=(e,t)=>{let r=af(e),n=Yee(t),i=Jee(n.prefix,r);return hvt(yvt(n,i,r))},Zee=Object.freeze({bytesToHex:Wee,hexToBytes:Gee,concatBytes:F4,mod:En,invert:PTe,randomBytes:TTe}),BTe={sha512Async:async e=>{let t=uvt(),r=F4(e);return $j(await t.digest("SHA-512",r.buffer))},sha512:void 0},bvt=e=>(e=e===void 0?TTe(H4):e,af(e,H4)),_vt=Object.freeze({getExtendedPublicKeyAsync:fvt,getExtendedPublicKey:Yee,randomSecretKey:bvt}),Hj=8,vvt=256,jTe=Math.ceil(vvt/Hj)+1,Fee=2**(Hj-1),wvt=()=>{let e=[],t=N_,r=t;for(let n=0;n<jTe;n++){r=t,e.push(r);for(let i=1;i<Fee;i++)r=r.add(t),e.push(r);t=r.double()}return e},cTe=void 0,uTe=(e,t)=>{let r=t.negate();return e?r:t},Evt=e=>{let t=cTe||(cTe=wvt()),r=k_,n=N_,i=2**Hj,o=i,s=zj(i-1),a=zj(Hj);for(let c=0;c<jTe;c++){let u=Number(e&s);e>>=a,u>Fee&&(u-=o,e+=1n);let d=c*Fee,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(uTe(f,t[l])):r=r.add(uTe(m,t[p]))}return e!==0n&&ss("invalid wnaf"),{p:r,f:n}};Tvt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),Ivt=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Uee(this.buffer)}update(e){dTe(this),UTe(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let s=Math.min(n-this.pos,i-o);if(s===n){let a=Uee(e);for(;n<=i-o;o+=n)this.process(a,o);continue}r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dTe(this),xvt(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,$ee(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let d=o;d<n;d++)t[d]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let s=Uee(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},zs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Nj=BigInt(2**32-1),lTe=BigInt(32);pTe=(e,t,r)=>e>>>r,fTe=(e,t,r)=>e<<32-r|t>>>r,D4=(e,t,r)=>e>>>r|t<<32-r,L4=(e,t,r)=>e<<32-r|t>>>r,Bj=(e,t,r)=>e<<64-r|t>>>r-32,jj=(e,t,r)=>e>>>r-32|t<<64-r;Cvt=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Rvt=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,kvt=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Nvt=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Bvt=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),jvt=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,MTe=Ovt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Uvt=MTe[0],Mvt=MTe[1],iy=new Uint32Array(80),oy=new Uint32Array(80),qvt=class extends Ivt{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:l,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h]}set(e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let E=0;E<16;E++,t+=4)iy[E]=e.getUint32(t),oy[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=iy[E-15]|0,w=oy[E-15]|0,A=D4(_,w,1)^D4(_,w,8)^pTe(_,w,7),x=L4(_,w,1)^L4(_,w,8)^fTe(_,w,7),S=iy[E-2]|0,I=oy[E-2]|0,T=D4(S,I,19)^Bj(S,I,61)^pTe(S,I,6),O=L4(S,I,19)^jj(S,I,61)^fTe(S,I,6),j=kvt(x,O,oy[E-7],oy[E-16]),M=Nvt(j,A,T,iy[E-7],iy[E-16]);iy[E]=M|0,oy[E]=j|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:p,Fl:f,Gh:m,Gl:h,Hh:y,Hl:v}=this;for(let E=0;E<80;E++){let _=D4(d,l,14)^D4(d,l,18)^Bj(d,l,41),w=L4(d,l,14)^L4(d,l,18)^jj(d,l,41),A=d&p^~d&m,x=l&f^~l&h,S=Bvt(v,w,x,Mvt[E],oy[E]),I=jvt(S,y,_,A,Uvt[E],iy[E]),T=S|0,O=D4(r,n,28)^Bj(r,n,34)^Bj(r,n,39),j=L4(r,n,28)^jj(r,n,34)^jj(r,n,39),M=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=E0(c|0,u|0,I|0,T|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let k=Cvt(T,j,U);r=Rvt(k,I,O,M),n=k|0}({h:r,l:n}=E0(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=E0(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=E0(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=E0(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=E0(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=E0(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=E0(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=E0(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){$ee(iy,oy)}destroy(){this.destroyed=!0,$ee(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Dvt=class extends qvt{Ah=zs[0]|0;Al=zs[1]|0;Bh=zs[2]|0;Bl=zs[3]|0;Ch=zs[4]|0;Cl=zs[5]|0;Dh=zs[6]|0;Dl=zs[7]|0;Eh=zs[8]|0;El=zs[9]|0;Fh=zs[10]|0;Fl=zs[11]|0;Gh=zs[12]|0;Gl=zs[13]|0;Hh=zs[14]|0;Hl=zs[15]|0;constructor(){super(64)}},Lvt=Svt(()=>new Dvt,Tvt(3)),mTe=BTe;mTe.sha512||(mTe.sha512=e=>Lvt(e));hTe=32;aBr=Zee.bytesToHex,LTe=Zee.hexToBytes,cBr=Zee.concatBytes;uBr=new TextEncoder;dBr=LTe("302e020100300506032b657004220420"),lBr=LTe("302a300506032b6570032100"),z4=2,Vvt=["new","continue"],Mee="nominal_usd_usdc_parity",Dj=["card:vic","wallet:x402"],Kvt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Wvt=/^[A-Za-z0-9_-]{43}$/,Gvt=/^(?:0|[1-9][0-9]*)$/,Jvt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,HTe=/[\u0000-\u001f\u007f]/,Yvt=2147483647,Zvt=9223372036854775807n,yTe=100,Xvt=512,Qvt=/^0x[0-9a-f]{40}$/,pBr=new TextEncoder;Pr=2,Xee="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",i5t=8,FTe=Xee.length-1;if((Xee.length&FTe)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");$Te=/^ap_[A-Za-z0-9_-]{24}$/,vTe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Kj=/[\p{Cc}\p{Cf}]/u,o5t=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,s5t=255,a5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,c5t=100,u5t=200,d5t=64,l5t=100,wTe=2048,VTe=/[\u0080-\u009f\u2028\u2029]/;});var n7e={};Pi(n7e,{VisaBindingRequiredError:()=>cf,jkt:()=>ay,readSeed:()=>jT});function ay(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return t7e.createHash("sha256").update(t,"utf8").digest("base64url")}function jT(e){let t=new Uint8Array(r7e.readFileSync(e));if(t.length!==32)throw new Error("Subway identity key must be a 32-byte Ed25519 seed");return t}var t7e,r7e,cf,Gj=R(()=>{"use strict";t7e=_e(require("node:crypto")),r7e=_e(require("node:fs"));cf=class extends Error{reason;constructor(t="No active .visa mesh admission binding is stored. Identity pairing does not grant a .visa name or TAP/channel binding; configure that capability separately when its approval flow is available."){super(t),this.name="VisaBindingRequiredError",this.reason="missing_or_incompatible"}}});function tte(e,t){switch(e){case"name_not_found":return new i7e(t);case"delivery_failed":return new o7e(t);case"timeout":return new UT(t);case"not_registered":return new s7e;case"register_failed":return new Jj(t);case"invalid_message":return new a7e(t);case"rate_limited":return new c7e(t);default:return new uf(e,t)}}var uf,i7e,o7e,UT,s7e,Hs,a7e,Jj,c7e,rte=R(()=>{"use strict";uf=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},i7e=class extends uf{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},o7e=class extends uf{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},UT=class extends uf{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},s7e=class extends uf{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Hs=class extends uf{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},a7e=class extends uf{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},Jj=class extends uf{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},c7e=class extends uf{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var u7e,nte=R(()=>{"use strict";u7e=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})});function L_(e){return e.includes(".")?e:`${e}.relay`}function ite(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function b5t(){if(typeof WebSocket<"u")return WebSocket;try{let e=u7e("ws");return e.default??e}catch{return}}function _5t(e,t,r){return Math.min(Math.max(e,t),r)}function $5t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function G7e(e,t,r=""){let n=$5t(e),i=e?.length;if(!n||t!==void 0){let s=r&&`"${r}" `,a="",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 g7e(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 V5t(e,t){G7e(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 MT(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function cte(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function lf(e,t){return e<<32-t|e>>>t}function J7e(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 K5t(e,t,r){return e&t^~e&r}function W5t(e,t,r){return e&t^e&r^t&r}function G5t(e,t=!1){return t?{h:Number(e&Yj),l:Number(e>>b7e&Yj)}:{h:Number(e>>b7e&Yj)|0,l:Number(e&Yj)|0}}function J5t(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}=G5t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function S0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function lwt(e){return M5t(e)}function pwt(e,t){return L5t(t,e)}function mwt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function gwt(e){let t=fwt(uwt(e.payload)),r=`${e.messageId}
|
|
9
9
|
${e.senderPeerId}
|
|
@@ -175,7 +175,7 @@ Full request-key fingerprint to compare exactly: ${n.identityKeyJkt}
|
|
|
175
175
|
`:`Agent not found: ${r}
|
|
176
176
|
`),process.exitCode=1;return}if(G_(n)){let o=r8(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: ${t8(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(`
|
|
177
177
|
`));return}let i=n.binding_jwt?r8(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: ${t8(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
|
|
178
|
-
`))})}var ff,nPe,gy,Gte,C0,Jte,Yte,H4t,n8=R(()=>{"use strict";ff=_e(require("fs")),nPe=_e(require("os")),gy=_e(require("path")),Gte=require("node:readline/promises");V4();sj();Cee();mU();_U();IIe();VIe();GIe();RU();C0=gy.join(nPe.homedir(),".visa-cli","agents");Jte=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Yte=32768,H4t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var ure={};Pi(ure,{SUBWAY_PROTOCOL:()=>vPe,registerDirect:()=>h8t,resolveDirect:()=>y8t});function ore(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 ld(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 sre(e,t){return e<<3|t}function r7(e,t,r){e.push(sre(t,2)),ore(e,r.length);for(let n of r)e.push(n)}function n8t(e,t){let r=[];return r7(r,1,ire.encode(e)),t&&t.length>0&&r7(r,2,ire.encode(t)),Uint8Array.from(r)}function i8t(e,t,r){let n=[];return r!==0n&&(n.push(sre(1,0)),ore(n,r)),r7(n,2,n8t(e,t)),Uint8Array.from(n)}function o8t(e){let t=[];return r7(t,1,ire.encode(e)),Uint8Array.from(t)}function s8t(e,t){let r=[];return t!==0n&&(r.push(sre(1,0)),ore(r,t)),r7(r,3,o8t(e)),Uint8Array.from(r)}function a8t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ld(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.error=bPe.decode(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function c8t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=ld(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]=ld(e,t),u=c,d=u+Number(a);r.error=bPe.decode(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function are(e,t,r){if(r===0)return ld(e,t)[1];if(r===2){let[n,i]=ld(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 _Pe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ld(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.registerNameResponse=a8t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.resolveNameResponse=c8t(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function u8t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function cre(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function d8t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=cre(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:_Pe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function l8t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=cre(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:_Pe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function nre(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 m8t(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>dPe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+cre(nre(t).subarray(0,4)),n>dPe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return nre(t).subarray(0,n)}return nre(t)}async function wPe(e){return(0,lPe.createLibp2p)({...e?{privateKey:await(0,hPe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,pPe.tcp)()],connectionEncrypters:[(0,fPe.noise)()],streamMuxers:[(0,mPe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function EPe(e,t,r){let n=await e.dialProtocol((0,yPe.multiaddr)(t),vPe,{signal:AbortSignal.timeout(p8t)});n.send(u8t(r));let i;return Promise.race([m8t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),f8t)})]).finally(()=>clearTimeout(i))}async function h8t(e){let t=await wPe(e.seed);try{let r=await EPe(t,e.relayMultiaddr,i8t(e.name,e.binding,e.requestId??1n)),n=d8t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function y8t(e){let t=await wPe(e.seed);try{let r=await EPe(t,e.relayMultiaddr,s8t(e.name,e.requestId??1n)),n=l8t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,gPe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var lPe,pPe,fPe,mPe,hPe,yPe,gPe,ire,bPe,vPe,p8t,f8t,dPe,dre=R(()=>{"use strict";nte();lPe=require("libp2p"),pPe=require("@libp2p/tcp"),fPe=require("@chainsafe/libp2p-noise"),mPe=require("@chainsafe/libp2p-yamux"),hPe=require("@libp2p/crypto/keys"),yPe=require("@multiformats/multiaddr"),gPe=require("uint8arrays/to-string"),ire=new TextEncoder,bPe=new TextDecoder;vPe="/subway/p2p/1.0.0",p8t=15e3,f8t=15e3,dPe=1<<20});var o7={};Pi(o7,{DEFAULT_VISA_RELAY_MULTIADDR:()=>APe,MESH:()=>Oi,RELAY_URL:()=>n7,connectOrThrow:()=>o8,ensureMailbox:()=>Are,isSubwayEnabled:()=>hre,listRegistered:()=>Ere,loadBindingFor:()=>_re,loadRegistry:()=>Y_,makeClient:()=>i8,meshName:()=>mf,pairedVisaBinding:()=>TPe,pairedVisaBindingForIdentity:()=>IPe,readInbox:()=>_8t,registerName:()=>i7,resolveActingName:()=>jU,resolveMeshName:()=>vre,seedSubwayKeyFromExactIdentity:()=>SPe,seedSubwayKeyFromTapAgent:()=>xPe,sendMessage:()=>wre,sendVia:()=>v8t,subwayKeyPath:()=>bre,visaRelayMultiaddr:()=>mre});function mre(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??APe}function mf(e){return e.includes(".")?e:`${e}.${Oi}`}function hre(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 gre(){lu.mkdirSync(yre,{recursive:!0,mode:448})}function g8t(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function bre(e){return BU.join(yre,`${g8t(e)}.key`)}function Y_(){if(!lu.existsSync(fre))return{};try{return JSON.parse(lu.readFileSync(fre,"utf8"))}catch{return{}}}function lre(e){gre(),lu.writeFileSync(fre,JSON.stringify(e,null,2),{mode:384})}function pre(){try{return NU.userInfo().username}catch{return"local"}}function xPe(e){if(lu.existsSync(e))return null;let t=PU();if(!t)return null;try{let r=$4(t.private_key_jwk);return gre(),lu.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function SPe(e,t){let r=$4(t.identityPrivateJwk);if(ay(sy(B_(r)))!==t.identityKeyJkt)throw new cf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(lu.existsSync(e)){if(ay(sy(B_(jT(e))))!==t.identityKeyJkt)throw new cf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return gre(),lu.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function i8(e,t={}){return new yIe({name:mf(e),url:n7,keyPath:bre(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function _re(e){if(Oi!=="visa")return;let t=Y_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function o8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${n7})`)),t))])}function jU(e){if(e)return e;let t=Object.keys(Y_());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 TPe(e,t=Date.now()){let r=PU();if(!r?.binding_jwt)return null;let n=r8(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 IPe(e,t,r=Date.now()){for(let n of OU()){if(n.agent_jkt!==t)continue;let i=r8(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 i7(e,t={}){let r=bre(e),n=mf(e),i,o;if(t.exactIdentity){if(o=Oi==="visa"?IPe(n,t.exactIdentity.identityKeyJkt):null,Oi==="visa"&&!o)throw new cf;i=SPe(r,t.exactIdentity)}else i=xPe(r),o=Oi==="visa"?TPe(n):null;let s,a={};if(o){if(!lu.existsSync(r))throw new cf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(ay(sy(B_(jT(r))))!==o.identityKeyJkt)throw new cf("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(Oi==="visa")throw new cf;let c=Oi==="visa"?mre():process.env.SUBWAY_RELAY_MULTIADDR;if(Oi==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(dre(),ure)),l=await d({relayMultiaddr:c,seed:jT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=Y_();return p[e]={relayName:n,mesh:Oi,peerId:l.peerId,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(p),{relayName:n,mesh:Oi,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Oi==="visa"&&!process.env.SUBWAY_RELAY){let d=Y_();return d[e]={relayName:n,mesh:Oi,peerId:null,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(d),{relayName:n,mesh:Oi,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=i8(e,{autoReconnect:!1,binding:s});try{await o8(u);let d=Y_();return d[e]={relayName:n,mesh:Oi,peerId:u.peerId,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(d),{relayName:n,mesh:Oi,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function vre(e){let t=mf(e),r=Oi==="visa"?mre():process.env.SUBWAY_RELAY_MULTIADDR;if(Oi==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(dre(),ure)),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 wre(e,t,r){let n=i8(e,{autoReconnect:!1,binding:_re(e)});try{await o8(n);let i=mf(t);return await n.sendSigned(i,"chat",r),{to:i,as:mf(e)}}finally{n.disconnect()}}function Ere(){let e=Y_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Are(e){let t=kU.get(e);if(t)return{relayName:mf(e),peerId:t.client.peerId};let r=i8(e,{autoReconnect:!0,binding:_re(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>b8t&&n.shift()}),kU.set(e,{client:r,buffer:n}),await o8(r),{relayName:mf(e),peerId:r.peerId}}async function _8t(e,t=20,r=!1){await Are(e);let n=kU.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function v8t(e,t,r){await Are(e);let n=kU.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=mf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:mf(e)}}var lu,NU,BU,Oi,APe,n7,yre,fre,kU,b8t,Z_=R(()=>{"use strict";Tte();V4();lu=_e(require("fs")),NU=_e(require("os")),BU=_e(require("path"));Gj();n8();Oi=process.env.SUBWAY_MESH??"relay",APe="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";n7=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";yre=BU.join(NU.homedir(),".visa-cli","subway"),fre=BU.join(yre,"registry.json");kU=new Map,b8t=200});var HPe={};Pi(HPe,{PAIRING_DIR:()=>yf,cancelPairing:()=>rre,claimPairing:()=>J_,getPairingStatus:()=>CU,initiatePairing:()=>t7,latestPendingHumanPairing:()=>TU,latestPendingRuntimePairing:()=>HU,pairingFilePath:()=>zU,pollAndActivatePairing:()=>IU,readPendingPairing:()=>dd,registerOnVisaMeshIfEnabled:()=>tre,removePendingPairing:()=>e7,tryActivatePairing:()=>kre,verifyPairing:()=>by,writePendingPairing:()=>Rre});async function tre(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await i7(e),!0}catch(t){return Me.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Tre(e){return typeof e=="string"&&A8t.test(e)}function s8(e){return typeof e=="string"&&x8t.test(e)}function s7(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function BPe(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 MU(e){if(typeof e!="string"||e.length===0||e.length>NPe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&BPe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function LU(e){if(e.length===0||e.length>NPe)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:"&&BPe(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 Ire(e){if(typeof e!="string")return!1;try{return LU(e)===e}catch{return!1}}function I8t(e){return ic(e)&&hf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&ti(e.x)}function P8t(e){return ic(e)&&hf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&ti(e.x)&&ti(e.d)}function O8t(e,t){try{let r=j_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function UU(e,t){if(typeof e!="string"||S8t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function jPe(e){if(!ic(e)||!hf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=UU(e.runtime,100),r=UU(e.contextLabel,200),n=e.cliVersion===void 0?void 0:UU(e.cliVersion,64),i=e.platform===void 0?void 0:UU(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 C8t(e){if(!ic(e))return!1;let t=jPe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function UPe(e){return ic(e)?hf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===Pr&&s8(e.pairingId)&&Tre(e.agentId)&&ti(e.verifier)&&Ire(e.authUrl)&&MU(e.skillUrl)&&s7(e.expiresAt)&&s7(e.createdAt):!1}function MPe(e){return!ic(e)||!hf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==Pr||!s8(e.pairingId)||!Tre(e.agentId)||!Ire(e.authUrl)||!ti(e.claimToken)||!ti(e.serverNonce)||!ti(e.identityKeyJkt)||!I8t(e.identityPublicJwk)||!P8t(e.identityPrivateJwk)||!C8t(e.runtime)||!s7(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&ay(e.identityPublicJwk)===e.identityKeyJkt&&O8t(e.identityPrivateJwk,e.identityPublicJwk)}function R8t(e){return ic(e)&&hf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===Pr&&ti(e.verifier)&&Ire(e.authUrl)&&s7(e.createdAt)}function a7(e,t,r){if(!ic(e)||e.protocolVersion!==Pr||!s8(e.pairingId)||!Tre(e.agentId)||typeof e.state!="string"||!T8t.has(e.state)||!s7(e.expiresAt)||e.skillUrl!==void 0&&!MU(e.skillUrl)||e.authorizationUrl!==void 0&&!MU(e.authorizationUrl)||e.serverNonce!==void 0&&!ti(e.serverNonce)||e.authApiUrl!==void 0&&!MU(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 zU(e,t,r=yf){if(!s8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return DU.join(r,`${e}.${t}.json`)}function qPe(e){kl.mkdirSync(e,{recursive:!0,mode:448});let t=kl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");kl.chmodSync(e,448),Rl(e)}function Pre(e){return DU.join(e,w8t)}function Ore(e){let t=HT(Pre(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(!R8t(r))throw new Error("local pairing initiation state is invalid");return r}function k8t(e,t){qPe(t),K_(Pre(t),JSON.stringify(e,null,2))}function PPe(e,t){let r=Ore(t);if(!r)return;let n=dd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&Cre(t)}function Cre(e){Ore(e)&&Rl(e)&&kl.rmSync(Pre(e),{force:!0})}function Rre(e,t=yf){if(!(e.role==="human"?UPe(e):MPe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");qPe(t);let n=zU(e.pairingId,e.role,t);K_(n,JSON.stringify(e,null,2))}function e7(e,t,r=yf){dd(e,t,r)&&Rl(r)&&kl.rmSync(zU(e,t,r),{force:!0})}function xre(e,t=yf){e7(e,"human",t),e7(e,"runtime",t),Cre(t)}function dd(e,t,r=yf){if(!s8(e))return null;let n=HT(zU(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(!UPe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!MPe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function DPe(e,t){return Rl(t)?kl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!s8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return dd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function TU(e=yf){return DPe("human",e)}function HU(e=yf){return DPe("runtime",e)}function qU(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Sre(e,t){return t?t.aborted?Promise.reject(qU(t)):new Promise((r,n)=>{let i=()=>n(qU(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 X_(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 ${OPe}ms`)),OPe);s.unref?.();try{if(i.signal.aborted)throw qU(i.signal);let a=await Sre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":kPe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Sre(a.json(),i.signal)}catch{if(i.signal.aborted)throw qU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=ic(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 t7(e={}){let t=LU(e.authUrl??du()),r=e.pairingDir??yf,n=Ore(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<E8t;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:Pr,verifier:GTe(),authUrl:t,createdAt:new Date().toISOString()};o||k8t(s,r);let a=s.verifier,{body:c}=await X_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,cliChallenge:JTe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(a7(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:Pr,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:c.skillUrl,expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return Rre(u,r),e.retainInitiationDraft||Cre(r),u}async function by(e){let{pairing:t}=e,{body:r}=await X_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return a7(r,t.pairingId,t.agentId),r}async function CU(e){let t=LU(e.authUrl??du()),{body:r}=await X_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return a7(r,e.pairingId,e.expectedAgentId),r}function LPe(e,t){return Buffer.from(Vj(e,Buffer.from(t,"utf8"))).toString("base64url")}function N8t(e){let t=LPe(Buffer.from(e.identityPrivateJwk.d,"base64url"),ete({protocolVersion:Pr,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:kT(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:Pr,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function CPe(e,t,r){let{body:n}=await X_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N8t(e))},t,{signal:r}),i=n;if(!ic(i)||!hf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==Pr||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!==Wj(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function J_(e){let t=LU(e.authUrl??du()),r=e.fetchImpl??fetch,n=e.pairingDir??yf,i=jPe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:kPe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=dd(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 PPe(o.pairingId,n),CPe(o,r,e.signal)}let s=await CU({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!ti(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=qTe(),c=j_(a.secretKey),u=sy(a.publicKey),d=ay(u),l=i,p=YTe();ete({protocolVersion:Pr,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:kT(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:Pr,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 Rre(f,n),PPe(f.pairingId,n),CPe(f,r,e.signal)}async function zPe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await X_(`${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(a7(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw xre(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!ic(r)||!hf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==Pr||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!ic(r.artifact)||!ti(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=NT(r.artifact),o=JSON.parse(i),s=QTe(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=LPe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),XTe({protocolVersion:Pr,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:kT(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await X_(`${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:Pr,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!ic(d)||!hf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==Pr||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||!ic(d.credentials)||!hf(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:Pr,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()};return(e.writeAgentRecord??Qte)(l,e.agentDir),xre(e.pending.pairingId,e.pairingDir),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function kre(e){return zPe(e)}async function IU(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 zPe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Sre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function rre(e){let{pairing:t}=e,{body:r}=await X_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return a7(r,t.pairingId,t.agentId),r.state==="cancelled"&&xre(t.pairingId,e.pairingDir),r}var kl,RPe,DU,kPe,yf,w8t,E8t,A8t,x8t,S8t,T8t,NPe,OPe,RU=R(()=>{"use strict";kl=_e(require("node:fs")),RPe=_e(require("node:os")),DU=_e(require("node:path"));V4();I_();ud();Gj();Z_();mU();n8();kPe="4.1.0-rc.41",yf=DU.join(RPe.homedir(),".visa-cli","pairings"),w8t=".initiation.v2.json",E8t=15*6e4,A8t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,x8t=/^ap_[A-Za-z0-9_-]{24}$/,S8t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,T8t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),NPe=2048;OPe=3e4});function FPe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function B8t(e,t){return t?t.aborted?Promise.reject(FPe(t)):new Promise((r,n)=>{let i=()=>n(FPe(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 j8t(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function $Pe(e,t){if(t!==void 0&&j8t(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function U8t(e){return{status:"activated",protocolVersion:Pr,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function YT(e={}){let t=HU(e.pairingDir);if(t){$Pe(t.authUrl,e.authUrl);let s=dd(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 J_({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 by({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:Pr,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await t7({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await J_({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 by({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:Pr,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function M8t(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function ZT(e={}){let t=HU(e.pairingDir);if(!t)return{status:"no_pending"};let r=dd(t.pairingId,"human",e.pairingDir);try{$Pe(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 kre({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return U8t(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 J_({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 by({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await B8t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:Pr,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:M8t(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function PIe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await ei.saveSessionToken(e),!0}catch{return!1}}var _U=R(()=>{"use strict";V4();Qh();RU()});var Mre={};Pi(Mre,{CardDrawRefusedError:()=>Q_,cardDrawIntentHash:()=>tOe,decimalUsdToCents:()=>Ure,fetchCardDrawVerdict:()=>Z8t,loadCardMandateCapability:()=>Y8t,registerCardMandate:()=>X8t});function V8t(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,jre.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function K8t(e){let{secretKey:t,publicKey:r}=DTe(e),n=j_(t),i=sy(r);return{privateJwk:n,publicJwk:i,jkt:V8t(i)}}async function QPe(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:$8t},o=`${ZPe(i)}.${ZPe(n)}`,s=$4(e.privateJwk),a=Vj(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function eOe(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(!W8t.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:G8t,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,jre.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function J8t(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 Ure(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 tOe(e,t){let r=Ure(e.amount);return r===null?null:eOe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Y8t(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(n8(),ie(uPe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=J8t(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=K8t($4(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 VU(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${XPe}ms`)),XPe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function rOe(e){return e.replace(/\/+$/,"")}async function Z8t(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=rOe(e.authBaseUrl),i=tOe(e.draw,e.drawId);if(i===null)throw new Q_(400,["invalid_amount"]);let o=await VU(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Q_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Q_(502,["challenge_malformed"]);let a=await QPe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await VU(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 Q_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function X8t(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=rOe(e.authBaseUrl),i=Ure(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=eOe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await VU(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 QPe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await VU(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 jre,$8t,ZPe,W8t,G8t,Q_,XPe,qre=R(()=>{"use strict";jre=require("node:crypto");V4();$8t="visa-agent-pop+jwt",ZPe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");W8t=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),G8t=1;Q_=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},XPe=3e4});var PCe=g(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});Ml.formatCents=ICe;Ml.formatUsd=x9t;Ml.formatMicros=pM;Ml.formatMicrosWire=S9t;Ml.formatTxAmount=T9t;Ml.formatDate=I9t;Ml.formatRelativeTime=P9t;Ml.formatTime=O9t;Ml.formatAge=C9t;var TCe=1e6,A9t=100;function ICe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/A9t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function x9t(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 pM(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/TCe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function S9t(e,t,r={}){return e&&/^-?\d+$/.test(e)?pM(e,r):t!=null&&Number.isFinite(t)?ICe(t,r):r.fallback??"\u2014"}function T9t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return pM(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?pM(n*TCe,t):t.fallback??"\u2014"}function I9t(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 P9t(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?I8(n,i,a,"minute"):c<24?I8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?I8(n,i,u,"day"):d<4?I8(n,i,d,"week"):l<12?I8(n,i,l,"month"):I8(n,i,p,"year")}function I8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function O9t(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 C9t(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 P8=g(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.formatAge=Xt.formatTime=Xt.formatRelativeTime=Xt.formatDate=Xt.formatTxAmount=Xt.formatMicrosWire=Xt.formatMicros=Xt.formatUsd=Xt.formatCents=void 0;Xt.micros=R9t;Xt.fromCents=k9t;Xt.fromUsdc=N9t;Xt.fromUsd=B9t;Xt.toCents=j9t;Xt.toCentsForAcquirer=U9t;Xt.toUsdc=M9t;Xt.toWire=q9t;Xt.fromWire=D9t;Xt.toDisplay=L9t;Xt.toUsdRounded2dp=z9t;Xt.add=H9t;Xt.sub=F9t;Xt.clampNonNegative=$9t;Xt.isNonNegative=V9t;Xt.max=K9t;Xt.min=W9t;var M0=10000n,OCe=1000000n;function R9t(e){return e}function k9t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*M0}function N9t(e){return e}function B9t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function j9t(e){if(e>=0n)return Number(e/M0);let t=e/M0,r=e%M0;return Number(r===0n?t:t-1n)}function U9t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/M0)}function M9t(e){return e}function q9t(e){return e.toString()}function D9t(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 L9t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/OCe,a=o%OCe,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 z9t(e){let t=e<0n,r=t?-e:e,n=r/M0,o=r%M0*2n,s;o<M0?s=n:o>M0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function H9t(e,t){return e+t}function F9t(e,t){return e-t}function $9t(e){return e<0n?0n:e}function V9t(e){return e>=0n}function K9t(e,t){return e>t?e:t}function W9t(e,t){return e<t?e:t}var q0=PCe();Object.defineProperty(Xt,"formatCents",{enumerable:!0,get:function(){return q0.formatCents}});Object.defineProperty(Xt,"formatUsd",{enumerable:!0,get:function(){return q0.formatUsd}});Object.defineProperty(Xt,"formatMicros",{enumerable:!0,get:function(){return q0.formatMicros}});Object.defineProperty(Xt,"formatMicrosWire",{enumerable:!0,get:function(){return q0.formatMicrosWire}});Object.defineProperty(Xt,"formatTxAmount",{enumerable:!0,get:function(){return q0.formatTxAmount}});Object.defineProperty(Xt,"formatDate",{enumerable:!0,get:function(){return q0.formatDate}});Object.defineProperty(Xt,"formatRelativeTime",{enumerable:!0,get:function(){return q0.formatRelativeTime}});Object.defineProperty(Xt,"formatTime",{enumerable:!0,get:function(){return q0.formatTime}});Object.defineProperty(Xt,"formatAge",{enumerable:!0,get:function(){return q0.formatAge}})});var dne=g(ac=>{"use strict";var G9t=ac&&ac.__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]})),J9t=ac&&ac.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),RCe=ac&&ac.__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"&&G9t(r,t,n[i]);return J9t(r,t),r}})();Object.defineProperty(ac,"__esModule",{value:!0});ac.pruneResponsesDir=une;ac.isTextualContentType=fM;ac.isValidUtf8=NCe;ac.spillFilename=BCe;ac.describePaidBody=ane;ac.capturePaidResponse=txt;var wf=RCe(require("fs")),I7=RCe(require("path")),Y9t=require("node:crypto"),kCe=16*1024,sne=2*1024,Z9t=64*1024*1024,X9t=3e4,cne=256*1024*1024;function une(e,t=cne,r){try{let n=r?I7.basename(r):null,i=wf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=wf.statSync(I7.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{wf.rmSync(I7.join(e,s.name),{force:!0})}catch{}}catch{}}var Q9t=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function fM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||Q9t.has(t)}function NCe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var ext={"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 BCe(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=ext[o]??(fM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jCe(e,t,r){let n=BCe(t,r,new Date),i=I7.extname(n),o=n.slice(0,n.length-i.length);return I7.join(e,`${o}-${(0,Y9t.randomBytes)(8).toString("hex")}${i}`)}function UCe(e){wf.mkdirSync(e,{recursive:!0,mode:448})}function CCe(e,t){let r=0;for(;r<t.length;){let n=wf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function ane(e,t,r,n,i){let o=r?fM(r):NCe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=kCe)return{...s,body:n.toString("utf-8")};UCe(i);let a=jCe(i,e,r);return wf.writeFileSync(a,n,{flag:"wx",mode:384}),une(i,cne,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,sne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function txt(e,t,r,n={}){let i=n.maxBytes??Z9t,o=n.timeoutMs??X9t;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 ane(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&&(wf.closeSync(p),p=null)},E=()=>{if(v(),m)try{wf.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,j)=>{x=setTimeout(()=>j(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<sne){let O=T.subarray(0,Math.min(T.length,sne-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=kCe)continue;UCe(r),f=jCe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=wf.openSync(m,"wx",384);for(let O of u)CCe(p,O);u.length=0,d=0}else CCe(p,T)}if(p===null){let A=Buffer.concat(u,d);return ane(e,t.status,t.headers.get("content-type"),A,r)}v(),wf.renameSync(m,f),m=null,une(r,cne,f);let _=t.headers.get("content-type"),w=_?fM(_):!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 Sy=g(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.TURNKEY_API_BASE_URL_ENV=fo.CIRCLE_TESTNET_FAUCET_URL=fo.NETWORK_ENV=fo.NETWORKS=void 0;fo.resolveNetwork=rxt;fo.turnkeyApiBaseUrl=ixt;fo.explorerTxUrl=oxt;fo.explorerAddressUrl=sxt;fo.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}};fo.NETWORK_ENV="VISA_V4_NETWORK";fo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var MCe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function rxt(e=process.env){let t=(e[fo.NETWORK_ENV]??"").trim();if(t==="")return fo.NETWORKS["base-mainnet"];let r=MCe[t.toLowerCase()];if(!r)throw new Error(`unknown ${fo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(MCe).join(", "));return fo.NETWORKS[r]}fo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var nxt="https://api.turnkey.com";function ixt(e=process.env){let t=(e[fo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?nxt:t}function oxt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function sxt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qCe=g(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.version=void 0;mM.version="1.2.3"});var g6=g(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.BaseError=void 0;var axt=qCe(),lne=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@${axt.version}`].join(`
|
|
178
|
+
`))})}var ff,nPe,gy,Gte,C0,Jte,Yte,H4t,n8=R(()=>{"use strict";ff=_e(require("fs")),nPe=_e(require("os")),gy=_e(require("path")),Gte=require("node:readline/promises");V4();sj();Cee();mU();_U();IIe();VIe();GIe();RU();C0=gy.join(nPe.homedir(),".visa-cli","agents");Jte=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Yte=32768,H4t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var ure={};Pi(ure,{SUBWAY_PROTOCOL:()=>vPe,registerDirect:()=>h8t,resolveDirect:()=>y8t});function ore(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 ld(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 sre(e,t){return e<<3|t}function r7(e,t,r){e.push(sre(t,2)),ore(e,r.length);for(let n of r)e.push(n)}function n8t(e,t){let r=[];return r7(r,1,ire.encode(e)),t&&t.length>0&&r7(r,2,ire.encode(t)),Uint8Array.from(r)}function i8t(e,t,r){let n=[];return r!==0n&&(n.push(sre(1,0)),ore(n,r)),r7(n,2,n8t(e,t)),Uint8Array.from(n)}function o8t(e){let t=[];return r7(t,1,ire.encode(e)),Uint8Array.from(t)}function s8t(e,t){let r=[];return t!==0n&&(r.push(sre(1,0)),ore(r,t)),r7(r,3,o8t(e)),Uint8Array.from(r)}function a8t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ld(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.error=bPe.decode(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function c8t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=ld(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]=ld(e,t),u=c,d=u+Number(a);r.error=bPe.decode(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function are(e,t,r){if(r===0)return ld(e,t)[1];if(r===2){let[n,i]=ld(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 _Pe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=ld(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ld(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.registerNameResponse=a8t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=ld(e,t),u=c,d=u+Number(a);r.resolveNameResponse=c8t(e.subarray(u,d)),t=d}else t=are(e,t,s)}return r}function u8t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function cre(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function d8t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=cre(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:_Pe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function l8t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=cre(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:_Pe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function nre(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 m8t(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>dPe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+cre(nre(t).subarray(0,4)),n>dPe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return nre(t).subarray(0,n)}return nre(t)}async function wPe(e){return(0,lPe.createLibp2p)({...e?{privateKey:await(0,hPe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,pPe.tcp)()],connectionEncrypters:[(0,fPe.noise)()],streamMuxers:[(0,mPe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function EPe(e,t,r){let n=await e.dialProtocol((0,yPe.multiaddr)(t),vPe,{signal:AbortSignal.timeout(p8t)});n.send(u8t(r));let i;return Promise.race([m8t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),f8t)})]).finally(()=>clearTimeout(i))}async function h8t(e){let t=await wPe(e.seed);try{let r=await EPe(t,e.relayMultiaddr,i8t(e.name,e.binding,e.requestId??1n)),n=d8t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function y8t(e){let t=await wPe(e.seed);try{let r=await EPe(t,e.relayMultiaddr,s8t(e.name,e.requestId??1n)),n=l8t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,gPe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var lPe,pPe,fPe,mPe,hPe,yPe,gPe,ire,bPe,vPe,p8t,f8t,dPe,dre=R(()=>{"use strict";nte();lPe=require("libp2p"),pPe=require("@libp2p/tcp"),fPe=require("@chainsafe/libp2p-noise"),mPe=require("@chainsafe/libp2p-yamux"),hPe=require("@libp2p/crypto/keys"),yPe=require("@multiformats/multiaddr"),gPe=require("uint8arrays/to-string"),ire=new TextEncoder,bPe=new TextDecoder;vPe="/subway/p2p/1.0.0",p8t=15e3,f8t=15e3,dPe=1<<20});var o7={};Pi(o7,{DEFAULT_VISA_RELAY_MULTIADDR:()=>APe,MESH:()=>Oi,RELAY_URL:()=>n7,connectOrThrow:()=>o8,ensureMailbox:()=>Are,isSubwayEnabled:()=>hre,listRegistered:()=>Ere,loadBindingFor:()=>_re,loadRegistry:()=>Y_,makeClient:()=>i8,meshName:()=>mf,pairedVisaBinding:()=>TPe,pairedVisaBindingForIdentity:()=>IPe,readInbox:()=>_8t,registerName:()=>i7,resolveActingName:()=>jU,resolveMeshName:()=>vre,seedSubwayKeyFromExactIdentity:()=>SPe,seedSubwayKeyFromTapAgent:()=>xPe,sendMessage:()=>wre,sendVia:()=>v8t,subwayKeyPath:()=>bre,visaRelayMultiaddr:()=>mre});function mre(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??APe}function mf(e){return e.includes(".")?e:`${e}.${Oi}`}function hre(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 gre(){lu.mkdirSync(yre,{recursive:!0,mode:448})}function g8t(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function bre(e){return BU.join(yre,`${g8t(e)}.key`)}function Y_(){if(!lu.existsSync(fre))return{};try{return JSON.parse(lu.readFileSync(fre,"utf8"))}catch{return{}}}function lre(e){gre(),lu.writeFileSync(fre,JSON.stringify(e,null,2),{mode:384})}function pre(){try{return NU.userInfo().username}catch{return"local"}}function xPe(e){if(lu.existsSync(e))return null;let t=PU();if(!t)return null;try{let r=$4(t.private_key_jwk);return gre(),lu.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function SPe(e,t){let r=$4(t.identityPrivateJwk);if(ay(sy(B_(r)))!==t.identityKeyJkt)throw new cf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(lu.existsSync(e)){if(ay(sy(B_(jT(e))))!==t.identityKeyJkt)throw new cf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return gre(),lu.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function i8(e,t={}){return new yIe({name:mf(e),url:n7,keyPath:bre(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function _re(e){if(Oi!=="visa")return;let t=Y_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function o8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${n7})`)),t))])}function jU(e){if(e)return e;let t=Object.keys(Y_());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 TPe(e,t=Date.now()){let r=PU();if(!r?.binding_jwt)return null;let n=r8(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 IPe(e,t,r=Date.now()){for(let n of OU()){if(n.agent_jkt!==t)continue;let i=r8(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 i7(e,t={}){let r=bre(e),n=mf(e),i,o;if(t.exactIdentity){if(o=Oi==="visa"?IPe(n,t.exactIdentity.identityKeyJkt):null,Oi==="visa"&&!o)throw new cf;i=SPe(r,t.exactIdentity)}else i=xPe(r),o=Oi==="visa"?TPe(n):null;let s,a={};if(o){if(!lu.existsSync(r))throw new cf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(ay(sy(B_(jT(r))))!==o.identityKeyJkt)throw new cf("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(Oi==="visa")throw new cf;let c=Oi==="visa"?mre():process.env.SUBWAY_RELAY_MULTIADDR;if(Oi==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(dre(),ure)),l=await d({relayMultiaddr:c,seed:jT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=Y_();return p[e]={relayName:n,mesh:Oi,peerId:l.peerId,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(p),{relayName:n,mesh:Oi,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Oi==="visa"&&!process.env.SUBWAY_RELAY){let d=Y_();return d[e]={relayName:n,mesh:Oi,peerId:null,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(d),{relayName:n,mesh:Oi,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=i8(e,{autoReconnect:!1,binding:s});try{await o8(u);let d=Y_();return d[e]={relayName:n,mesh:Oi,peerId:u.peerId,owner:pre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},lre(d),{relayName:n,mesh:Oi,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function vre(e){let t=mf(e),r=Oi==="visa"?mre():process.env.SUBWAY_RELAY_MULTIADDR;if(Oi==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(dre(),ure)),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 wre(e,t,r){let n=i8(e,{autoReconnect:!1,binding:_re(e)});try{await o8(n);let i=mf(t);return await n.sendSigned(i,"chat",r),{to:i,as:mf(e)}}finally{n.disconnect()}}function Ere(){let e=Y_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Are(e){let t=kU.get(e);if(t)return{relayName:mf(e),peerId:t.client.peerId};let r=i8(e,{autoReconnect:!0,binding:_re(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>b8t&&n.shift()}),kU.set(e,{client:r,buffer:n}),await o8(r),{relayName:mf(e),peerId:r.peerId}}async function _8t(e,t=20,r=!1){await Are(e);let n=kU.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function v8t(e,t,r){await Are(e);let n=kU.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=mf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:mf(e)}}var lu,NU,BU,Oi,APe,n7,yre,fre,kU,b8t,Z_=R(()=>{"use strict";Tte();V4();lu=_e(require("fs")),NU=_e(require("os")),BU=_e(require("path"));Gj();n8();Oi=process.env.SUBWAY_MESH??"relay",APe="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";n7=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";yre=BU.join(NU.homedir(),".visa-cli","subway"),fre=BU.join(yre,"registry.json");kU=new Map,b8t=200});var HPe={};Pi(HPe,{PAIRING_DIR:()=>yf,cancelPairing:()=>rre,claimPairing:()=>J_,getPairingStatus:()=>CU,initiatePairing:()=>t7,latestPendingHumanPairing:()=>TU,latestPendingRuntimePairing:()=>HU,pairingFilePath:()=>zU,pollAndActivatePairing:()=>IU,readPendingPairing:()=>dd,registerOnVisaMeshIfEnabled:()=>tre,removePendingPairing:()=>e7,tryActivatePairing:()=>kre,verifyPairing:()=>by,writePendingPairing:()=>Rre});async function tre(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await i7(e),!0}catch(t){return Me.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Tre(e){return typeof e=="string"&&A8t.test(e)}function s8(e){return typeof e=="string"&&x8t.test(e)}function s7(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function BPe(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 MU(e){if(typeof e!="string"||e.length===0||e.length>NPe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&BPe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function LU(e){if(e.length===0||e.length>NPe)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:"&&BPe(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 Ire(e){if(typeof e!="string")return!1;try{return LU(e)===e}catch{return!1}}function I8t(e){return ic(e)&&hf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&ti(e.x)}function P8t(e){return ic(e)&&hf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&ti(e.x)&&ti(e.d)}function O8t(e,t){try{let r=j_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function UU(e,t){if(typeof e!="string"||S8t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function jPe(e){if(!ic(e)||!hf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=UU(e.runtime,100),r=UU(e.contextLabel,200),n=e.cliVersion===void 0?void 0:UU(e.cliVersion,64),i=e.platform===void 0?void 0:UU(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 C8t(e){if(!ic(e))return!1;let t=jPe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function UPe(e){return ic(e)?hf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===Pr&&s8(e.pairingId)&&Tre(e.agentId)&&ti(e.verifier)&&Ire(e.authUrl)&&MU(e.skillUrl)&&s7(e.expiresAt)&&s7(e.createdAt):!1}function MPe(e){return!ic(e)||!hf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==Pr||!s8(e.pairingId)||!Tre(e.agentId)||!Ire(e.authUrl)||!ti(e.claimToken)||!ti(e.serverNonce)||!ti(e.identityKeyJkt)||!I8t(e.identityPublicJwk)||!P8t(e.identityPrivateJwk)||!C8t(e.runtime)||!s7(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&ay(e.identityPublicJwk)===e.identityKeyJkt&&O8t(e.identityPrivateJwk,e.identityPublicJwk)}function R8t(e){return ic(e)&&hf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===Pr&&ti(e.verifier)&&Ire(e.authUrl)&&s7(e.createdAt)}function a7(e,t,r){if(!ic(e)||e.protocolVersion!==Pr||!s8(e.pairingId)||!Tre(e.agentId)||typeof e.state!="string"||!T8t.has(e.state)||!s7(e.expiresAt)||e.skillUrl!==void 0&&!MU(e.skillUrl)||e.authorizationUrl!==void 0&&!MU(e.authorizationUrl)||e.serverNonce!==void 0&&!ti(e.serverNonce)||e.authApiUrl!==void 0&&!MU(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 zU(e,t,r=yf){if(!s8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return DU.join(r,`${e}.${t}.json`)}function qPe(e){kl.mkdirSync(e,{recursive:!0,mode:448});let t=kl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");kl.chmodSync(e,448),Rl(e)}function Pre(e){return DU.join(e,w8t)}function Ore(e){let t=HT(Pre(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(!R8t(r))throw new Error("local pairing initiation state is invalid");return r}function k8t(e,t){qPe(t),K_(Pre(t),JSON.stringify(e,null,2))}function PPe(e,t){let r=Ore(t);if(!r)return;let n=dd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&Cre(t)}function Cre(e){Ore(e)&&Rl(e)&&kl.rmSync(Pre(e),{force:!0})}function Rre(e,t=yf){if(!(e.role==="human"?UPe(e):MPe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");qPe(t);let n=zU(e.pairingId,e.role,t);K_(n,JSON.stringify(e,null,2))}function e7(e,t,r=yf){dd(e,t,r)&&Rl(r)&&kl.rmSync(zU(e,t,r),{force:!0})}function xre(e,t=yf){e7(e,"human",t),e7(e,"runtime",t),Cre(t)}function dd(e,t,r=yf){if(!s8(e))return null;let n=HT(zU(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(!UPe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!MPe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function DPe(e,t){return Rl(t)?kl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!s8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return dd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function TU(e=yf){return DPe("human",e)}function HU(e=yf){return DPe("runtime",e)}function qU(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Sre(e,t){return t?t.aborted?Promise.reject(qU(t)):new Promise((r,n)=>{let i=()=>n(qU(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 X_(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 ${OPe}ms`)),OPe);s.unref?.();try{if(i.signal.aborted)throw qU(i.signal);let a=await Sre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":kPe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Sre(a.json(),i.signal)}catch{if(i.signal.aborted)throw qU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=ic(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 t7(e={}){let t=LU(e.authUrl??du()),r=e.pairingDir??yf,n=Ore(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<E8t;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:Pr,verifier:GTe(),authUrl:t,createdAt:new Date().toISOString()};o||k8t(s,r);let a=s.verifier,{body:c}=await X_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,cliChallenge:JTe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(a7(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:Pr,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:c.skillUrl,expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return Rre(u,r),e.retainInitiationDraft||Cre(r),u}async function by(e){let{pairing:t}=e,{body:r}=await X_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return a7(r,t.pairingId,t.agentId),r}async function CU(e){let t=LU(e.authUrl??du()),{body:r}=await X_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return a7(r,e.pairingId,e.expectedAgentId),r}function LPe(e,t){return Buffer.from(Vj(e,Buffer.from(t,"utf8"))).toString("base64url")}function N8t(e){let t=LPe(Buffer.from(e.identityPrivateJwk.d,"base64url"),ete({protocolVersion:Pr,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:kT(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:Pr,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function CPe(e,t,r){let{body:n}=await X_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N8t(e))},t,{signal:r}),i=n;if(!ic(i)||!hf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==Pr||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!==Wj(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function J_(e){let t=LU(e.authUrl??du()),r=e.fetchImpl??fetch,n=e.pairingDir??yf,i=jPe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:kPe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=dd(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 PPe(o.pairingId,n),CPe(o,r,e.signal)}let s=await CU({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!ti(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=qTe(),c=j_(a.secretKey),u=sy(a.publicKey),d=ay(u),l=i,p=YTe();ete({protocolVersion:Pr,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:kT(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:Pr,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 Rre(f,n),PPe(f.pairingId,n),CPe(f,r,e.signal)}async function zPe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await X_(`${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(a7(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw xre(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!ic(r)||!hf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==Pr||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!ic(r.artifact)||!ti(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=NT(r.artifact),o=JSON.parse(i),s=QTe(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=LPe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),XTe({protocolVersion:Pr,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:kT(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await X_(`${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:Pr,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!ic(d)||!hf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==Pr||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||!ic(d.credentials)||!hf(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:Pr,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()};return(e.writeAgentRecord??Qte)(l,e.agentDir),xre(e.pending.pairingId,e.pairingDir),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function kre(e){return zPe(e)}async function IU(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 zPe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Sre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function rre(e){let{pairing:t}=e,{body:r}=await X_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Pr,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return a7(r,t.pairingId,t.agentId),r.state==="cancelled"&&xre(t.pairingId,e.pairingDir),r}var kl,RPe,DU,kPe,yf,w8t,E8t,A8t,x8t,S8t,T8t,NPe,OPe,RU=R(()=>{"use strict";kl=_e(require("node:fs")),RPe=_e(require("node:os")),DU=_e(require("node:path"));V4();I_();ud();Gj();Z_();mU();n8();kPe="4.1.0-rc.42",yf=DU.join(RPe.homedir(),".visa-cli","pairings"),w8t=".initiation.v2.json",E8t=15*6e4,A8t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,x8t=/^ap_[A-Za-z0-9_-]{24}$/,S8t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,T8t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),NPe=2048;OPe=3e4});function FPe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function B8t(e,t){return t?t.aborted?Promise.reject(FPe(t)):new Promise((r,n)=>{let i=()=>n(FPe(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 j8t(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function $Pe(e,t){if(t!==void 0&&j8t(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function U8t(e){return{status:"activated",protocolVersion:Pr,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function YT(e={}){let t=HU(e.pairingDir);if(t){$Pe(t.authUrl,e.authUrl);let s=dd(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 J_({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 by({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:Pr,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await t7({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await J_({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 by({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:Pr,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function M8t(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function ZT(e={}){let t=HU(e.pairingDir);if(!t)return{status:"no_pending"};let r=dd(t.pairingId,"human",e.pairingDir);try{$Pe(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 kre({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return U8t(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 J_({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 by({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await B8t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:Pr,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:M8t(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function PIe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await ei.saveSessionToken(e),!0}catch{return!1}}var _U=R(()=>{"use strict";V4();Qh();RU()});var Mre={};Pi(Mre,{CardDrawRefusedError:()=>Q_,cardDrawIntentHash:()=>tOe,decimalUsdToCents:()=>Ure,fetchCardDrawVerdict:()=>Z8t,loadCardMandateCapability:()=>Y8t,registerCardMandate:()=>X8t});function V8t(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,jre.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function K8t(e){let{secretKey:t,publicKey:r}=DTe(e),n=j_(t),i=sy(r);return{privateJwk:n,publicJwk:i,jkt:V8t(i)}}async function QPe(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:$8t},o=`${ZPe(i)}.${ZPe(n)}`,s=$4(e.privateJwk),a=Vj(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function eOe(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(!W8t.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:G8t,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,jre.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function J8t(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 Ure(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 tOe(e,t){let r=Ure(e.amount);return r===null?null:eOe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Y8t(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(n8(),ie(uPe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=J8t(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=K8t($4(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 VU(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${XPe}ms`)),XPe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function rOe(e){return e.replace(/\/+$/,"")}async function Z8t(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=rOe(e.authBaseUrl),i=tOe(e.draw,e.drawId);if(i===null)throw new Q_(400,["invalid_amount"]);let o=await VU(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Q_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Q_(502,["challenge_malformed"]);let a=await QPe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await VU(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 Q_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function X8t(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=rOe(e.authBaseUrl),i=Ure(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=eOe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await VU(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 QPe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await VU(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 jre,$8t,ZPe,W8t,G8t,Q_,XPe,qre=R(()=>{"use strict";jre=require("node:crypto");V4();$8t="visa-agent-pop+jwt",ZPe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");W8t=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),G8t=1;Q_=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},XPe=3e4});var PCe=g(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});Ml.formatCents=ICe;Ml.formatUsd=x9t;Ml.formatMicros=pM;Ml.formatMicrosWire=S9t;Ml.formatTxAmount=T9t;Ml.formatDate=I9t;Ml.formatRelativeTime=P9t;Ml.formatTime=O9t;Ml.formatAge=C9t;var TCe=1e6,A9t=100;function ICe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/A9t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function x9t(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 pM(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/TCe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function S9t(e,t,r={}){return e&&/^-?\d+$/.test(e)?pM(e,r):t!=null&&Number.isFinite(t)?ICe(t,r):r.fallback??"\u2014"}function T9t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return pM(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?pM(n*TCe,t):t.fallback??"\u2014"}function I9t(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 P9t(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?I8(n,i,a,"minute"):c<24?I8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?I8(n,i,u,"day"):d<4?I8(n,i,d,"week"):l<12?I8(n,i,l,"month"):I8(n,i,p,"year")}function I8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function O9t(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 C9t(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 P8=g(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.formatAge=Xt.formatTime=Xt.formatRelativeTime=Xt.formatDate=Xt.formatTxAmount=Xt.formatMicrosWire=Xt.formatMicros=Xt.formatUsd=Xt.formatCents=void 0;Xt.micros=R9t;Xt.fromCents=k9t;Xt.fromUsdc=N9t;Xt.fromUsd=B9t;Xt.toCents=j9t;Xt.toCentsForAcquirer=U9t;Xt.toUsdc=M9t;Xt.toWire=q9t;Xt.fromWire=D9t;Xt.toDisplay=L9t;Xt.toUsdRounded2dp=z9t;Xt.add=H9t;Xt.sub=F9t;Xt.clampNonNegative=$9t;Xt.isNonNegative=V9t;Xt.max=K9t;Xt.min=W9t;var M0=10000n,OCe=1000000n;function R9t(e){return e}function k9t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*M0}function N9t(e){return e}function B9t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function j9t(e){if(e>=0n)return Number(e/M0);let t=e/M0,r=e%M0;return Number(r===0n?t:t-1n)}function U9t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/M0)}function M9t(e){return e}function q9t(e){return e.toString()}function D9t(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 L9t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/OCe,a=o%OCe,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 z9t(e){let t=e<0n,r=t?-e:e,n=r/M0,o=r%M0*2n,s;o<M0?s=n:o>M0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function H9t(e,t){return e+t}function F9t(e,t){return e-t}function $9t(e){return e<0n?0n:e}function V9t(e){return e>=0n}function K9t(e,t){return e>t?e:t}function W9t(e,t){return e<t?e:t}var q0=PCe();Object.defineProperty(Xt,"formatCents",{enumerable:!0,get:function(){return q0.formatCents}});Object.defineProperty(Xt,"formatUsd",{enumerable:!0,get:function(){return q0.formatUsd}});Object.defineProperty(Xt,"formatMicros",{enumerable:!0,get:function(){return q0.formatMicros}});Object.defineProperty(Xt,"formatMicrosWire",{enumerable:!0,get:function(){return q0.formatMicrosWire}});Object.defineProperty(Xt,"formatTxAmount",{enumerable:!0,get:function(){return q0.formatTxAmount}});Object.defineProperty(Xt,"formatDate",{enumerable:!0,get:function(){return q0.formatDate}});Object.defineProperty(Xt,"formatRelativeTime",{enumerable:!0,get:function(){return q0.formatRelativeTime}});Object.defineProperty(Xt,"formatTime",{enumerable:!0,get:function(){return q0.formatTime}});Object.defineProperty(Xt,"formatAge",{enumerable:!0,get:function(){return q0.formatAge}})});var dne=g(ac=>{"use strict";var G9t=ac&&ac.__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]})),J9t=ac&&ac.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),RCe=ac&&ac.__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"&&G9t(r,t,n[i]);return J9t(r,t),r}})();Object.defineProperty(ac,"__esModule",{value:!0});ac.pruneResponsesDir=une;ac.isTextualContentType=fM;ac.isValidUtf8=NCe;ac.spillFilename=BCe;ac.describePaidBody=ane;ac.capturePaidResponse=txt;var wf=RCe(require("fs")),I7=RCe(require("path")),Y9t=require("node:crypto"),kCe=16*1024,sne=2*1024,Z9t=64*1024*1024,X9t=3e4,cne=256*1024*1024;function une(e,t=cne,r){try{let n=r?I7.basename(r):null,i=wf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=wf.statSync(I7.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{wf.rmSync(I7.join(e,s.name),{force:!0})}catch{}}catch{}}var Q9t=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function fM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||Q9t.has(t)}function NCe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var ext={"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 BCe(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=ext[o]??(fM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jCe(e,t,r){let n=BCe(t,r,new Date),i=I7.extname(n),o=n.slice(0,n.length-i.length);return I7.join(e,`${o}-${(0,Y9t.randomBytes)(8).toString("hex")}${i}`)}function UCe(e){wf.mkdirSync(e,{recursive:!0,mode:448})}function CCe(e,t){let r=0;for(;r<t.length;){let n=wf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function ane(e,t,r,n,i){let o=r?fM(r):NCe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=kCe)return{...s,body:n.toString("utf-8")};UCe(i);let a=jCe(i,e,r);return wf.writeFileSync(a,n,{flag:"wx",mode:384}),une(i,cne,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,sne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function txt(e,t,r,n={}){let i=n.maxBytes??Z9t,o=n.timeoutMs??X9t;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 ane(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&&(wf.closeSync(p),p=null)},E=()=>{if(v(),m)try{wf.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,j)=>{x=setTimeout(()=>j(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<sne){let O=T.subarray(0,Math.min(T.length,sne-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=kCe)continue;UCe(r),f=jCe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=wf.openSync(m,"wx",384);for(let O of u)CCe(p,O);u.length=0,d=0}else CCe(p,T)}if(p===null){let A=Buffer.concat(u,d);return ane(e,t.status,t.headers.get("content-type"),A,r)}v(),wf.renameSync(m,f),m=null,une(r,cne,f);let _=t.headers.get("content-type"),w=_?fM(_):!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 Sy=g(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.TURNKEY_API_BASE_URL_ENV=fo.CIRCLE_TESTNET_FAUCET_URL=fo.NETWORK_ENV=fo.NETWORKS=void 0;fo.resolveNetwork=rxt;fo.turnkeyApiBaseUrl=ixt;fo.explorerTxUrl=oxt;fo.explorerAddressUrl=sxt;fo.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}};fo.NETWORK_ENV="VISA_V4_NETWORK";fo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var MCe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function rxt(e=process.env){let t=(e[fo.NETWORK_ENV]??"").trim();if(t==="")return fo.NETWORKS["base-mainnet"];let r=MCe[t.toLowerCase()];if(!r)throw new Error(`unknown ${fo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(MCe).join(", "));return fo.NETWORKS[r]}fo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var nxt="https://api.turnkey.com";function ixt(e=process.env){let t=(e[fo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?nxt:t}function oxt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function sxt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qCe=g(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.version=void 0;mM.version="1.2.3"});var g6=g(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.BaseError=void 0;var axt=qCe(),lne=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@${axt.version}`].join(`
|
|
179
179
|
`);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}};hM.BaseError=lne});var DCe=g(pne=>{"use strict";Object.defineProperty(pne,"__esModule",{value:!0});pne.narrow=cxt;function cxt(e){return e}});var P7=g(D0=>{"use strict";Object.defineProperty(D0,"__esModule",{value:!0});D0.isTupleRegex=D0.integerRegex=D0.bytesRegex=void 0;D0.execTyped=uxt;function uxt(e,t){return e.exec(t)?.groups}D0.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;D0.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)?$/;D0.isTupleRegex=/^\(.+?\).*?$/});var hne=g(mne=>{"use strict";Object.defineProperty(mne,"__esModule",{value:!0});mne.formatAbiParameter=fne;var dxt=P7(),LCe=/^tuple(?<array>(\[(\d*)\])*)$/;function fne(e){let t=e.type;if(LCe.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+=fne(o),i<r-1&&(t+=", ")}let n=(0,dxt.execTyped)(LCe,e.type);return t+=`)${n?.array||""}`,fne({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var gne=g(yne=>{"use strict";Object.defineProperty(yne,"__esModule",{value:!0});yne.formatAbiParameters=pxt;var lxt=hne();function pxt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,lxt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var _ne=g(bne=>{"use strict";Object.defineProperty(bne,"__esModule",{value:!0});bne.formatAbiItem=fxt;var O7=gne();function fxt(e){return e.type==="function"?`function ${e.name}(${(0,O7.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,O7.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,O7.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,O7.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,O7.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var zCe=g(vne=>{"use strict";Object.defineProperty(vne,"__esModule",{value:!0});vne.formatAbi=hxt;var mxt=_ne();function hxt(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,mxt.formatAbiItem)(i);t.push(o)}return t}});var b6=g(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.functionModifiers=Ci.eventModifiers=Ci.modifiers=void 0;Ci.isErrorSignature=yxt;Ci.execErrorSignature=gxt;Ci.isEventSignature=bxt;Ci.execEventSignature=_xt;Ci.isFunctionSignature=vxt;Ci.execFunctionSignature=wxt;Ci.isStructSignature=Ext;Ci.execStructSignature=Axt;Ci.isConstructorSignature=xxt;Ci.execConstructorSignature=Sxt;Ci.isFallbackSignature=Txt;Ci.execFallbackSignature=Ixt;Ci.isReceiveSignature=Oxt;var O8=P7(),HCe=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function yxt(e){return HCe.test(e)}function gxt(e){return(0,O8.execTyped)(HCe,e)}var FCe=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function bxt(e){return FCe.test(e)}function _xt(e){return(0,O8.execTyped)(FCe,e)}var $Ce=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function vxt(e){return $Ce.test(e)}function wxt(e){return(0,O8.execTyped)($Ce,e)}var VCe=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Ext(e){return VCe.test(e)}function Axt(e){return(0,O8.execTyped)(VCe,e)}var KCe=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function xxt(e){return KCe.test(e)}function Sxt(e){return(0,O8.execTyped)(KCe,e)}var WCe=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function Txt(e){return WCe.test(e)}function Ixt(e){return(0,O8.execTyped)(WCe,e)}var Pxt=/^receive\(\) external payable$/;function Oxt(e){return Pxt.test(e)}Ci.modifiers=new Set(["memory","indexed","storage","calldata"]);Ci.eventModifiers=new Set(["indexed"]);Ci.functionModifiers=new Set(["calldata","memory","storage"])});var C7=g(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});Ty.UnknownSolidityTypeError=Ty.UnknownTypeError=Ty.InvalidAbiItemError=void 0;var xne=g6(),wne=class extends xne.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"})}};Ty.InvalidAbiItemError=wne;var Ene=class extends xne.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"})}};Ty.UnknownTypeError=Ene;var Ane=class extends xne.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"})}};Ty.UnknownSolidityTypeError=Ane});var C8=g(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.InvalidAbiTypeParameterError=Ws.InvalidFunctionModifierError=Ws.InvalidModifierError=Ws.SolidityProtectedKeywordError=Ws.InvalidParameterError=Ws.InvalidAbiParametersError=Ws.InvalidAbiParameterError=void 0;var _6=g6(),Sne=class extends _6.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"})}};Ws.InvalidAbiParameterError=Sne;var Tne=class extends _6.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"})}};Ws.InvalidAbiParametersError=Tne;var Ine=class extends _6.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};Ws.InvalidParameterError=Ine;var Pne=class extends _6.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"})}};Ws.SolidityProtectedKeywordError=Pne;var One=class extends _6.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"})}};Ws.InvalidModifierError=One;var Cne=class extends _6.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"})}};Ws.InvalidFunctionModifierError=Cne;var Rne=class extends _6.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"})}};Ws.InvalidAbiTypeParameterError=Rne});var yM=g(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});Iy.InvalidStructSignatureError=Iy.UnknownSignatureError=Iy.InvalidSignatureError=void 0;var jne=g6(),kne=class extends jne.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};Iy.InvalidSignatureError=kne;var Nne=class extends jne.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};Iy.UnknownSignatureError=Nne;var Bne=class extends jne.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"})}};Iy.InvalidStructSignatureError=Bne});var Mne=g(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0});gM.CircularReferenceError=void 0;var Cxt=g6(),Une=class extends Cxt.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"})}};gM.CircularReferenceError=Une});var Dne=g(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.InvalidParenthesisError=void 0;var Rxt=g6(),qne=class extends Rxt.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"})}};bM.InvalidParenthesisError=qne});var GCe=g(R7=>{"use strict";Object.defineProperty(R7,"__esModule",{value:!0});R7.parameterCache=void 0;R7.getParameterCacheKey=kxt;function kxt(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}`}R7.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 w6=g(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.parseSignature=jxt;fu.parseFunctionSignature=JCe;fu.parseEventSignature=YCe;fu.parseErrorSignature=ZCe;fu.parseConstructorSignature=XCe;fu.parseFallbackSignature=QCe;fu.parseAbiParameter=v6;fu.splitParameters=bd;fu.isSolidityType=eRe;fu.isSolidityKeyword=tRe;fu.isValidDataLocation=rRe;var R8=P7(),Nxt=C7(),_M=C8(),k8=yM(),Bxt=Dne(),vM=GCe(),xa=b6();function jxt(e,t={}){if((0,xa.isFunctionSignature)(e))return JCe(e,t);if((0,xa.isEventSignature)(e))return YCe(e,t);if((0,xa.isErrorSignature)(e))return ZCe(e,t);if((0,xa.isConstructorSignature)(e))return XCe(e,t);if((0,xa.isFallbackSignature)(e))return QCe(e);if((0,xa.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new k8.UnknownSignatureError({signature:e})}function JCe(e,t={}){let r=(0,xa.execFunctionSignature)(e);if(!r)throw new k8.InvalidSignatureError({signature:e,type:"function"});let n=bd(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(v6(n[a],{modifiers:xa.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=bd(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(v6(a[u],{modifiers:xa.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function YCe(e,t={}){let r=(0,xa.execEventSignature)(e);if(!r)throw new k8.InvalidSignatureError({signature:e,type:"event"});let n=bd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(v6(n[s],{modifiers:xa.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function ZCe(e,t={}){let r=(0,xa.execErrorSignature)(e);if(!r)throw new k8.InvalidSignatureError({signature:e,type:"error"});let n=bd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(v6(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function XCe(e,t={}){let r=(0,xa.execConstructorSignature)(e);if(!r)throw new k8.InvalidSignatureError({signature:e,type:"constructor"});let n=bd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(v6(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function QCe(e){let t=(0,xa.execFallbackSignature)(e);if(!t)throw new k8.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var Uxt=/^(?<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$_]*))?$/,Mxt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,qxt=/^u?int$/;function v6(e,t){let r=(0,vM.getParameterCacheKey)(e,t?.type,t?.structs);if(vM.parameterCache.has(r))return vM.parameterCache.get(r);let n=R8.isTupleRegex.test(e),i=(0,R8.execTyped)(n?Mxt:Uxt,e);if(!i)throw new _M.InvalidParameterError({param:e});if(i.name&&tRe(i.name))throw new _M.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=bd(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(v6(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(qxt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!eRe(c))throw new Nxt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new _M.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(xa.functionModifiers.has(i.modifier)&&!rRe(c,!!i.array))throw new _M.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return vM.parameterCache.set(r,d),d}function bd(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?bd(a,[...t,r.trim()]):bd(a,t,`${r}${s}`,n);case"(":return bd(a,t,`${r}${s}`,n+1);case")":return bd(a,t,`${r}${s}`,n-1);default:return bd(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Bxt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function eRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||R8.bytesRegex.test(e)||R8.integerRegex.test(e)}var Dxt=/^(?: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 tRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||R8.bytesRegex.test(e)||R8.integerRegex.test(e)||Dxt.test(e)}function rRe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var k7=g(Lne=>{"use strict";Object.defineProperty(Lne,"__esModule",{value:!0});Lne.parseStructs=Fxt;var nRe=P7(),Lxt=C7(),zxt=C8(),iRe=yM(),Hxt=Mne(),oRe=b6(),sRe=w6();function Fxt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,oRe.isStructSignature)(a))continue;let c=(0,oRe.execStructSignature)(a);if(!c)throw new iRe.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,sRe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new iRe.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]=aRe(c,t)}return n}var $xt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function aRe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(nRe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,nRe.execTyped)($xt,s.type);if(!c?.type)throw new zxt.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new Hxt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:aRe(t[d],t,new Set([...r,d]))})}else if((0,sRe.isSolidityType)(d))n.push(s);else throw new Lxt.UnknownTypeError({type:d})}}return n}});var cRe=g(zne=>{"use strict";Object.defineProperty(zne,"__esModule",{value:!0});zne.parseAbi=Gxt;var Vxt=b6(),Kxt=k7(),Wxt=w6();function Gxt(e){let t=(0,Kxt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,Vxt.isStructSignature)(o)||r.push((0,Wxt.parseSignature)(o,t))}return r}});var dRe=g(Hne=>{"use strict";Object.defineProperty(Hne,"__esModule",{value:!0});Hne.parseAbiItem=Xxt;var Jxt=C7(),Yxt=b6(),Zxt=k7(),uRe=w6();function Xxt(e){let t;if(typeof e=="string")t=(0,uRe.parseSignature)(e);else{let r=(0,Zxt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,Yxt.isStructSignature)(o)){t=(0,uRe.parseSignature)(o,r);break}}}if(!t)throw new Jxt.InvalidAbiItemError({signature:e});return t}});var pRe=g($ne=>{"use strict";Object.defineProperty($ne,"__esModule",{value:!0});$ne.parseAbiParameter=tSt;var Qxt=C8(),Fne=b6(),eSt=k7(),lRe=w6();function tSt(e){let t;if(typeof e=="string")t=(0,lRe.parseAbiParameter)(e,{modifiers:Fne.modifiers});else{let r=(0,eSt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,Fne.isStructSignature)(o)){t=(0,lRe.parseAbiParameter)(o,{modifiers:Fne.modifiers,structs:r});break}}}if(!t)throw new Qxt.InvalidAbiParameterError({param:e});return t}});var hRe=g(Kne=>{"use strict";Object.defineProperty(Kne,"__esModule",{value:!0});Kne.parseAbiParameters=iSt;var rSt=C8(),Vne=b6(),nSt=k7(),fRe=w6(),mRe=w6();function iSt(e){let t=[];if(typeof e=="string"){let r=(0,fRe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,mRe.parseAbiParameter)(r[i],{modifiers:Vne.modifiers}))}else{let r=(0,nSt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,Vne.isStructSignature)(o))continue;let s=(0,fRe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,mRe.parseAbiParameter)(s[c],{modifiers:Vne.modifiers,structs:r}))}}if(t.length===0)throw new rSt.InvalidAbiParametersError({params:e});return t}});var N7=g(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.CircularReferenceError=ft.InvalidParenthesisError=ft.UnknownSignatureError=ft.InvalidSignatureError=ft.InvalidStructSignatureError=ft.InvalidAbiParameterError=ft.InvalidAbiParametersError=ft.InvalidParameterError=ft.SolidityProtectedKeywordError=ft.InvalidModifierError=ft.InvalidFunctionModifierError=ft.InvalidAbiTypeParameterError=ft.UnknownSolidityTypeError=ft.InvalidAbiItemError=ft.UnknownTypeError=ft.parseAbiParameters=ft.parseAbiParameter=ft.parseAbiItem=ft.parseAbi=ft.formatAbiParameters=ft.formatAbiParameter=ft.formatAbiItem=ft.formatAbi=ft.narrow=ft.BaseError=void 0;var oSt=g6();Object.defineProperty(ft,"BaseError",{enumerable:!0,get:function(){return oSt.BaseError}});var sSt=DCe();Object.defineProperty(ft,"narrow",{enumerable:!0,get:function(){return sSt.narrow}});var aSt=zCe();Object.defineProperty(ft,"formatAbi",{enumerable:!0,get:function(){return aSt.formatAbi}});var cSt=_ne();Object.defineProperty(ft,"formatAbiItem",{enumerable:!0,get:function(){return cSt.formatAbiItem}});var uSt=hne();Object.defineProperty(ft,"formatAbiParameter",{enumerable:!0,get:function(){return uSt.formatAbiParameter}});var dSt=gne();Object.defineProperty(ft,"formatAbiParameters",{enumerable:!0,get:function(){return dSt.formatAbiParameters}});var lSt=cRe();Object.defineProperty(ft,"parseAbi",{enumerable:!0,get:function(){return lSt.parseAbi}});var pSt=dRe();Object.defineProperty(ft,"parseAbiItem",{enumerable:!0,get:function(){return pSt.parseAbiItem}});var fSt=pRe();Object.defineProperty(ft,"parseAbiParameter",{enumerable:!0,get:function(){return fSt.parseAbiParameter}});var mSt=hRe();Object.defineProperty(ft,"parseAbiParameters",{enumerable:!0,get:function(){return mSt.parseAbiParameters}});var Wne=C7();Object.defineProperty(ft,"UnknownTypeError",{enumerable:!0,get:function(){return Wne.UnknownTypeError}});Object.defineProperty(ft,"InvalidAbiItemError",{enumerable:!0,get:function(){return Wne.InvalidAbiItemError}});Object.defineProperty(ft,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return Wne.UnknownSolidityTypeError}});var E6=C8();Object.defineProperty(ft,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return E6.InvalidAbiTypeParameterError}});Object.defineProperty(ft,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return E6.InvalidFunctionModifierError}});Object.defineProperty(ft,"InvalidModifierError",{enumerable:!0,get:function(){return E6.InvalidModifierError}});Object.defineProperty(ft,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return E6.SolidityProtectedKeywordError}});Object.defineProperty(ft,"InvalidParameterError",{enumerable:!0,get:function(){return E6.InvalidParameterError}});Object.defineProperty(ft,"InvalidAbiParametersError",{enumerable:!0,get:function(){return E6.InvalidAbiParametersError}});Object.defineProperty(ft,"InvalidAbiParameterError",{enumerable:!0,get:function(){return E6.InvalidAbiParameterError}});var Gne=yM();Object.defineProperty(ft,"InvalidStructSignatureError",{enumerable:!0,get:function(){return Gne.InvalidStructSignatureError}});Object.defineProperty(ft,"InvalidSignatureError",{enumerable:!0,get:function(){return Gne.InvalidSignatureError}});Object.defineProperty(ft,"UnknownSignatureError",{enumerable:!0,get:function(){return Gne.UnknownSignatureError}});var hSt=Dne();Object.defineProperty(ft,"InvalidParenthesisError",{enumerable:!0,get:function(){return hSt.InvalidParenthesisError}});var ySt=Mne();Object.defineProperty(ft,"CircularReferenceError",{enumerable:!0,get:function(){return ySt.CircularReferenceError}})});var ir=g(Jne=>{"use strict";Object.defineProperty(Jne,"__esModule",{value:!0});Jne.getAction=gSt;function gSt(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 Ef=g(wM=>{"use strict";Object.defineProperty(wM,"__esModule",{value:!0});wM.formatAbiItem=_St;wM.formatAbiParams=Yne;var bSt=Dn();function _St(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new bSt.InvalidDefinitionTypeError(e.type);return`${e.name}(${Yne(e.inputs,{includeName:t})})`}function Yne(e,{includeName:t=!1}={}){return e?e.map(r=>vSt(r,{includeName:t})).join(t?", ":","):""}function vSt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Yne(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var ds=g(Zne=>{"use strict";Object.defineProperty(Zne,"__esModule",{value:!0});Zne.isHex=wSt;function wSt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var ls=g(Xne=>{"use strict";Object.defineProperty(Xne,"__esModule",{value:!0});Xne.size=ASt;var ESt=ds();function ASt(e){return(0,ESt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var yRe=g(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.version=void 0;EM.version="2.54.6"});var Ot=g(B7=>{"use strict";Object.defineProperty(B7,"__esModule",{value:!0});B7.BaseError=void 0;B7.setErrorConfig=xSt;var gRe=yRe(),AM={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${gRe.version}`};function xSt(e){AM=e}var Qne=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=AM.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...AM.version?[`Version: ${AM.version}`]:[]].join(`
|
|
180
180
|
`);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=gRe.version}walk(t){return bRe(this,t)}};B7.BaseError=Qne;function bRe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?bRe(e.cause,t):t?null:e}});var Dn=g(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.UnsupportedPackedAbiType=lt.InvalidDefinitionTypeError=lt.InvalidArrayError=lt.InvalidAbiDecodingTypeError=lt.InvalidAbiEncodingTypeError=lt.DecodeLogTopicsMismatch=lt.DecodeLogDataMismatch=lt.BytesSizeMismatchError=lt.AbiItemAmbiguityError=lt.AbiFunctionSignatureNotFoundError=lt.AbiFunctionOutputsNotFoundError=lt.AbiFunctionNotFoundError=lt.AbiEventNotFoundError=lt.AbiEventSignatureNotFoundError=lt.AbiEventSignatureEmptyTopicsError=lt.AbiErrorSignatureNotFoundError=lt.AbiErrorNotFoundError=lt.AbiErrorInputsNotFoundError=lt.AbiEncodingLengthMismatchError=lt.AbiEncodingBytesSizeMismatchError=lt.AbiEncodingArrayLengthMismatchError=lt.AbiDecodingZeroDataError=lt.AbiDecodingDataSizeTooSmallError=lt.AbiDecodingDataSizeInvalidError=lt.AbiConstructorParamsNotFoundError=lt.AbiConstructorNotFoundError=void 0;var j7=Ef(),SSt=ls(),ln=Ot(),eie=class extends ln.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(`
|
|
181
181
|
`),{docsPath:t,name:"AbiConstructorNotFoundError"})}};lt.AbiConstructorNotFoundError=eie;var tie=class extends ln.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(`
|
|
@@ -20907,7 +20907,7 @@ ${n}
|
|
|
20907
20907
|
`),wT(ET(),n+`
|
|
20908
20908
|
`)}catch{}}function eSe(e){try{let t=fj();if(!t)return;let r=Math.max(Date.now(),t.renderedAt+1),n={...t,refreshFailedAt:r,refreshErrorReason:vT(e).slice(0,200)};wT(E_(),JSON.stringify(n)+`
|
|
20909
20909
|
`)}catch{}}function w_(){try{wr.unlinkSync(Wxe())}catch{}}function fj(){let e=E_();if(!wr.existsSync(e))return null;try{return JSON.parse(wr.readFileSync(e,"utf-8"))}catch{return null}}function tSe(){return fj()?.status??null}function u6t(){if(process.env.JEST_WORKER_ID)return;let e=Wxe();try{if(wr.mkdirSync(Vr.dirname(e),{recursive:!0}),!m6t(e))return;let t=process.argv[1]?Vr.resolve(process.argv[1]):"";if(!t){w_();return}let r=cj(),n=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),i=r==="no-color"||n==="light"||n==="dark"?{}:{VISA_CLI_HUD_THEME:r},o=(0,Vxe.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...i,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",w_),o.unref()}catch{w_()}}function vT(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var d6t=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function l6t(e){let t=[],r=`__VISA_CLI_HUD_SGR_${(0,dee.randomBytes)(8).toString("hex")}_`,n=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!d6t.test(o))return"";let s=`${r}${t.length}__`;return t.push(o),s}),i=new RegExp(`${r}(\\d+)__`,"g");return vT(n).replace(i,(o,s)=>t[Number(s)]??"")}var rc={get reset(){return Ds().reset},get visaBlue(){return Ds().visaBlue},get visaBlueSoft(){return Ds().visaBlueSoft},get visaGold(){return Ds().visaGold},get green(){return Ds().green},get muted(){return Ds().muted},get chrome(){return Ds().chrome}};function uu(e,t){return e.length===0||process.env.NO_COLOR||uj()?e:`${t}${e}${rc.reset}`}function $xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mee(){let e=A_.homedir();if(!e||!Vr.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Vr.resolve(e)}function p6t(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function f6t(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function m6t(e){for(let t=0;t<2;t+=1){let r;try{return r=wr.openSync(e,"wx"),wr.writeFileSync(r,String(Date.now())),!0}catch(n){if(n?.code!=="EEXIST")return!1;try{let i=wr.statSync(e);if(Date.now()-i.mtimeMs<=Q_t)return!1;wr.unlinkSync(e)}catch{}}finally{r!==void 0&&wr.closeSync(r)}}return!1}function uee(e){return e instanceof Error?e.message:"unknown file system error"}function wT(e,t){wr.mkdirSync(Vr.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${(0,dee.randomBytes)(8).toString("hex")}.tmp`;try{wr.writeFileSync(r,t),wr.renameSync(r,e)}catch(n){try{wr.unlinkSync(r)}catch{}throw n}}var h6t=1440*60*1e3;function hj(e,t){Io.mkdirSync(Ea.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${iSe.randomBytes(8).toString("hex")}.tmp`;try{Io.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
20910
|
-
`),Io.renameSync(r,e)}catch(n){try{Io.unlinkSync(r)}catch{}throw n}}function rSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var yee="# visa-cli-hud-v1";function yj(e,t){if(!e&&!t&&y6t())return`visa-cli config statusline ${yee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?Ea.resolve(n):"";return`${i?`${rSe(r)} ${rSe(i)} config statusline`:"visa-cli config statusline"} ${yee}`}function y6t(){try{return(0,oSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function ey(e){return typeof e!="string"?!1:e.includes(yee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function g6t(){return"4.1.0-rc.
|
|
20910
|
+
`),Io.renameSync(r,e)}catch(n){try{Io.unlinkSync(r)}catch{}throw n}}function rSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var yee="# visa-cli-hud-v1";function yj(e,t){if(!e&&!t&&y6t())return`visa-cli config statusline ${yee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?Ea.resolve(n):"";return`${i?`${rSe(r)} ${rSe(i)} config statusline`:"visa-cli config statusline"} ${yee}`}function y6t(){try{return(0,oSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function ey(e){return typeof e!="string"?!1:e.includes(yee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function g6t(){return"4.1.0-rc.42"}function gj(e){let t=Ea.dirname(Ea.resolve(e));return Ea.basename(t)===".claude"?Ea.dirname(t):sSe.homedir()}function mj(e,t){let r=Ea.relative(t,e);return!r.startsWith("..")&&!Ea.isAbsolute(r)?`~/${r}`:e}function b6t(e){return Ea.join(gj(e),".visa-cli","hud-self-heal.json")}function _6t(e,t,r,n){try{if(!Io.existsSync(e))return!1;let i=JSON.parse(Io.readFileSync(e,"utf-8"));return i.version===t&&typeof i.checkedAt=="number"&&r-i.checkedAt<n}catch{return!1}}function hee(e,t,r){try{hj(e,{version:t,checkedAt:r})}catch{}}function v6t(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function bj(e,t={}){let r=t.now??Date.now(),n=t.version??g6t(),i=t.stampPath??b6t(e),o=t.minIntervalMs??h6t,s=[],a=!1,c=!1;if(!t.force&&_6t(i,n,r,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!Io.existsSync(e))return hee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(Io.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!ey(l))return hee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??yj)();if(l!==p&&(u.statusLine=v6t(d,p),hj(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!_j()){let f=gj(e);if(x_(f).length>0){let h=g0(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let y=h.rcPaths.map(v=>mj(v,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${y}.`)}}}return hee(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}catch(u){if(t.force){let d=u instanceof Error?u.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${d}. Run: visa-cli config hud doctor
|
|
20911
20911
|
`)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}}function w6t(e,t){let r=gj(t),n=x_(r);if(n.length===0)return e;let i=n.map(o=>mj(o,r)).join(", ");return`${e}
|
|
20912
20912
|
Note: a shell-prompt HUD block was detected in ${i}. If it is unintended, remove it with: visa-cli config hud disable shell`}function _j(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function nSe(e,t){let r=gj(t),n=x_(r);if(n.length===0)return e;let i=n.map(s=>mj(s,r)).join(", ");if(_j())return`${e}
|
|
20913
20913
|
Note: a legacy shell-prompt HUD block was detected in ${i}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=g0(null,r);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let s=o.rcPaths.map(a=>mj(a,r)).join(", ");return`${e}
|
|
@@ -20916,10 +20916,10 @@ Note: a legacy shell-prompt HUD block was detected in ${i} but could not be auto
|
|
|
20916
20916
|
`)}var ySe="WARNING: This Visa Key is a bearer secret for headless API use. Touch ID will not be prompted when the key is used; anyone with the key can authorize API charges within the caps above until it expires or is revoked. Store it like a password and revoke it immediately if exposed.";function x6t(e){let t=Math.max(5,...e.map(([o])=>o.length)),r=Math.max(5,...e.map(([,o])=>o.length)),n=`+-${"-".repeat(t)}-+-${"-".repeat(r)}-+`,i=(o,s)=>`| ${o.padEnd(t)} | ${s.padEnd(r)} |`;return[n,i("Field","Value"),n,...e.map(([o,s])=>i(o,s)),n]}function gSe(e,t={}){let r=[...A6t().split(`
|
|
20917
20917
|
`),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...x6t([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${gee(e.daily_cap_cents)}/day`],["Total cap",mSe(e.total_cap_cents)],["Allowed tools",hSe(e.allowed_tools)]]),"","Guardrails",`- Spend: ${gee(e.daily_cap_cents)}/day, ${mSe(e.total_cap_cents)} total`,`- Tools: ${hSe(e.allowed_tools)}`,"- Auth: X-Api-Key header for supported v4 services","Save this key now - it won't be shown again."];return e.biometric_warning?r.push("",ySe,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",ySe),`${r.join(`
|
|
20918
20918
|
`)}
|
|
20919
|
-
`}function bSe(e){return e.json===!0||e.isTTY!==!0}function bee(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return r}function _ee(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return r}function _Se(e,t){let r=bee(e);if(r!==void 0)return r;if(bSe(t))return 500}function vSe(e,t){let r=_ee(e);if(r!==void 0)return r;if(bSe(t)||t.recommendedCapsAccepted===!0)return 2500}async function wSe(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 vj=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var ESe={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 ASe(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&&ESe[r]?ESe[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 S6t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function SSe(e,t){let r=xSe(e),n=xSe(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:T6t(r.pre,n.pre)>0}function xSe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(S6t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function T6t(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}function ty(){return!!(TSe(process.env.VISA_CLI_NO_UPDATE_CHECK)||TSe(process.env.CI)||process.env.NODE_ENV==="test")}function TSe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}I_();var Ij="4.1.0-rc.
|
|
20919
|
+
`}function bSe(e){return e.json===!0||e.isTTY!==!0}function bee(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return r}function _ee(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return r}function _Se(e,t){let r=bee(e);if(r!==void 0)return r;if(bSe(t))return 500}function vSe(e,t){let r=_ee(e);if(r!==void 0)return r;if(bSe(t)||t.recommendedCapsAccepted===!0)return 2500}async function wSe(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 vj=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var ESe={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 ASe(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&&ESe[r]?ESe[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 S6t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function SSe(e,t){let r=xSe(e),n=xSe(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:T6t(r.pre,n.pre)>0}function xSe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(S6t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function T6t(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}function ty(){return!!(TSe(process.env.VISA_CLI_NO_UPDATE_CHECK)||TSe(process.env.CI)||process.env.NODE_ENV==="test")}function TSe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}I_();var Ij="4.1.0-rc.42",L6t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function z6t(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}).`)}var H6t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function M4(e){return typeof e=="string"?e.trim():""}function F6t(e){let t=e&&typeof e=="object"?e:{},r=M4(t.error)||M4(t.message);if(!r)return H6t;let n=M4(t.error_code),i=[["surface",M4(t.disabled_surface)],["flag",M4(t.flag)],["correlation_id",M4(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 $6t(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?L6t.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(`
|
|
20920
20920
|
`)}var rf=class{constructor(t){this.getSessionToken=t;this.baseUrl=du()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!ty()){let n=t.headers.get("X-Latest-Version");n&&SSe(n,Ij)&&(this.lastSignals.updateAvailable={currentVersion:Ij,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Ij}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new vj(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(F6t(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error($6t());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 wSe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Ij,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(ASe(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),z6t(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 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)}};Cee();var Ree=require("child_process"),GSe=require("util"),JSe=_e(require("crypto")),en=_e(require("fs")),YSe=_e(require("os")),Ls=_e(require("path"));ud();ZB();Qh();var _0=(0,GSe.promisify)(Ree.execFile),G6t=6e4,J6t=()=>process.platform==="darwin",q4=()=>process.platform==="win32",ny=Ls.join(YSe.homedir(),".visa-mcp","bin"),O_=Ls.join(ny,"Visa CLI"),b0=Ls.join(ny,"visa-keychain-win.exe"),ZSe=Ls.join(__dirname,"..","native"),DSe="6",LSe=Ls.join(ny,"visa-keychain.version"),zSe=Ls.join(ny,"visa-keychain.sha256"),HSe="1",FSe=Ls.join(ny,"visa-keychain-win.version"),$Se=Ls.join(ny,"visa-keychain-win.sha256"),XSe=[Ls.join(ZSe,"bin","win32-x64","visa-keychain-win.exe"),Ls.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Ls.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Pj(e){let t=en.readFileSync(e);return JSe.createHash("sha256").update(t).digest("hex")}function Y6t(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let r=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(r)}function VSe(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function KSe(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function QSe(){try{if(en.readFileSync(LSe,"utf-8").trim()===DSe&&en.existsSync(O_)){let n=en.readFileSync(zSe,"utf-8").trim();if(Pj(O_)!==n)Me.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),en.unlinkSync(O_);else return O_}}catch{}let e=Ls.join(ZSe,"visa-keychain.m");if(en.existsSync(e)||(e=Ls.resolve(__dirname,"..","..","native","visa-keychain.m")),en.existsSync(e)||(e=Ls.resolve(__dirname,"..","native","visa-keychain.m")),!en.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");en.mkdirSync(ny,{recursive:!0,mode:448});try{await _0("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",O_,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=Pj(O_);return en.writeFileSync(zSe,t,{mode:384}),en.writeFileSync(LSe,DSe,{mode:384}),O_}function eTe(){for(let e of XSe)if(en.existsSync(e))return e;return null}async function Rj(){try{if(en.readFileSync(FSe,"utf-8").trim()===HSe&&en.existsSync(b0)){let n=en.readFileSync($Se,"utf-8").trim();if(Pj(b0)!==n)Me.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),en.unlinkSync(b0);else return b0}}catch{}let e=eTe();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
20921
|
-
If building from source, run native/build-win.bat first.`);en.mkdirSync(ny,{recursive:!0}),en.copyFileSync(e,b0);let t=Pj(b0);return en.writeFileSync($Se,t,{mode:384}),en.writeFileSync(FSe,HSe,{mode:384}),b0}async function Z6t(){return q4()?Rj():QSe()}var Oj="visa-cli",Cj="attestation-key";async function X6t(e){if(!await tf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await _0("security",["delete-generic-password","-s",Oj,"-a",Cj],{timeout:5e3})}catch{}try{await _0("security",["add-generic-password","-s",Oj,"-a",Cj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${Q6t(t)}).`)}}function Q6t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function evt(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(i)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function tvt(){if(!await tf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await _0("security",["find-generic-password","-s",Oj,"-a",Cj,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:evt(e)}}}async function rvt(){let e=await tvt();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function tTe(e){let t=await Z6t(),r;try{r=(await _0(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 Y6t(r)}var WSe=!1;function nvt(){if(!q4())return!1;try{return en.existsSync(b0)||eTe()!==null?!0:(WSe||(WSe=!0,Me.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:b0,searchedPrebuiltPaths:XSe})),!1)}catch{return!1}}function v0(){return hT()||J6t()?!0:q4()?nvt():!1}async function rTe(){if(q4()){let i=await Rj(),{stdout:o}=await _0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await tTe(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let r=e.slice(0,t),n=e.slice(t+1);return await X6t(r),n}async function kee(e,t,r={}){if(hT())return Promise.resolve(Axe());let n=r.timeoutMs??G6t;if(q4()){let a=await Rj(),c=["sign",e];t&&c.push(t);let u;try{u=(await _0(a,c,{timeout:n})).stdout}catch(l){throw VSe(l)?KSe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await rvt();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await QSe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,Ree.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):VSe(d)?c(KSe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function kj(){if(q4()){try{let e=await Rj();await _0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await tf())try{await _0("security",["delete-generic-password","-s",Oj,"-a",Cj],{timeout:5e3})}catch{}try{await tTe(["delete-key"])}catch{}}Qh();ud();sj();_U();n8();var lCe=require("child_process"),cM=_e(require("fs")),uM=_e(require("os")),pCe=_e(require("path"));I_();ZB();var VPe="4.1.0-rc.
|
|
20922
|
-
`)}function WPe(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var Lre=require("node:os"),l7=require("node:path"),p7=require("node:fs/promises"),iOe=require("node:fs"),oOe=require("node:url"),sOe=require("node:crypto");ud();var L8t=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function c8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!L8t.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var R0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function GPe(e){let t;try{t=new URL(e)}catch{throw new R0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new R0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}ud();var z8t={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},H8t=300*1e3,Bre={},JPe=0,u7=null;function F8t(){return u7||(u7=(async()=>{try{let e=await Nl.getFeatureFlags();Bre=e&&e.flags||{},JPe=Date.now()}catch(e){Bre={},Me.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{u7=null}})(),u7)}async function FU(){Date.now()-JPe<H8t||await F8t()}function u8(e){let t=z8t[e];return t?Bre[t]!==!0:!1}var YPe=require("node:crypto"),d7=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},$U=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 d7(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??YPe.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 aOe(e){return[(0,l7.join)(e,"checkout-engine","index.js"),(0,l7.join)(e,"..","checkout-engine","index.js")]}function Q8t(e,t=iOe.existsSync){return aOe(e).find(r=>t(r))??null}var KU=null,cOe=async()=>{if(KU)return KU;let e=Q8t(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${aOe(__dirname).join(" and ")}).`);return KU=(await import((0,oOe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await e3t(),cardMandateRegister:await t3t()}),KU};async function e3t(){let e=await Promise.resolve().then(()=>(qre(),Mre));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function t3t(){let e=await Promise.resolve().then(()=>(qre(),Mre));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function zre(){return u8("pay_merchant")?(await FU(),u8("pay_merchant")):!1}var uOe=(0,l7.join)((0,Lre.homedir)(),".visa-mcp","agent-credential.json"),dOe=(0,l7.join)((0,Lre.homedir)(),".visa-mcp","contact.json"),lOe=new $U;function f7(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var r3t=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function pOe(e){return r3t.has(e)?e:null}async function WU(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?f7(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:pOe(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){Me.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function nOe(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?f7(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:pOe(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){Me.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function Dre(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new R0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function fOe(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=f7(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 mOe(e={},t={}){if(await(t.flagDisabled??zre)())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??lOe).get(n);return o?fOe(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 hOe(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:Pee()&&!process.env.VISA_VERIFY_WEB_URL?null:P_();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??zre)())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??lOe,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=GPe(e.url??"").toString(),c=Dre(e.amount)}catch(I){if(I instanceof R0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??uOe,l=t.contactPath??dOe;try{await(0,p7.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,p7.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 I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);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??cOe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);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 I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>Nl.emitTelemetry(I)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Me.info("pay_merchant:review",{host:_,currency:u});let I;try{I=await y.review(v)}catch(T){throw await WU({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 WU({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${c8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{Me.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,...I?{onApprovalUrl:I}:{}})}catch(U){throw await WU({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:U instanceof Error?U.message:String(U),startedAt:A,submit:m}),U}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",j=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await WU({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:j,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=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:j,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)"}.${M}`: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.${M}`:`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 I=(0,sOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Me.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async O=>{try{let j=await S(M=>{Me.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(M)});return Me.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:j.success===!0}),j}catch(j){throw Me.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:f7(j instanceof Error?j.message:String(j))}),j}}});return fOe(T,"authorize")}catch(T){if(T instanceof d7)return Me.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 yOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:P_();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??zre)())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=Dre(e.ceiling)}catch(_){if(_ instanceof R0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=Dre(e.perTransaction)}catch(_){if(_ instanceof R0)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??uOe,u=t.contactPath??dOe;try{await(0,p7.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,p7.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??cOe,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??(_=>Nl.emitTelemetry(_)),y=Date.now();Me.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?f7(_.message):String(_);return Me.warn("start_card_mandate:failed",{message:w}),await nOe({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&&Me.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await nOe({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 ${c8(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 cCe=require("node:crypto");var iCe=require("node:crypto");var Dr={};Pi(Dr,{BRAND:()=>P3t,DIRTY:()=>e6,EMPTY_PATH:()=>s3t,INVALID:()=>bt,NEVER:()=>iEt,OK:()=>Ks,ParseStatus:()=>us,Schema:()=>Dt,ZodAny:()=>wy,ZodArray:()=>j0,ZodBigInt:()=>r6,ZodBoolean:()=>n6,ZodBranded:()=>h7,ZodCatch:()=>m6,ZodDate:()=>i6,ZodDefault:()=>f6,ZodDiscriminatedUnion:()=>YU,ZodEffects:()=>md,ZodEnum:()=>l6,ZodError:()=>oc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>XU,ZodIntersection:()=>c6,ZodIssueCode:()=>ye,ZodLazy:()=>u6,ZodLiteral:()=>d6,ZodMap:()=>h8,ZodNaN:()=>g8,ZodNativeEnum:()=>p6,ZodNever:()=>Bl,ZodNull:()=>s6,ZodNullable:()=>_f,ZodNumber:()=>t6,ZodObject:()=>sc,ZodOptional:()=>pd,ZodParsedType:()=>Be,ZodPipeline:()=>y7,ZodPromise:()=>Ey,ZodReadonly:()=>h6,ZodRecord:()=>ZU,ZodSchema:()=>Dt,ZodSet:()=>y8,ZodString:()=>vy,ZodSymbol:()=>f8,ZodTransformer:()=>md,ZodTuple:()=>bf,ZodType:()=>Dt,ZodUndefined:()=>o6,ZodUnion:()=>a6,ZodUnknown:()=>B0,ZodVoid:()=>m8,addIssueToContext:()=>Te,any:()=>yd,array:()=>ue,bigint:()=>k3t,boolean:()=>hd,coerce:()=>pu,custom:()=>xOe,date:()=>N3t,datetimeRegex:()=>EOe,defaultErrorMap:()=>k0,discriminatedUnion:()=>L3t,effect:()=>Y3t,enum:()=>gd,function:()=>V3t,getErrorMap:()=>d8,getParsedType:()=>gf,instanceof:()=>C3t,intersection:()=>z3t,isAborted:()=>GU,isAsync:()=>l8,isDirty:()=>JU,isValid:()=>_y,late:()=>O3t,lazy:()=>K3t,literal:()=>W3t,makeIssue:()=>m7,map:()=>F3t,nan:()=>R3t,nativeEnum:()=>G3t,never:()=>M3t,null:()=>b8,nullable:()=>X3t,number:()=>Or,object:()=>fe,objectUtil:()=>Hre,oboolean:()=>nEt,onumber:()=>rEt,optional:()=>Z3t,ostring:()=>tEt,pipeline:()=>eEt,preprocess:()=>Q3t,promise:()=>J3t,quotelessJson:()=>n3t,record:()=>Zt,set:()=>$3t,setErrorMap:()=>o3t,strictObject:()=>D3t,string:()=>z,symbol:()=>B3t,transformer:()=>Y3t,tuple:()=>H3t,undefined:()=>j3t,union:()=>_8,unknown:()=>U3t,util:()=>Yt,void:()=>q3t});var Yt;(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})(Yt||(Yt={}));var Hre;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Hre||(Hre={}));var Be=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gf=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=Yt.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"]),n3t=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),oc=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,Yt.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()}};oc.create=e=>new oc(e);var i3t=(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,Yt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Yt.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}"`:Yt.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,Yt.assertNever(e)}return{message:r}},k0=i3t;var gOe=k0;function o3t(e){gOe=e}function d8(){return gOe}var m7=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}},s3t=[];function Te(e,t){let r=d8(),n=m7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===k0?void 0:k0].filter(i=>!!i)});e.common.issues.push(n)}var us=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 bt;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 bt;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}}},bt=Object.freeze({status:"aborted"}),e6=e=>({status:"dirty",value:e}),Ks=e=>({status:"valid",value:e}),GU=e=>e.status==="aborted",JU=e=>e.status==="dirty",_y=e=>e.status==="valid",l8=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 fd=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}},bOe=(e,t)=>{if(_y(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 oc(e.common.issues);return this._error=r,this._error}}};function Ut(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 Dt=class{get description(){return this._def.description}_getType(t){return gf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:gf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new us,ctx:{common:t.parent.common,data:t.data,parsedType:gf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(l8(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:gf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return bOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return _y(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=>_y(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:gf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(l8(i)?i:Promise.resolve(i));return bOe(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 md({schema:this,typeName:xt.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 pd.create(this,this._def)}nullable(){return _f.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return j0.create(this)}promise(){return Ey.create(this,this._def)}or(t){return a6.create([this,t],this._def)}and(t){return c6.create(this,t,this._def)}transform(t){return new md({...Ut(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new f6({...Ut(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new h7({typeName:xt.ZodBranded,type:this,...Ut(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new m6({...Ut(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return y7.create(this,t)}readonly(){return h6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},a3t=/^c[^\s-]{8,}$/i,c3t=/^[0-9a-z]+$/,u3t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d3t=/^[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,l3t=/^[a-z0-9_-]{21}$/i,p3t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,f3t=/^[-+]?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)?)??$/,m3t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h3t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fre,y3t=/^(?:(?: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])$/,g3t=/^(?:(?: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])$/,b3t=/^(([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]))$/,_3t=/^(([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])$/,v3t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w3t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vOe="((\\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])))",E3t=new RegExp(`^${vOe}$`);function wOe(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 A3t(e){return new RegExp(`^${wOe(e)}$`)}function EOe(e){let t=`${vOe}T${wOe(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 x3t(e,t){return!!((t==="v4"||!t)&&y3t.test(e)||(t==="v6"||!t)&&b3t.test(e))}function S3t(e,t){if(!p3t.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 T3t(e,t){return!!((t==="v4"||!t)&&g3t.test(e)||(t==="v6"||!t)&&_3t.test(e))}var vy=class e extends Dt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),bt}let n=new us,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(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),Te(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?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")m3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Fre||(Fre=new RegExp(h3t,"u")),Fre.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")d3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")l3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")a3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")c3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")u3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(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),Te(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),Te(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),Te(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),Te(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),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?EOe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?E3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?A3t(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?f3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?x3t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?S3t(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?T3t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?v3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?w3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Yt.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}};vy.create=e=>new vy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...Ut(e)});function I3t(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 t6=class e extends Dt{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 Te(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),bt}let n,i=new us;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(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),Te(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),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?I3t(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(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),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Yt.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"&&Yt.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)}};t6.create=e=>new t6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...Ut(e)});var r6=class e extends Dt{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 us;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),Te(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),Te(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),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),bt}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}};r6.create=e=>new r6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...Ut(e)});var n6=class extends Dt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),bt}return Ks(t.data)}};n6.create=e=>new n6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...Ut(e)});var i6=class e extends Dt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),bt}let n=new us,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(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),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Yt.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}};i6.create=e=>new i6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...Ut(e)});var f8=class extends Dt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),bt}return Ks(t.data)}};f8.create=e=>new f8({typeName:xt.ZodSymbol,...Ut(e)});var o6=class extends Dt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),bt}return Ks(t.data)}};o6.create=e=>new o6({typeName:xt.ZodUndefined,...Ut(e)});var s6=class extends Dt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),bt}return Ks(t.data)}};s6.create=e=>new s6({typeName:xt.ZodNull,...Ut(e)});var wy=class extends Dt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ks(t.data)}};wy.create=e=>new wy({typeName:xt.ZodAny,...Ut(e)});var B0=class extends Dt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ks(t.data)}};B0.create=e=>new B0({typeName:xt.ZodUnknown,...Ut(e)});var Bl=class extends Dt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),bt}};Bl.create=e=>new Bl({typeName:xt.ZodNever,...Ut(e)});var m8=class extends Dt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),bt}return Ks(t.data)}};m8.create=e=>new m8({typeName:xt.ZodVoid,...Ut(e)});var j0=class e extends Dt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Te(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(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&&(Te(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&&(Te(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 fd(r,s,r.path,a)))).then(s=>us.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new fd(r,s,r.path,a)));return us.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)}};j0.create=(e,t)=>new j0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...Ut(t)});function p8(e){if(e instanceof sc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=pd.create(p8(n))}return new sc({...e._def,shape:()=>t})}else return e instanceof j0?new j0({...e._def,type:p8(e.element)}):e instanceof pd?pd.create(p8(e.unwrap())):e instanceof _f?_f.create(p8(e.unwrap())):e instanceof bf?bf.create(e.items.map(t=>p8(t))):e}var sc=class e extends Dt{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=Yt.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 Te(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Bl&&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 fd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Bl){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&&(Te(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 fd(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=>us.mergeObjectSync(n,u)):us.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:xt.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 Yt.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 Yt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return p8(this)}partial(t){let r={};for(let n of Yt.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 Yt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof pd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return AOe(Yt.objectKeys(this.shape))}};sc.create=(e,t)=>new sc({shape:()=>e,unknownKeys:"strip",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});sc.strictCreate=(e,t)=>new sc({shape:()=>e,unknownKeys:"strict",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});sc.lazycreate=(e,t)=>new sc({shape:e,unknownKeys:"strip",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});var a6=class extends Dt{_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 oc(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),bt}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 oc(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};a6.create=(e,t)=>new a6({options:e,typeName:xt.ZodUnion,...Ut(t)});var N0=e=>e instanceof u6?N0(e.schema):e instanceof md?N0(e.innerType()):e instanceof d6?[e.value]:e instanceof l6?e.options:e instanceof p6?Yt.objectValues(e.enum):e instanceof f6?N0(e._def.innerType):e instanceof o6?[void 0]:e instanceof s6?[null]:e instanceof pd?[void 0,...N0(e.unwrap())]:e instanceof _f?[null,...N0(e.unwrap())]:e instanceof h7||e instanceof h6?N0(e.unwrap()):e instanceof m6?N0(e._def.innerType):[],YU=class e extends Dt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Te(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),bt;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}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}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=N0(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:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ut(n)})}};function $re(e,t){let r=gf(e),n=gf(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Yt.objectKeys(t),o=Yt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=$re(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=$re(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 c6=class extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(GU(o)||GU(s))return bt;let a=$re(o.value,s.value);return a.valid?((JU(o)||JU(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),bt)};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}))}};c6.create=(e,t,r)=>new c6({left:e,right:t,typeName:xt.ZodIntersection,...Ut(r)});var bf=class e extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Te(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(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 fd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>us.mergeArray(r,s)):us.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};bf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bf({items:e,typeName:xt.ZodTuple,rest:null,...Ut(t)})};var ZU=class e extends Dt{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 Te(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new fd(n,a,n.path,a)),value:s._parse(new fd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?us.mergeObjectAsync(r,i):us.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Dt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...Ut(n)}):new e({keyType:vy.create(),valueType:t,typeName:xt.ZodRecord,...Ut(r)})}},h8=class extends Dt{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 Te(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new fd(n,a,n.path,[u,"key"])),value:o._parse(new fd(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 bt;(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 bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};h8.create=(e,t,r)=>new h8({valueType:t,keyType:e,typeName:xt.ZodMap,...Ut(r)});var y8=class e extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Te(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(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&&(Te(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 bt;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 fd(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)}};y8.create=(e,t)=>new y8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...Ut(t)});var XU=class e extends Dt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Te(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),bt;function n(a,c){return m7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,d8(),k0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return m7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,d8(),k0].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 Ey){let a=this;return Ks(async function(...c){let u=new oc([]),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 Ks(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new oc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new oc([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:bf.create(t).rest(B0.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||bf.create([]).rest(B0.create()),returns:r||B0.create(),typeName:xt.ZodFunction,...Ut(n)})}},u6=class extends Dt{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})}};u6.create=(e,t)=>new u6({getter:e,typeName:xt.ZodLazy,...Ut(t)});var d6=class extends Dt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};d6.create=(e,t)=>new d6({value:e,typeName:xt.ZodLiteral,...Ut(t)});function AOe(e,t){return new l6({values:e,typeName:xt.ZodEnum,...Ut(t)})}var l6=class e extends Dt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}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 Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Ks(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})}};l6.create=AOe;var p6=class extends Dt{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Yt.objectValues(r);return Te(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Ks(t.data)}get enum(){return this._def.values}};p6.create=(e,t)=>new p6({values:e,typeName:xt.ZodNativeEnum,...Ut(t)});var Ey=class extends Dt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),bt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ks(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ey.create=(e,t)=>new Ey({type:e,typeName:xt.ZodPromise,...Ut(t)});var md=class extends Dt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.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=>{Te(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 bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?e6(c.value):r.value==="dirty"?e6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?e6(a.value):r.value==="dirty"?e6(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"?bt:(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"?bt:(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(!_y(s))return bt;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=>_y(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Yt.assertNever(i)}};md.create=(e,t,r)=>new md({schema:e,typeName:xt.ZodEffects,effect:t,...Ut(r)});md.createWithPreprocess=(e,t,r)=>new md({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...Ut(r)});var pd=class extends Dt{_parse(t){return this._getType(t)===Be.undefined?Ks(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pd.create=(e,t)=>new pd({innerType:e,typeName:xt.ZodOptional,...Ut(t)});var _f=class extends Dt{_parse(t){return this._getType(t)===Be.null?Ks(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_f.create=(e,t)=>new _f({innerType:e,typeName:xt.ZodNullable,...Ut(t)});var f6=class extends Dt{_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}};f6.create=(e,t)=>new f6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ut(t)});var m6=class extends Dt{_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 l8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new oc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new oc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};m6.create=(e,t)=>new m6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ut(t)});var g8=class extends Dt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};g8.create=e=>new g8({typeName:xt.ZodNaN,...Ut(e)});var P3t=Symbol("zod_brand"),h7=class extends Dt{_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}},y7=class e extends Dt{_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"?bt:o.status==="dirty"?(r.dirty(),e6(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"?bt: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:xt.ZodPipeline})}},h6=class extends Dt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(_y(i)&&(i.value=Object.freeze(i.value)),i);return l8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};h6.create=(e,t)=>new h6({innerType:e,typeName:xt.ZodReadonly,...Ut(t)});function _Oe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function xOe(e,t={},r){return e?wy.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=_Oe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=_Oe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):wy.create()}var O3t={object:sc.lazycreate},xt;(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"})(xt||(xt={}));var C3t=(e,t={message:`Input not instance of ${e.name}`})=>xOe(r=>r instanceof e,t),z=vy.create,Or=t6.create,R3t=g8.create,k3t=r6.create,hd=n6.create,N3t=i6.create,B3t=f8.create,j3t=o6.create,b8=s6.create,yd=wy.create,U3t=B0.create,M3t=Bl.create,q3t=m8.create,ue=j0.create,fe=sc.create,D3t=sc.strictCreate,_8=a6.create,L3t=YU.create,z3t=c6.create,H3t=bf.create,Zt=ZU.create,F3t=h8.create,$3t=y8.create,V3t=XU.create,K3t=u6.create,W3t=d6.create,gd=l6.create,G3t=p6.create,J3t=Ey.create,Y3t=md.create,Z3t=pd.create,X3t=_f.create,Q3t=md.createWithPreprocess,eEt=y7.create,tEt=()=>z().optional(),rEt=()=>Or().optional(),nEt=()=>hd().optional(),pu={string:(e=>vy.create({...e,coerce:!0})),number:(e=>t6.create({...e,coerce:!0})),boolean:(e=>n6.create({...e,coerce:!0})),bigint:(e=>r6.create({...e,coerce:!0})),date:(e=>i6.create({...e,coerce:!0}))};var iEt=bt;var sEt=gd(["enc","sig"]),aEt=gd(["markdown","plain"]),cEt=gd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),uEt=gd(["error","info","warning"]),E8=gd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),dEt=gd(["completed","failed","pending"]),lEt=gd(["digital","pickup","shipping"]),pEt=gd(["fulfilled","partial","processing","removed"]),fEt=gd(["across","each"]),Vre=gd(["pickup","shipping"]),mEt=fe({config:Zt(z(),yd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),hEt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:sEt.optional(),x:z().optional(),y:z().optional()}),yEt=fe({config:Zt(z(),yd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),gEt=fe({endpoint:z()}),bEt=fe({schema:z()}),SOe=fe({endpoint:z(),schema:z()}),_Et=SOe,vEt=SOe,Aa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),po=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),Kre=po,TOe=fe({id:z()}),wEt=TOe,EEt=TOe,g7=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),QU=fe({type:z()}),Vi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),Wre=Vi,IOe=fe({id:z(),image_url:z().optional(),price:Or(),title:z()}),eM=fe({amount:Or(),display_text:z().optional(),type:z()}),Ay=fe({title:z().optional(),type:z(),url:z()}),U0=fe({code:z().optional(),content:z(),content_type:aEt.optional(),path:z().optional(),severity:cEt.optional(),type:uEt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Gre=U0,A8=fe({id:z(),label:z().optional(),permalink_url:z()}),AEt=fe({amount:Or(),display_text:z()}),xEt=fe({config:Zt(z(),yd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Jre=fe({id:z(),quantity:Or()}),SEt=Jre,TEt=Jre,IEt=Jre,PEt=fe({fulfilled:Or(),original:Or().optional(),total:Or()}),OEt=fe({billing_address:g7.optional(),credential:QU.optional(),display:Zt(z(),yd()).optional(),handler_id:z(),id:z(),type:z()}),CEt=fe({checkout_mandate:z()}),REt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),kEt=fe({analytics:hd().optional(),marketing:hd().optional(),preferences:hd().optional(),sale_of_data:hd().optional()});var NEt=kEt;var POe=fe({codes:ue(z()).optional()}),BEt=POe,jEt=fe({amount:Or(),path:z()}),UEt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:g7.optional(),name:z().optional()}),MEt=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:pu.date().optional(),id:z(),latest_fulfillment_time:pu.date().optional(),title:z(),totals:ue(eM)}),qEt=fe({description:z().optional(),fulfillable_on:_8([b8(),z()]).optional(),line_item_ids:ue(z()),type:Vre}),DEt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:g7.optional(),name:z().optional()}),LEt=fe({max:Or().optional(),min:Or().optional()}),b7=fe({taxonomy:z().optional(),value:z()}),_7=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),v8=fe({amount:Or(),currency:z()}),v7=fe({alt_text:z().optional(),height:Or().optional(),type:z(),url:z(),width:Or().optional()}),zEt=fe({id:z().optional(),label:z()}),w7=fe({count:Or().optional(),scale_max:Or(),scale_min:Or().optional(),value:Or()}),OOe=fe({available:hd().optional(),status:z().optional()}),HEt=OOe,COe=fe({type:z(),value:z()}),FEt=COe,$Et=fe({id:z(),match:z().optional()}),Yre=fe({id:z().optional(),label:z(),name:z()}),ROe=Yre,kOe=fe({links:ue(Ay).optional(),name:z().optional()}),VEt=kOe,NOe=fe({unit:z(),value:Or()});var KEt=NOe,WEt=fe({cursor:z().optional(),limit:Or().optional()}),GEt=fe({cursor:z().optional(),has_next_page:hd(),total_count:Or().optional()}),JEt=fe({handlers:ue(mEt).optional()}),YEt=fe({a2a:gEt.optional(),embedded:bEt.optional(),mcp:_Et.optional(),rest:vEt.optional(),spec:z(),version:z()}),x8=fe({item:wEt,quantity:Or()}),ZEt=fe({billing_address:g7.optional(),credential:QU.optional(),display:Zt(z(),yd()).optional(),handler_id:z(),id:z(),type:z(),selected:hd().optional()}),E7=fe({id:z().optional(),item:EEt,parent_id:z().optional(),quantity:Or()}),tM=fe({instruments:ue(ZEt).optional()}),XEt=tM,A7=tM,S8=tM,rM=tM,y6=fe({id:z(),item:IOe,parent_id:z().optional(),quantity:Or(),totals:ue(eM)}),xy=fe({amount:Or(),display_text:z().optional(),type:z(),lines:ue(AEt).optional()}),jl=fe({capabilities:Zt(z(),ue(xEt)),version:z()}),QEt=fe({description:z().optional(),id:z(),line_items:ue(SEt).optional(),occurred_at:pu.date(),status:dEt,totals:ue(eM).optional(),type:z()}),eAt=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(TEt),occurred_at:pu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),tAt=fe({description:z().optional(),destination:g7,fulfillable_on:z().optional(),id:z(),line_items:ue(IEt),method_type:lEt}),rAt=fe({id:z(),item:IOe,parent_id:z().optional(),quantity:PEt,status:pEt,totals:ue(eM)}),lUr=fe({payment_data:OEt}),pUr=fe({ap2:CEt.optional()}),fUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,ap2:REt.optional()}),Zre=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:NEt.optional()}),nAt=Zre,iAt=Zre,BOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional(),discounts:BEt.optional()}),oAt=fe({allocations:ue(jEt).optional(),amount:Or(),automatic:hd().optional(),code:z().optional(),eligibility:z().optional(),method:fEt.optional(),priority:Or().optional(),provisional:hd().optional(),title:z()}),jOe=fe({id:z(),line_item_ids:ue(z()),options:ue(MEt).optional(),selected_option_id:_8([b8(),z()]).optional()}),sAt=fe({destinations:ue(DEt).optional(),groups:ue(jOe).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:_8([b8(),z()]).optional(),type:Vre}),mUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),signals:Vi.optional()}),hUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),id:z(),line_items:ue(E7),signals:Vi.optional()}),yUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay).optional(),messages:ue(U0).optional(),signals:Vi.optional(),totals:ue(xy),ucp:jl}),aAt=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional()}),UOe=aAt,gUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,cart_id:z().optional()}),Xre=fe({categories:ue(z()).optional(),price:LEt.optional()}),w8=fe({max:v8,min:v8}),Qre=fe({name:z(),values:ue(zEt)}),MOe=fe({amount:Or(),currency:z(),measure:NOe,reference:KEt}),cAt=MOe,bUr=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(ROe).optional(),signals:Wre.optional()}),_Ur=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),pagination:WEt.optional(),query:z().optional(),signals:Wre.optional()}),uAt=fe({capabilities:ue(yEt),services:Zt(z(),YEt),version:z()}),vUr=fe({attribution:Zt(z(),z()).optional(),payment:XEt,signals:Vi.optional()}),qOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl}),dAt=fe({events:ue(eAt).optional(),expectations:ue(tAt).optional()}),DOe=fe({attribution:Zt(z(),z()).optional(),buyer:Zre.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional()}),LOe=fe({attribution:Zt(z(),z()).optional(),buyer:iAt.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional()}),zOe=fe({attribution:Zt(z(),z()).optional(),buyer:nAt.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl}),HOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),discounts:POe.optional()}),lAt=fe({applied:ue(oAt).optional(),codes:ue(z()).optional()}),pAt=fe({destinations:ue(UEt).optional(),groups:ue(jOe).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:_8([b8(),z()]).optional(),type:Vre}),fAt=fe({available_methods:ue(qEt).optional(),methods:ue(sAt).optional()}),FOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),cart_id:z().optional()}),wUr=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),ids:ue(z()),signals:Wre.optional()}),mAt=fe({availability:OOe.optional(),barcodes:ue(COe).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price:v8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Yre).optional(),price:v8,rating:w7.optional(),seller:kOe.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:MOe.optional(),url:z().optional(),inputs:ue($Et)}),$Oe=fe({availability:HEt.optional(),barcodes:ue(FEt).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price:v8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Yre).optional(),price:v8,rating:w7.optional(),seller:VEt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:cAt.optional(),url:z().optional()}),hAt=fe({categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Qre).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue($Oe)}),EUr=fe({payment:JEt.optional(),signing_keys:ue(hEt).optional(),ucp:uAt}),VOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional()}),yAt=fe({adjustments:ue(QEt).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:dAt,id:z(),label:z().optional(),line_items:ue(rAt),messages:ue(U0).optional(),permalink_url:z(),totals:ue(xy),ucp:jl}),KOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,discounts:lAt.optional()}),WOe=fe({methods:ue(pAt).optional()}),GOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional(),fulfillment:WOe.optional()}),JOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,fulfillment:fAt.optional()}),gAt=fe({categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Qre).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mAt)}),bAt=fe({options:ue(Qre).optional(),selected:ue(ROe).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue($Oe)}),AUr=fe({messages:ue(Gre).optional(),pagination:GEt.optional(),products:ue(hAt),ucp:jl}),YOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),fulfillment:WOe.optional()}),xUr=fe({messages:ue(Gre).optional(),products:ue(gAt),ucp:jl}),SUr=fe({messages:ue(Gre).optional(),product:bAt,ucp:jl});var OUr=QU.extend({token:Dr.string().optional()}),_At=Dr.object({webhook_url:Dr.string().url().optional()}),ZOe=qOe.extend(JOe.pick({fulfillment:!0}).shape).extend(KOe.pick({discounts:!0}).shape).extend(zOe.pick({buyer:!0}).shape).extend({platform:_At.optional()}),XOe=VOe.extend(YOe.pick({fulfillment:!0}).shape).extend(HOe.pick({discounts:!0}).shape).extend(DOe.pick({buyer:!0}).shape).extend(FOe.pick({cart_id:!0}).shape),QOe=UOe.extend(GOe.pick({fulfillment:!0}).shape).extend(BOe.pick({discounts:!0}).shape).extend(LOe.pick({buyer:!0}).shape);ud();async function nM(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 iM(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 vAt=3e4,eCe=2*1024*1024,Ul=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function tCe(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 rCe(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"?XOe:QOe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function wAt(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 nCe(e,t,r,n){try{e[t](r,n)}catch{}}function EAt(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 oM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=tCe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=tCe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??vAt,this.boundaryLogger=t.logger??Me}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:rCe(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:rCe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=iM(this.timeoutMs,this.signal),o=(0,iCe.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 nM(u,eCe,"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 Ul(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>eCe)throw new Ul("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Ul("UCP MCP response is not valid JSON",void 0,u.status)}if(!wAt(l))throw new Ul("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Ul("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Ul(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Ul(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Ul("UCP MCP response is missing result.structuredContent");if(!ZOe.safeParse(EAt(p.structuredContent)).success)throw new Ul("UCP checkout response failed schema validation");return nCe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw nCe(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 sCe=require("node:crypto");ud();var aM="2026-04-08",AAt="dev.ucp.shopping",xAt="dev.ucp.shopping.checkout",SAt=1024*1024,TAt=1e4,IAt="https://ucp.dev",x7=Dr.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"),PAt=Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:x7,schema:x7,transport:Dr.enum(["rest","mcp","a2a","embedded"]),endpoint:x7.optional()}).passthrough(),OAt=Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:x7,schema:x7,extends:Dr.union([Dr.string(),Dr.array(Dr.string()).min(1)]).optional()}).passthrough(),CAt=Dr.object({ucp:Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Dr.record(Dr.array(PAt)),capabilities:Dr.record(Dr.array(OAt)),payment_handlers:Dr.record(Dr.array(Dr.unknown())).optional()}).passthrough(),signing_keys:Dr.array(Dr.unknown()).optional()}).passthrough();function RAt(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 sM(e,t){if(new URL(e).origin!==IAt)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function oCe(e,t,r,n){try{e[t](r,n)}catch{}}async function kAt(e,t={}){let r=RAt(e,"UCP business URL"),n=iM(t.timeoutMs??TAt,t.signal),i=t.logger??Me,o=(0,sCe.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 nM(c,SAt,"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=CAt.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return oCe(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 oCe(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 NAt(e){if(e.ucp.version!==aM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[xAt]?.find(i=>i.version===aM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");sM(t.spec,"Checkout capability spec"),sM(t.schema,"Checkout capability schema");let r=e.ucp.services[AAt]?.find(i=>i.version===aM&&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");sM(r.spec,"Shopping service spec"),sM(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 aCe(e,t={}){let r=await kAt(e,t);return{...r,endpoint:NAt(r.profile),version:aM}}var BAt="https://app.visacli.sh/.well-known/ucp";function jAt(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 UAt(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 ene(e,t=new Set){if(Array.isArray(e))for(let r of e)ene(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?UAt(n,t):ene(n,t);return t}function MAt(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=ene(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 qAt(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 DAt(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 uCe(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??aCe)(e.business),i=await(t.getCheckout??(async(u,d)=>await new oM({endpoint:u.endpoint,platformProfileUrl:jAt(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??BAt)}).getCheckout(d)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");let o=String(i.status??"unknown");if(o==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_already_completed"};if(o!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_not_escalated"};if(typeof i.continue_url!="string"||!i.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"missing_continue_url"};let s=qAt(i),a=MAt(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,cCe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,o,s.currency,String(s.minor),a.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:c,checkoutStatus:"requires_escalation",amount:s,merchant:{businessOrigin:r.businessOrigin,sourceHost:a.sourceHost,targetHost:a.targetHost,originRewritten:a.originRewritten},payMerchantRequest:{action:"review",url:a.url,amount:s.decimal,currency:s.currency},messages:DAt(i),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>."}}I_();function tne(){return du()}var Nl=new rf(()=>ei.getSessionToken()),LAt="4.1.0-rc.41",uMr=["","","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(`
|
|
20921
|
+
If building from source, run native/build-win.bat first.`);en.mkdirSync(ny,{recursive:!0}),en.copyFileSync(e,b0);let t=Pj(b0);return en.writeFileSync($Se,t,{mode:384}),en.writeFileSync(FSe,HSe,{mode:384}),b0}async function Z6t(){return q4()?Rj():QSe()}var Oj="visa-cli",Cj="attestation-key";async function X6t(e){if(!await tf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await _0("security",["delete-generic-password","-s",Oj,"-a",Cj],{timeout:5e3})}catch{}try{await _0("security",["add-generic-password","-s",Oj,"-a",Cj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${Q6t(t)}).`)}}function Q6t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function evt(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(i)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function tvt(){if(!await tf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await _0("security",["find-generic-password","-s",Oj,"-a",Cj,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:evt(e)}}}async function rvt(){let e=await tvt();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function tTe(e){let t=await Z6t(),r;try{r=(await _0(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 Y6t(r)}var WSe=!1;function nvt(){if(!q4())return!1;try{return en.existsSync(b0)||eTe()!==null?!0:(WSe||(WSe=!0,Me.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:b0,searchedPrebuiltPaths:XSe})),!1)}catch{return!1}}function v0(){return hT()||J6t()?!0:q4()?nvt():!1}async function rTe(){if(q4()){let i=await Rj(),{stdout:o}=await _0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await tTe(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let r=e.slice(0,t),n=e.slice(t+1);return await X6t(r),n}async function kee(e,t,r={}){if(hT())return Promise.resolve(Axe());let n=r.timeoutMs??G6t;if(q4()){let a=await Rj(),c=["sign",e];t&&c.push(t);let u;try{u=(await _0(a,c,{timeout:n})).stdout}catch(l){throw VSe(l)?KSe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await rvt();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await QSe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,Ree.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):VSe(d)?c(KSe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function kj(){if(q4()){try{let e=await Rj();await _0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await tf())try{await _0("security",["delete-generic-password","-s",Oj,"-a",Cj],{timeout:5e3})}catch{}try{await tTe(["delete-key"])}catch{}}Qh();ud();sj();_U();n8();var lCe=require("child_process"),cM=_e(require("fs")),uM=_e(require("os")),pCe=_e(require("path"));I_();ZB();var VPe="4.1.0-rc.42";function Nre(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function q8t(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=Iee(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function a8(e){return e==null?"\u2014":e?"yes":"no"}async function c7(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=Tee("auth.serverUrl"),s=du(),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:a8(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=q8t("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:a8(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=ty(),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:a8(!u),source:d}),n.push({key:"client.version",value:VPe,formatted:VPe,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=Yh();n.push({key:"dev.mockKeychain",value:p,formatted:a8(p),source:Nre("VISA_MOCK_KEYCHAIN",!!l),hint:ZQ()});let f=process.env.VISA_MOCK_TOUCHID,m=hT();n.push({key:"dev.mockTouchid",value:m,formatted:a8(m),source:Nre("VISA_MOCK_TOUCHID",!!f),hint:ZQ()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:a8(!!h),source:Nre("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}function D8t(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function KPe(e,t={}){if(e.length===0)return"";let r=Math.max(...e.map(o=>o.key.length)),n=Math.max(...e.map(o=>o.formatted.length)),i=[];for(let o of e){let s=o.key.padEnd(r+2),a=o.formatted.padEnd(n+2);i.push(`${s}${a}(${D8t(o.source)})`),t.verbose&&o.hint&&i.push(` ${"\u21B3".padStart(r)} ${o.hint}`)}return i.join(`
|
|
20922
|
+
`)}function WPe(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var Lre=require("node:os"),l7=require("node:path"),p7=require("node:fs/promises"),iOe=require("node:fs"),oOe=require("node:url"),sOe=require("node:crypto");ud();var L8t=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function c8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!L8t.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var R0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function GPe(e){let t;try{t=new URL(e)}catch{throw new R0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new R0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}ud();var z8t={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},H8t=300*1e3,Bre={},JPe=0,u7=null;function F8t(){return u7||(u7=(async()=>{try{let e=await Nl.getFeatureFlags();Bre=e&&e.flags||{},JPe=Date.now()}catch(e){Bre={},Me.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{u7=null}})(),u7)}async function FU(){Date.now()-JPe<H8t||await F8t()}function u8(e){let t=z8t[e];return t?Bre[t]!==!0:!1}var YPe=require("node:crypto"),d7=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},$U=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 d7(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??YPe.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 aOe(e){return[(0,l7.join)(e,"checkout-engine","index.js"),(0,l7.join)(e,"..","checkout-engine","index.js")]}function Q8t(e,t=iOe.existsSync){return aOe(e).find(r=>t(r))??null}var KU=null,cOe=async()=>{if(KU)return KU;let e=Q8t(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${aOe(__dirname).join(" and ")}).`);return KU=(await import((0,oOe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await e3t(),cardMandateRegister:await t3t()}),KU};async function e3t(){let e=await Promise.resolve().then(()=>(qre(),Mre));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function t3t(){let e=await Promise.resolve().then(()=>(qre(),Mre));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function zre(){return u8("pay_merchant")?(await FU(),u8("pay_merchant")):!1}var uOe=(0,l7.join)((0,Lre.homedir)(),".visa-mcp","agent-credential.json"),dOe=(0,l7.join)((0,Lre.homedir)(),".visa-mcp","contact.json"),lOe=new $U;function f7(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var r3t=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function pOe(e){return r3t.has(e)?e:null}async function WU(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?f7(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:pOe(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){Me.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function nOe(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?f7(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:pOe(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){Me.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function Dre(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new R0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function fOe(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=f7(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 mOe(e={},t={}){if(await(t.flagDisabled??zre)())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??lOe).get(n);return o?fOe(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 hOe(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:Pee()&&!process.env.VISA_VERIFY_WEB_URL?null:P_();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??zre)())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??lOe,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=GPe(e.url??"").toString(),c=Dre(e.amount)}catch(I){if(I instanceof R0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??uOe,l=t.contactPath??dOe;try{await(0,p7.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,p7.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 I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);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??cOe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);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 I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>Nl.emitTelemetry(I)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Me.info("pay_merchant:review",{host:_,currency:u});let I;try{I=await y.review(v)}catch(T){throw await WU({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 WU({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${c8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{Me.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,...I?{onApprovalUrl:I}:{}})}catch(U){throw await WU({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:U instanceof Error?U.message:String(U),startedAt:A,submit:m}),U}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",j=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await WU({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:j,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=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:j,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)"}.${M}`: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.${M}`:`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 I=(0,sOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Me.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async O=>{try{let j=await S(M=>{Me.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(M)});return Me.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:j.success===!0}),j}catch(j){throw Me.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:f7(j instanceof Error?j.message:String(j))}),j}}});return fOe(T,"authorize")}catch(T){if(T instanceof d7)return Me.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 yOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:P_();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??zre)())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=Dre(e.ceiling)}catch(_){if(_ instanceof R0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=Dre(e.perTransaction)}catch(_){if(_ instanceof R0)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??uOe,u=t.contactPath??dOe;try{await(0,p7.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,p7.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??cOe,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??(_=>Nl.emitTelemetry(_)),y=Date.now();Me.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?f7(_.message):String(_);return Me.warn("start_card_mandate:failed",{message:w}),await nOe({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&&Me.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await nOe({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 ${c8(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 cCe=require("node:crypto");var iCe=require("node:crypto");var Dr={};Pi(Dr,{BRAND:()=>P3t,DIRTY:()=>e6,EMPTY_PATH:()=>s3t,INVALID:()=>bt,NEVER:()=>iEt,OK:()=>Ks,ParseStatus:()=>us,Schema:()=>Dt,ZodAny:()=>wy,ZodArray:()=>j0,ZodBigInt:()=>r6,ZodBoolean:()=>n6,ZodBranded:()=>h7,ZodCatch:()=>m6,ZodDate:()=>i6,ZodDefault:()=>f6,ZodDiscriminatedUnion:()=>YU,ZodEffects:()=>md,ZodEnum:()=>l6,ZodError:()=>oc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>XU,ZodIntersection:()=>c6,ZodIssueCode:()=>ye,ZodLazy:()=>u6,ZodLiteral:()=>d6,ZodMap:()=>h8,ZodNaN:()=>g8,ZodNativeEnum:()=>p6,ZodNever:()=>Bl,ZodNull:()=>s6,ZodNullable:()=>_f,ZodNumber:()=>t6,ZodObject:()=>sc,ZodOptional:()=>pd,ZodParsedType:()=>Be,ZodPipeline:()=>y7,ZodPromise:()=>Ey,ZodReadonly:()=>h6,ZodRecord:()=>ZU,ZodSchema:()=>Dt,ZodSet:()=>y8,ZodString:()=>vy,ZodSymbol:()=>f8,ZodTransformer:()=>md,ZodTuple:()=>bf,ZodType:()=>Dt,ZodUndefined:()=>o6,ZodUnion:()=>a6,ZodUnknown:()=>B0,ZodVoid:()=>m8,addIssueToContext:()=>Te,any:()=>yd,array:()=>ue,bigint:()=>k3t,boolean:()=>hd,coerce:()=>pu,custom:()=>xOe,date:()=>N3t,datetimeRegex:()=>EOe,defaultErrorMap:()=>k0,discriminatedUnion:()=>L3t,effect:()=>Y3t,enum:()=>gd,function:()=>V3t,getErrorMap:()=>d8,getParsedType:()=>gf,instanceof:()=>C3t,intersection:()=>z3t,isAborted:()=>GU,isAsync:()=>l8,isDirty:()=>JU,isValid:()=>_y,late:()=>O3t,lazy:()=>K3t,literal:()=>W3t,makeIssue:()=>m7,map:()=>F3t,nan:()=>R3t,nativeEnum:()=>G3t,never:()=>M3t,null:()=>b8,nullable:()=>X3t,number:()=>Or,object:()=>fe,objectUtil:()=>Hre,oboolean:()=>nEt,onumber:()=>rEt,optional:()=>Z3t,ostring:()=>tEt,pipeline:()=>eEt,preprocess:()=>Q3t,promise:()=>J3t,quotelessJson:()=>n3t,record:()=>Zt,set:()=>$3t,setErrorMap:()=>o3t,strictObject:()=>D3t,string:()=>z,symbol:()=>B3t,transformer:()=>Y3t,tuple:()=>H3t,undefined:()=>j3t,union:()=>_8,unknown:()=>U3t,util:()=>Yt,void:()=>q3t});var Yt;(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})(Yt||(Yt={}));var Hre;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Hre||(Hre={}));var Be=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gf=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=Yt.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"]),n3t=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),oc=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,Yt.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()}};oc.create=e=>new oc(e);var i3t=(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,Yt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Yt.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}"`:Yt.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,Yt.assertNever(e)}return{message:r}},k0=i3t;var gOe=k0;function o3t(e){gOe=e}function d8(){return gOe}var m7=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}},s3t=[];function Te(e,t){let r=d8(),n=m7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===k0?void 0:k0].filter(i=>!!i)});e.common.issues.push(n)}var us=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 bt;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 bt;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}}},bt=Object.freeze({status:"aborted"}),e6=e=>({status:"dirty",value:e}),Ks=e=>({status:"valid",value:e}),GU=e=>e.status==="aborted",JU=e=>e.status==="dirty",_y=e=>e.status==="valid",l8=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 fd=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}},bOe=(e,t)=>{if(_y(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 oc(e.common.issues);return this._error=r,this._error}}};function Ut(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 Dt=class{get description(){return this._def.description}_getType(t){return gf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:gf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new us,ctx:{common:t.parent.common,data:t.data,parsedType:gf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(l8(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:gf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return bOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return _y(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=>_y(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:gf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(l8(i)?i:Promise.resolve(i));return bOe(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 md({schema:this,typeName:xt.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 pd.create(this,this._def)}nullable(){return _f.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return j0.create(this)}promise(){return Ey.create(this,this._def)}or(t){return a6.create([this,t],this._def)}and(t){return c6.create(this,t,this._def)}transform(t){return new md({...Ut(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new f6({...Ut(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new h7({typeName:xt.ZodBranded,type:this,...Ut(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new m6({...Ut(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return y7.create(this,t)}readonly(){return h6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},a3t=/^c[^\s-]{8,}$/i,c3t=/^[0-9a-z]+$/,u3t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d3t=/^[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,l3t=/^[a-z0-9_-]{21}$/i,p3t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,f3t=/^[-+]?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)?)??$/,m3t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h3t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fre,y3t=/^(?:(?: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])$/,g3t=/^(?:(?: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])$/,b3t=/^(([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]))$/,_3t=/^(([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])$/,v3t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w3t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vOe="((\\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])))",E3t=new RegExp(`^${vOe}$`);function wOe(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 A3t(e){return new RegExp(`^${wOe(e)}$`)}function EOe(e){let t=`${vOe}T${wOe(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 x3t(e,t){return!!((t==="v4"||!t)&&y3t.test(e)||(t==="v6"||!t)&&b3t.test(e))}function S3t(e,t){if(!p3t.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 T3t(e,t){return!!((t==="v4"||!t)&&g3t.test(e)||(t==="v6"||!t)&&_3t.test(e))}var vy=class e extends Dt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),bt}let n=new us,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(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),Te(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?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")m3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Fre||(Fre=new RegExp(h3t,"u")),Fre.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")d3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")l3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")a3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")c3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")u3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(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),Te(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),Te(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),Te(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),Te(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),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?EOe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?E3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?A3t(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?f3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?x3t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?S3t(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?T3t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?v3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?w3t.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Yt.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}};vy.create=e=>new vy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...Ut(e)});function I3t(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 t6=class e extends Dt{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 Te(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),bt}let n,i=new us;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(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),Te(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),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?I3t(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(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),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Yt.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"&&Yt.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)}};t6.create=e=>new t6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...Ut(e)});var r6=class e extends Dt{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 us;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),Te(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),Te(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),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),bt}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}};r6.create=e=>new r6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...Ut(e)});var n6=class extends Dt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),bt}return Ks(t.data)}};n6.create=e=>new n6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...Ut(e)});var i6=class e extends Dt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),bt}let n=new us,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(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),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Yt.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}};i6.create=e=>new i6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...Ut(e)});var f8=class extends Dt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),bt}return Ks(t.data)}};f8.create=e=>new f8({typeName:xt.ZodSymbol,...Ut(e)});var o6=class extends Dt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),bt}return Ks(t.data)}};o6.create=e=>new o6({typeName:xt.ZodUndefined,...Ut(e)});var s6=class extends Dt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),bt}return Ks(t.data)}};s6.create=e=>new s6({typeName:xt.ZodNull,...Ut(e)});var wy=class extends Dt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ks(t.data)}};wy.create=e=>new wy({typeName:xt.ZodAny,...Ut(e)});var B0=class extends Dt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ks(t.data)}};B0.create=e=>new B0({typeName:xt.ZodUnknown,...Ut(e)});var Bl=class extends Dt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),bt}};Bl.create=e=>new Bl({typeName:xt.ZodNever,...Ut(e)});var m8=class extends Dt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),bt}return Ks(t.data)}};m8.create=e=>new m8({typeName:xt.ZodVoid,...Ut(e)});var j0=class e extends Dt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Te(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(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&&(Te(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&&(Te(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 fd(r,s,r.path,a)))).then(s=>us.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new fd(r,s,r.path,a)));return us.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)}};j0.create=(e,t)=>new j0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...Ut(t)});function p8(e){if(e instanceof sc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=pd.create(p8(n))}return new sc({...e._def,shape:()=>t})}else return e instanceof j0?new j0({...e._def,type:p8(e.element)}):e instanceof pd?pd.create(p8(e.unwrap())):e instanceof _f?_f.create(p8(e.unwrap())):e instanceof bf?bf.create(e.items.map(t=>p8(t))):e}var sc=class e extends Dt{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=Yt.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 Te(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Bl&&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 fd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Bl){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&&(Te(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 fd(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=>us.mergeObjectSync(n,u)):us.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:xt.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 Yt.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 Yt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return p8(this)}partial(t){let r={};for(let n of Yt.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 Yt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof pd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return AOe(Yt.objectKeys(this.shape))}};sc.create=(e,t)=>new sc({shape:()=>e,unknownKeys:"strip",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});sc.strictCreate=(e,t)=>new sc({shape:()=>e,unknownKeys:"strict",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});sc.lazycreate=(e,t)=>new sc({shape:e,unknownKeys:"strip",catchall:Bl.create(),typeName:xt.ZodObject,...Ut(t)});var a6=class extends Dt{_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 oc(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),bt}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 oc(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};a6.create=(e,t)=>new a6({options:e,typeName:xt.ZodUnion,...Ut(t)});var N0=e=>e instanceof u6?N0(e.schema):e instanceof md?N0(e.innerType()):e instanceof d6?[e.value]:e instanceof l6?e.options:e instanceof p6?Yt.objectValues(e.enum):e instanceof f6?N0(e._def.innerType):e instanceof o6?[void 0]:e instanceof s6?[null]:e instanceof pd?[void 0,...N0(e.unwrap())]:e instanceof _f?[null,...N0(e.unwrap())]:e instanceof h7||e instanceof h6?N0(e.unwrap()):e instanceof m6?N0(e._def.innerType):[],YU=class e extends Dt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Te(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),bt;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}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}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=N0(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:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ut(n)})}};function $re(e,t){let r=gf(e),n=gf(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Yt.objectKeys(t),o=Yt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=$re(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=$re(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 c6=class extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(GU(o)||GU(s))return bt;let a=$re(o.value,s.value);return a.valid?((JU(o)||JU(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),bt)};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}))}};c6.create=(e,t,r)=>new c6({left:e,right:t,typeName:xt.ZodIntersection,...Ut(r)});var bf=class e extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Te(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(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 fd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>us.mergeArray(r,s)):us.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};bf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bf({items:e,typeName:xt.ZodTuple,rest:null,...Ut(t)})};var ZU=class e extends Dt{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 Te(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new fd(n,a,n.path,a)),value:s._parse(new fd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?us.mergeObjectAsync(r,i):us.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Dt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...Ut(n)}):new e({keyType:vy.create(),valueType:t,typeName:xt.ZodRecord,...Ut(r)})}},h8=class extends Dt{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 Te(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new fd(n,a,n.path,[u,"key"])),value:o._parse(new fd(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 bt;(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 bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};h8.create=(e,t,r)=>new h8({valueType:t,keyType:e,typeName:xt.ZodMap,...Ut(r)});var y8=class e extends Dt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Te(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(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&&(Te(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 bt;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 fd(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)}};y8.create=(e,t)=>new y8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...Ut(t)});var XU=class e extends Dt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Te(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),bt;function n(a,c){return m7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,d8(),k0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return m7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,d8(),k0].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 Ey){let a=this;return Ks(async function(...c){let u=new oc([]),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 Ks(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new oc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new oc([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:bf.create(t).rest(B0.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||bf.create([]).rest(B0.create()),returns:r||B0.create(),typeName:xt.ZodFunction,...Ut(n)})}},u6=class extends Dt{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})}};u6.create=(e,t)=>new u6({getter:e,typeName:xt.ZodLazy,...Ut(t)});var d6=class extends Dt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};d6.create=(e,t)=>new d6({value:e,typeName:xt.ZodLiteral,...Ut(t)});function AOe(e,t){return new l6({values:e,typeName:xt.ZodEnum,...Ut(t)})}var l6=class e extends Dt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}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 Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Ks(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})}};l6.create=AOe;var p6=class extends Dt{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Yt.objectValues(r);return Te(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Ks(t.data)}get enum(){return this._def.values}};p6.create=(e,t)=>new p6({values:e,typeName:xt.ZodNativeEnum,...Ut(t)});var Ey=class extends Dt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),bt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ks(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ey.create=(e,t)=>new Ey({type:e,typeName:xt.ZodPromise,...Ut(t)});var md=class extends Dt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.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=>{Te(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 bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?e6(c.value):r.value==="dirty"?e6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?e6(a.value):r.value==="dirty"?e6(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"?bt:(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"?bt:(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(!_y(s))return bt;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=>_y(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Yt.assertNever(i)}};md.create=(e,t,r)=>new md({schema:e,typeName:xt.ZodEffects,effect:t,...Ut(r)});md.createWithPreprocess=(e,t,r)=>new md({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...Ut(r)});var pd=class extends Dt{_parse(t){return this._getType(t)===Be.undefined?Ks(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pd.create=(e,t)=>new pd({innerType:e,typeName:xt.ZodOptional,...Ut(t)});var _f=class extends Dt{_parse(t){return this._getType(t)===Be.null?Ks(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_f.create=(e,t)=>new _f({innerType:e,typeName:xt.ZodNullable,...Ut(t)});var f6=class extends Dt{_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}};f6.create=(e,t)=>new f6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ut(t)});var m6=class extends Dt{_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 l8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new oc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new oc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};m6.create=(e,t)=>new m6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ut(t)});var g8=class extends Dt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};g8.create=e=>new g8({typeName:xt.ZodNaN,...Ut(e)});var P3t=Symbol("zod_brand"),h7=class extends Dt{_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}},y7=class e extends Dt{_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"?bt:o.status==="dirty"?(r.dirty(),e6(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"?bt: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:xt.ZodPipeline})}},h6=class extends Dt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(_y(i)&&(i.value=Object.freeze(i.value)),i);return l8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};h6.create=(e,t)=>new h6({innerType:e,typeName:xt.ZodReadonly,...Ut(t)});function _Oe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function xOe(e,t={},r){return e?wy.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=_Oe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=_Oe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):wy.create()}var O3t={object:sc.lazycreate},xt;(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"})(xt||(xt={}));var C3t=(e,t={message:`Input not instance of ${e.name}`})=>xOe(r=>r instanceof e,t),z=vy.create,Or=t6.create,R3t=g8.create,k3t=r6.create,hd=n6.create,N3t=i6.create,B3t=f8.create,j3t=o6.create,b8=s6.create,yd=wy.create,U3t=B0.create,M3t=Bl.create,q3t=m8.create,ue=j0.create,fe=sc.create,D3t=sc.strictCreate,_8=a6.create,L3t=YU.create,z3t=c6.create,H3t=bf.create,Zt=ZU.create,F3t=h8.create,$3t=y8.create,V3t=XU.create,K3t=u6.create,W3t=d6.create,gd=l6.create,G3t=p6.create,J3t=Ey.create,Y3t=md.create,Z3t=pd.create,X3t=_f.create,Q3t=md.createWithPreprocess,eEt=y7.create,tEt=()=>z().optional(),rEt=()=>Or().optional(),nEt=()=>hd().optional(),pu={string:(e=>vy.create({...e,coerce:!0})),number:(e=>t6.create({...e,coerce:!0})),boolean:(e=>n6.create({...e,coerce:!0})),bigint:(e=>r6.create({...e,coerce:!0})),date:(e=>i6.create({...e,coerce:!0}))};var iEt=bt;var sEt=gd(["enc","sig"]),aEt=gd(["markdown","plain"]),cEt=gd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),uEt=gd(["error","info","warning"]),E8=gd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),dEt=gd(["completed","failed","pending"]),lEt=gd(["digital","pickup","shipping"]),pEt=gd(["fulfilled","partial","processing","removed"]),fEt=gd(["across","each"]),Vre=gd(["pickup","shipping"]),mEt=fe({config:Zt(z(),yd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),hEt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:sEt.optional(),x:z().optional(),y:z().optional()}),yEt=fe({config:Zt(z(),yd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),gEt=fe({endpoint:z()}),bEt=fe({schema:z()}),SOe=fe({endpoint:z(),schema:z()}),_Et=SOe,vEt=SOe,Aa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),po=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),Kre=po,TOe=fe({id:z()}),wEt=TOe,EEt=TOe,g7=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),QU=fe({type:z()}),Vi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),Wre=Vi,IOe=fe({id:z(),image_url:z().optional(),price:Or(),title:z()}),eM=fe({amount:Or(),display_text:z().optional(),type:z()}),Ay=fe({title:z().optional(),type:z(),url:z()}),U0=fe({code:z().optional(),content:z(),content_type:aEt.optional(),path:z().optional(),severity:cEt.optional(),type:uEt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Gre=U0,A8=fe({id:z(),label:z().optional(),permalink_url:z()}),AEt=fe({amount:Or(),display_text:z()}),xEt=fe({config:Zt(z(),yd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Jre=fe({id:z(),quantity:Or()}),SEt=Jre,TEt=Jre,IEt=Jre,PEt=fe({fulfilled:Or(),original:Or().optional(),total:Or()}),OEt=fe({billing_address:g7.optional(),credential:QU.optional(),display:Zt(z(),yd()).optional(),handler_id:z(),id:z(),type:z()}),CEt=fe({checkout_mandate:z()}),REt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),kEt=fe({analytics:hd().optional(),marketing:hd().optional(),preferences:hd().optional(),sale_of_data:hd().optional()});var NEt=kEt;var POe=fe({codes:ue(z()).optional()}),BEt=POe,jEt=fe({amount:Or(),path:z()}),UEt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:g7.optional(),name:z().optional()}),MEt=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:pu.date().optional(),id:z(),latest_fulfillment_time:pu.date().optional(),title:z(),totals:ue(eM)}),qEt=fe({description:z().optional(),fulfillable_on:_8([b8(),z()]).optional(),line_item_ids:ue(z()),type:Vre}),DEt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:g7.optional(),name:z().optional()}),LEt=fe({max:Or().optional(),min:Or().optional()}),b7=fe({taxonomy:z().optional(),value:z()}),_7=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),v8=fe({amount:Or(),currency:z()}),v7=fe({alt_text:z().optional(),height:Or().optional(),type:z(),url:z(),width:Or().optional()}),zEt=fe({id:z().optional(),label:z()}),w7=fe({count:Or().optional(),scale_max:Or(),scale_min:Or().optional(),value:Or()}),OOe=fe({available:hd().optional(),status:z().optional()}),HEt=OOe,COe=fe({type:z(),value:z()}),FEt=COe,$Et=fe({id:z(),match:z().optional()}),Yre=fe({id:z().optional(),label:z(),name:z()}),ROe=Yre,kOe=fe({links:ue(Ay).optional(),name:z().optional()}),VEt=kOe,NOe=fe({unit:z(),value:Or()});var KEt=NOe,WEt=fe({cursor:z().optional(),limit:Or().optional()}),GEt=fe({cursor:z().optional(),has_next_page:hd(),total_count:Or().optional()}),JEt=fe({handlers:ue(mEt).optional()}),YEt=fe({a2a:gEt.optional(),embedded:bEt.optional(),mcp:_Et.optional(),rest:vEt.optional(),spec:z(),version:z()}),x8=fe({item:wEt,quantity:Or()}),ZEt=fe({billing_address:g7.optional(),credential:QU.optional(),display:Zt(z(),yd()).optional(),handler_id:z(),id:z(),type:z(),selected:hd().optional()}),E7=fe({id:z().optional(),item:EEt,parent_id:z().optional(),quantity:Or()}),tM=fe({instruments:ue(ZEt).optional()}),XEt=tM,A7=tM,S8=tM,rM=tM,y6=fe({id:z(),item:IOe,parent_id:z().optional(),quantity:Or(),totals:ue(eM)}),xy=fe({amount:Or(),display_text:z().optional(),type:z(),lines:ue(AEt).optional()}),jl=fe({capabilities:Zt(z(),ue(xEt)),version:z()}),QEt=fe({description:z().optional(),id:z(),line_items:ue(SEt).optional(),occurred_at:pu.date(),status:dEt,totals:ue(eM).optional(),type:z()}),eAt=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(TEt),occurred_at:pu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),tAt=fe({description:z().optional(),destination:g7,fulfillable_on:z().optional(),id:z(),line_items:ue(IEt),method_type:lEt}),rAt=fe({id:z(),item:IOe,parent_id:z().optional(),quantity:PEt,status:pEt,totals:ue(eM)}),lUr=fe({payment_data:OEt}),pUr=fe({ap2:CEt.optional()}),fUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,ap2:REt.optional()}),Zre=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:NEt.optional()}),nAt=Zre,iAt=Zre,BOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional(),discounts:BEt.optional()}),oAt=fe({allocations:ue(jEt).optional(),amount:Or(),automatic:hd().optional(),code:z().optional(),eligibility:z().optional(),method:fEt.optional(),priority:Or().optional(),provisional:hd().optional(),title:z()}),jOe=fe({id:z(),line_item_ids:ue(z()),options:ue(MEt).optional(),selected_option_id:_8([b8(),z()]).optional()}),sAt=fe({destinations:ue(DEt).optional(),groups:ue(jOe).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:_8([b8(),z()]).optional(),type:Vre}),mUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),signals:Vi.optional()}),hUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),id:z(),line_items:ue(E7),signals:Vi.optional()}),yUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay).optional(),messages:ue(U0).optional(),signals:Vi.optional(),totals:ue(xy),ucp:jl}),aAt=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional()}),UOe=aAt,gUr=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,cart_id:z().optional()}),Xre=fe({categories:ue(z()).optional(),price:LEt.optional()}),w8=fe({max:v8,min:v8}),Qre=fe({name:z(),values:ue(zEt)}),MOe=fe({amount:Or(),currency:z(),measure:NOe,reference:KEt}),cAt=MOe,bUr=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(ROe).optional(),signals:Wre.optional()}),_Ur=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),pagination:WEt.optional(),query:z().optional(),signals:Wre.optional()}),uAt=fe({capabilities:ue(yEt),services:Zt(z(),YEt),version:z()}),vUr=fe({attribution:Zt(z(),z()).optional(),payment:XEt,signals:Vi.optional()}),qOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl}),dAt=fe({events:ue(eAt).optional(),expectations:ue(tAt).optional()}),DOe=fe({attribution:Zt(z(),z()).optional(),buyer:Zre.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional()}),LOe=fe({attribution:Zt(z(),z()).optional(),buyer:iAt.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional()}),zOe=fe({attribution:Zt(z(),z()).optional(),buyer:nAt.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl}),HOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),discounts:POe.optional()}),lAt=fe({applied:ue(oAt).optional(),codes:ue(z()).optional()}),pAt=fe({destinations:ue(UEt).optional(),groups:ue(jOe).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:_8([b8(),z()]).optional(),type:Vre}),fAt=fe({available_methods:ue(qEt).optional(),methods:ue(sAt).optional()}),FOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),cart_id:z().optional()}),wUr=fe({attribution:Zt(z(),z()).optional(),context:Kre.optional(),filters:Xre.optional(),ids:ue(z()),signals:Wre.optional()}),mAt=fe({availability:OOe.optional(),barcodes:ue(COe).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price:v8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Yre).optional(),price:v8,rating:w7.optional(),seller:kOe.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:MOe.optional(),url:z().optional(),inputs:ue($Et)}),$Oe=fe({availability:HEt.optional(),barcodes:ue(FEt).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price:v8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Yre).optional(),price:v8,rating:w7.optional(),seller:VEt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:cAt.optional(),url:z().optional()}),hAt=fe({categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Qre).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue($Oe)}),EUr=fe({payment:JEt.optional(),signing_keys:ue(hEt).optional(),ucp:uAt}),VOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional()}),yAt=fe({adjustments:ue(QEt).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:dAt,id:z(),label:z().optional(),line_items:ue(rAt),messages:ue(U0).optional(),permalink_url:z(),totals:ue(xy),ucp:jl}),KOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,discounts:lAt.optional()}),WOe=fe({methods:ue(pAt).optional()}),GOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(E7),payment:rM.optional(),signals:Vi.optional(),fulfillment:WOe.optional()}),JOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),continue_url:z().optional(),currency:z(),expires_at:pu.date().optional(),id:z(),line_items:ue(y6),links:ue(Ay),messages:ue(U0).optional(),order:A8.optional(),payment:S8.optional(),signals:Vi.optional(),status:E8,totals:ue(xy),ucp:jl,fulfillment:fAt.optional()}),gAt=fe({categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),options:ue(Qre).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(mAt)}),bAt=fe({options:ue(Qre).optional(),selected:ue(ROe).optional(),categories:ue(b7).optional(),description:_7,handle:z().optional(),id:z(),list_price_range:w8.optional(),media:ue(v7).optional(),metadata:Zt(z(),yd()).optional(),price_range:w8,rating:w7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue($Oe)}),AUr=fe({messages:ue(Gre).optional(),pagination:GEt.optional(),products:ue(hAt),ucp:jl}),YOe=fe({attribution:Zt(z(),z()).optional(),buyer:Aa.optional(),context:po.optional(),line_items:ue(x8),payment:A7.optional(),signals:Vi.optional(),fulfillment:WOe.optional()}),xUr=fe({messages:ue(Gre).optional(),products:ue(gAt),ucp:jl}),SUr=fe({messages:ue(Gre).optional(),product:bAt,ucp:jl});var OUr=QU.extend({token:Dr.string().optional()}),_At=Dr.object({webhook_url:Dr.string().url().optional()}),ZOe=qOe.extend(JOe.pick({fulfillment:!0}).shape).extend(KOe.pick({discounts:!0}).shape).extend(zOe.pick({buyer:!0}).shape).extend({platform:_At.optional()}),XOe=VOe.extend(YOe.pick({fulfillment:!0}).shape).extend(HOe.pick({discounts:!0}).shape).extend(DOe.pick({buyer:!0}).shape).extend(FOe.pick({cart_id:!0}).shape),QOe=UOe.extend(GOe.pick({fulfillment:!0}).shape).extend(BOe.pick({discounts:!0}).shape).extend(LOe.pick({buyer:!0}).shape);ud();async function nM(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 iM(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 vAt=3e4,eCe=2*1024*1024,Ul=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function tCe(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 rCe(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"?XOe:QOe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function wAt(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 nCe(e,t,r,n){try{e[t](r,n)}catch{}}function EAt(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 oM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=tCe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=tCe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??vAt,this.boundaryLogger=t.logger??Me}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:rCe(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:rCe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=iM(this.timeoutMs,this.signal),o=(0,iCe.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 nM(u,eCe,"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 Ul(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>eCe)throw new Ul("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Ul("UCP MCP response is not valid JSON",void 0,u.status)}if(!wAt(l))throw new Ul("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Ul("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Ul(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Ul(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Ul("UCP MCP response is missing result.structuredContent");if(!ZOe.safeParse(EAt(p.structuredContent)).success)throw new Ul("UCP checkout response failed schema validation");return nCe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw nCe(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 sCe=require("node:crypto");ud();var aM="2026-04-08",AAt="dev.ucp.shopping",xAt="dev.ucp.shopping.checkout",SAt=1024*1024,TAt=1e4,IAt="https://ucp.dev",x7=Dr.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"),PAt=Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:x7,schema:x7,transport:Dr.enum(["rest","mcp","a2a","embedded"]),endpoint:x7.optional()}).passthrough(),OAt=Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:x7,schema:x7,extends:Dr.union([Dr.string(),Dr.array(Dr.string()).min(1)]).optional()}).passthrough(),CAt=Dr.object({ucp:Dr.object({version:Dr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Dr.record(Dr.array(PAt)),capabilities:Dr.record(Dr.array(OAt)),payment_handlers:Dr.record(Dr.array(Dr.unknown())).optional()}).passthrough(),signing_keys:Dr.array(Dr.unknown()).optional()}).passthrough();function RAt(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 sM(e,t){if(new URL(e).origin!==IAt)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function oCe(e,t,r,n){try{e[t](r,n)}catch{}}async function kAt(e,t={}){let r=RAt(e,"UCP business URL"),n=iM(t.timeoutMs??TAt,t.signal),i=t.logger??Me,o=(0,sCe.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 nM(c,SAt,"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=CAt.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return oCe(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 oCe(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 NAt(e){if(e.ucp.version!==aM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[xAt]?.find(i=>i.version===aM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");sM(t.spec,"Checkout capability spec"),sM(t.schema,"Checkout capability schema");let r=e.ucp.services[AAt]?.find(i=>i.version===aM&&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");sM(r.spec,"Shopping service spec"),sM(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 aCe(e,t={}){let r=await kAt(e,t);return{...r,endpoint:NAt(r.profile),version:aM}}var BAt="https://app.visacli.sh/.well-known/ucp";function jAt(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 UAt(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 ene(e,t=new Set){if(Array.isArray(e))for(let r of e)ene(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?UAt(n,t):ene(n,t);return t}function MAt(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=ene(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 qAt(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 DAt(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 uCe(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??aCe)(e.business),i=await(t.getCheckout??(async(u,d)=>await new oM({endpoint:u.endpoint,platformProfileUrl:jAt(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??BAt)}).getCheckout(d)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");let o=String(i.status??"unknown");if(o==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_already_completed"};if(o!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_not_escalated"};if(typeof i.continue_url!="string"||!i.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"missing_continue_url"};let s=qAt(i),a=MAt(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,cCe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,o,s.currency,String(s.minor),a.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:c,checkoutStatus:"requires_escalation",amount:s,merchant:{businessOrigin:r.businessOrigin,sourceHost:a.sourceHost,targetHost:a.targetHost,originRewritten:a.originRewritten},payMerchantRequest:{action:"review",url:a.url,amount:s.decimal,currency:s.currency},messages:DAt(i),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>."}}I_();function tne(){return du()}var Nl=new rf(()=>ei.getSessionToken()),LAt="4.1.0-rc.42",uMr=["","","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(`
|
|
20923
20923
|
`);function zAt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=bT(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(USe())return{opened:!1,url:t,blockedReason:"suppressed"};let r=gT();if(r.headless)return Me.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[tne(),P_()].filter(s=>!!s).map(s=>Bxe(t,s)).find(Boolean)??null;if(!i)return Me.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Uxe(i);return o?((0,lCe.execFile)(o.cmd,o.args,s=>{s&&Me.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Me.info(`No browser command for platform "${uM.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function HAt(){let e=!1,t;try{let n=pCe.join(uM.homedir(),".claude","settings.json");if(cM.existsSync(n)){let i=JSON.parse(cM.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=ey(o)}}catch{}let r=pj();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function FAt(e){let t=await Nl.getStatus(e);return t.hud=HAt(),!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=LAt,t}async function $At(e,t){return await Nl.feedback(e.message,e.transaction_id,t)}async function VAt(e){let t=await c7({api:Nl,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 rne=new Set(["auth.serverUrl"]);function S7(){return Object.keys(T_).filter(e=>!rne.has(e)).sort()}function fCe(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:S7()}}async function KAt(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(rne.has(e.key))return Me.warn("config:set:rejected:mcp-forbidden",{key:e.key}),fCe(e.key,"set");Me.info("config:set",{key:e.key});try{let t=Sj(e.key,e.value);return Me.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 Cl?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Cl?`Unknown setting "${e.key}". MCP-settable keys: ${S7().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Me.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:S7()}}}async function WAt(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(rne.has(e.key))return Me.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),fCe(e.key,"unset");Me.info("config:unset",{key:e.key});try{let t=Tj(e.key);return Me.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 Cl?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Cl?`Unknown setting "${e.key}". MCP-settable keys: ${S7().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Me.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:S7()}}}async function GAt(e=tne(),t=!1){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};if(!t){let r=JT();if(r){let n=r.display_name,i;if(process.env.SUBWAY_MESH==="visa"&&n){let{registerOnVisaMeshIfEnabled:s}=await Promise.resolve().then(()=>(RU(),HPe));i=await s(n)}Me.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 YT({authUrl:e,runtime:"visa-cli-mcp",contextLabel:"Pair this MCP runtime"});Me.info("agent:pairing_open",{pairingId:r.pairingId,agentId:r.agentId});let n=zAt(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 JAt(e=tne()){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};let t=await ZT({authUrl:e});switch(Me.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 dCe(){if(await ei.clearAll(),!!v0())try{await kj()}catch(e){Me.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function YAt(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Me.info("reset:attempt"),e.localOnly)return await dCe(),Me.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 Nl.logout(void 0,t)}catch{}return await dCe(),Me.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 ZAt(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(Z_(),o7)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{VisaBindingRequiredError:r}=await Promise.resolve().then(()=>(Gj(),n7e));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 XAt(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Z_(),o7));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function QAt(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(()=>(Z_(),o7)),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 e9t(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(Z_(),o7)),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 T8=class{static async subwayRegister(t){return ZAt(t||{})}static async subwayFind(t){return XAt(t||{})}static async subwaySend(t){return QAt(t||{})}static async subwayInbox(t){return e9t(t||{})}static async getStatus(t){return FAt(t)}static async feedback(t,r){return $At(t,r)}static async configList(t){return VAt(t||{})}static async configSet(t){return KAt(t||{})}static async configUnset(t){return WAt(t||{})}static async reset(t,r){return YAt(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?GAt(void 0,t?.force===!0):n==="claim"?JAt():{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 hOe(t)}static async ucpCheckoutHandoff(t,r){return u8("ucp_checkout_handoff")&&(await FU(),u8("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."}:uCe(t)}static async payMerchantStatus(t={},r){return mOe(t)}static async startCardMandate(t={},r){return yOe(t)}static async submitFeedback(t,r,n){Me.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await Nl.submitFeedback(t,r,n);return Me.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Me.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Me.info("feedback:list",{limit:t||20});try{let n=await Nl.getFeedback(t,r);return Me.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Me.error("feedback:error",{error:i}),n}}};async function mCe(e,t,r,n){let i=n.log??console.log,o=n.error??console.error,s=n.exit??(c=>process.exit(c)),a=n.env??process.env;try{let c=r.currency,u=r.rail,d=await n.payMerchant({action:"review",rail:u,url:e,amount:t,currency:c});if(!d||d.success!==!0)return o(d?.message||"Review failed."),void s(1);if(i(d.message),!r.submit){i("Review only \u2014 nothing charged. Re-run with --submit to authorize (passkey required).");return}let l=d.reviewId;if(typeof l!="string"||l.length===0)return o("Review did not return a usable reviewId \u2014 cannot authorize a charge. Nothing charged."),void s(1);a.CHECKOUT_AGENT_ALLOW_SUBMIT="1";let p=await n.payMerchant({action:"pay",rail:u,url:e,amount:t,currency:c,confirm:`PAY ${l}`});if(i(p?.message),!p||p.success!==!0)return void s(1)}catch(c){return o("Error:",c.message),void s(1)}}var hCe=require("node:fs/promises"),yCe=require("node:os"),gCe=require("node:path");async function bCe(e,t,r){let n=r.log??console.log,i=r.error??console.error,o=r.exit??(s=>process.exit(s));try{let s={...t.agent?{agent:t.agent}:{},ceiling:e,...t.perTransaction?{perTransaction:t.perTransaction}:{},...t.intent?{intent:t.intent}:{}},a=await r.startCardMandate(s);if(!a||a.success!==!0)return i(a?.message||"Could not create the mandate."),void o(1);n(a.message),n(""),n(` mandate: ${a.mandateId}`),n(` ceiling: ${a.ceiling} ${a.currency}`),typeof a.remainingMinor=="number"&&n(` remaining: ${c8(a.remainingMinor,a.currency??"USD")}`),n(" scope: eligible retail merchants (network category 5999)"),typeof a.maxPurchases=="number"&&n(` purchases: up to ${a.maxPurchases}`),a.expiresAt&&n(` expires: ${a.expiresAt}`)}catch(s){return i("Error:",s.message),void o(1)}}var t9t=300*1e3;function r9t(){return process.env.VISA_CARD_MANDATE_LEDGER_FILE??(0,gCe.join)((0,yCe.homedir)(),".visa-mcp","card-mandates.json")}async function n9t(){try{let e=JSON.parse(await(0,hCe.readFile)(r9t(),"utf8"));return!e||!Array.isArray(e.mandates)?{mandates:[]}:e}catch(e){if(e.code==="ENOENT")return null;throw e}}function i9t(e,t){let r=(e.reservations??[]).reduce((n,i)=>{let o=i.reservedAt!==void 0?Date.parse(i.reservedAt):NaN;return!Number.isFinite(o)||t-o>t9t?n:n+i.amountMinor},0);return e.ceilingMinor-e.spentMinor-r}function o9t(e){return e.length>18?`${e.slice(0,8)}\u2026${e.slice(-6)}`:e}async function _Ce(e={}){let t=e.log??console.log,r=e.error??console.error,n=e.exit??(s=>process.exit(s)),i=e.readLedger??n9t,o=(e.now??(()=>new Date))().getTime();try{let c=((await i())?.mandates??[]).filter(u=>{let d=Date.parse(u.expiresAt);return Number.isFinite(d)&&d>o});if(c.length===0){t("No active mandates. Create one with: visa-cli mandate start <ceiling>");return}t(`Active mandates
|
|
20924
20924
|
`);for(let u of c){if(t(` ${u.mandateId}`),t(u.crossMerchant?" scope: eligible retail merchants (network category 5999)":` merchant: ${u.merchantName||u.merchantHost||"(unknown)"}`),u.agentJkt&&t(` request key: ${o9t(u.agentJkt)}`),t(` remaining: ${c8(i9t(u,o),u.currencyCode)}`),Number.isSafeInteger(u.maxDraws)&&u.maxDraws>0){let d=(u.draws??[]).filter(l=>l.status==="committed").length;t(` credentials issued: ${d} of ${u.maxDraws}`)}t(` expires: ${u.expiresAt}`),u.unhonoredAt&&t(` unhonored: yes (disabled ${u.unhonoredAt}) \u2014 next checkout uses a fresh tap`),u.registerFailedAt&&t(` register: FAILED (${u.registerFailedAt}) \u2014 not used for tap-free draws; next checkout uses a fresh tap`)}}catch(s){return r("Error:",s.message),void n(1)}}ud();function vCe(e,t=process.stderr){if(ty()||!e?.updateAvailable)return!1;let{latestVersion:r}=e.updateAvailable;if(!r)return!1;let n=`Update available: v${r}. Run: visa-cli update`;return t.write(`
|
|
20925
20925
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
@@ -20935,7 +20935,7 @@ If building from source, run native/build-win.bat first.`);en.mkdirSync(ny,{recu
|
|
|
20935
20935
|
`)}function wkr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-1,0))}\u2026`}function Ekr(e){if(e.length===0)return"No matching paid services.";let t=["ID","Protocol","Price","Health","Service"],r=e.map(i=>[i.id,i.protocol,i.listedPriceUsd?`$${i.listedPriceUsd}`:"runtime",i.health,wkr(i.name,48)]),n=t.map((i,o)=>Math.max(i.length,...r.map(s=>s[o].length)));return[t,...r].map(i=>i.map((o,s)=>o.padEnd(n[s])).join(" ").trimEnd()).join(`
|
|
20936
20936
|
`)}function Akr(){let e=EU.map(r=>({id:r.id,detected:qte(r),connected:Vte(r)})),t={id:Math.max(6,...e.map(r=>r.id.length))};return[`${"Client".padEnd(t.id)} Detected Connected`,...e.map(r=>`${r.id.padEnd(t.id)} ${(r.detected?"yes":"no").padEnd(8)} ${r.connected?"yes":"no"}`)].join(`
|
|
20937
20937
|
`)}function xkr(e,t){if(e==="find"){let r=t.listings;txe(Ekr(r));return}if(e==="connections"){txe(Akr());return}txe(JSON.stringify(t,null,2))}async function Xp(e,t,r){let n="table";try{n=vkr(t);let i=await r();n==="table"?xkr(e,i):one(ECe(e,{data:i}),n)}catch(i){let o=i instanceof Error?i.message:String(i);n==="table"?process.stderr.write(`Error: ${o}
|
|
20938
|
-
`):one(ACe(e,o),n),process.exitCode=1}}function Skr(){this.help({error:!1})}function h2t(e){Zp(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${DQ.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await Xp("find",n,async()=>{let i=["all",...DQ];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return g_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),Zp(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await Xp("inspect",n,()=>g_().inspect({listingId:r,url:n.url,bodyJson:m2t(n.input)}))}),Zp(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await Xp("pay",n,()=>g_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:m2t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(Skr);Zp(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>Xp("wallet show",r,()=>g_().status())),Zp(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>Xp("wallet fund",r,()=>g_().fund())),Zp(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>Xp("wallet limits",r,()=>g_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),Zp(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await Xp("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return g_().activity(n)})}),Zp(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await Xp("receipt",n,()=>g_().receipt(r))}),Zp(e.command("connections").description("Show supported MCP client connections.")).action(async r=>Xp("connections",r,async()=>EU.map(n=>({id:n.id,name:n.displayName,detected:qte(n),connected:Vte(n)})))),Zp(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await Xp("connect",n,async()=>{let i=VT(r);if(!i)throw new Error(`unknown client: ${r}`);return DIe(i)})}),Zp(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await Xp("disconnect",n,async()=>{let i=VT(r);if(!i)throw new Error(`unknown client: ${r}`);return zIe(i)})})}ud();var nxe=!1;async function ixe(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!v0())throw n;if(Me.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(nxe)throw Me.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;nxe=!0,Me.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw Me.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await rTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),Me.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),Me.info("attestation:key-reregistered-after-recovery");let a=await t();return nxe=!1,a}catch(o){throw Me.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function oxe(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}n8();Tte();Z_();var Tkr="4.1.0-rc.41";async function y2t(e){let t=await i7(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${n7} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var WB=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function g2t(e){if(!hre(Tkr))return;e.command("register <name>").description(`Register a name on the "${Oi}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await y2t(r)}catch(n){WB("register",n)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await y2t(r)}catch(n){WB("register",n)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(r,n,i)=>{try{let o=jU(i.as),s=await wre(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){WB("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async r=>{try{let n=await vre(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){WB("find",n)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async r=>{try{let n=jU(r.as),i=i8(n,{autoReconnect:!0});await o8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${L_(n)} on "${Oi}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){WB("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=Ere();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var Hkr=_e(require("fs")),D2t=_e(require("os")),ef=_e(require("path")),L2t=require("node:readline/promises");Qh();var Jh=_e(require("fs")),h0=_e(require("path"));var Ikr=1,O4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Pkr=["terminal","claude","claude-code","all"];function zQ(e){let t=e.toLowerCase();return Pkr.includes(t)?t:null}var Okr=50,Ckr=64*1024,b2t=10,sxe=80,ot={get reset(){return Ds().reset},get visaBlue(){return Ds().visaBlue},get visaBlueSoft(){return Ds().visaBlueSoft},get visaGold(){return Ds().visaGold},get green(){return Ds().green},get muted(){return Ds().muted},get chrome(){return Ds().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||uj()?e:`${t}${e}${ot.reset}`}function _2t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function A2t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},Okr);e.on("data",s),e.on("end",a),e.on("error",c)})}function GB(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function JB(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Rkr(e){if(N2t(e))return Nkr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=LQ(e)||"claude",n=e.cwd?uo(h0.basename(e.cwd)):"",i=HQ(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=uo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${JB(v)}/${JB(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${GB(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let _=x2t(e.rate_limits),w=[E];_&&w.push(_);let A=w.join(t);return`${u}
|
|
20938
|
+
`):one(ACe(e,o),n),process.exitCode=1}}function Skr(){this.help({error:!1})}function h2t(e){Zp(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${DQ.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await Xp("find",n,async()=>{let i=["all",...DQ];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return g_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),Zp(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await Xp("inspect",n,()=>g_().inspect({listingId:r,url:n.url,bodyJson:m2t(n.input)}))}),Zp(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await Xp("pay",n,()=>g_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:m2t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(Skr);Zp(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>Xp("wallet show",r,()=>g_().status())),Zp(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>Xp("wallet fund",r,()=>g_().fund())),Zp(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>Xp("wallet limits",r,()=>g_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),Zp(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await Xp("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return g_().activity(n)})}),Zp(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await Xp("receipt",n,()=>g_().receipt(r))}),Zp(e.command("connections").description("Show supported MCP client connections.")).action(async r=>Xp("connections",r,async()=>EU.map(n=>({id:n.id,name:n.displayName,detected:qte(n),connected:Vte(n)})))),Zp(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await Xp("connect",n,async()=>{let i=VT(r);if(!i)throw new Error(`unknown client: ${r}`);return DIe(i)})}),Zp(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await Xp("disconnect",n,async()=>{let i=VT(r);if(!i)throw new Error(`unknown client: ${r}`);return zIe(i)})})}ud();var nxe=!1;async function ixe(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!v0())throw n;if(Me.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(nxe)throw Me.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;nxe=!0,Me.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw Me.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await rTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),Me.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),Me.info("attestation:key-reregistered-after-recovery");let a=await t();return nxe=!1,a}catch(o){throw Me.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function oxe(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}n8();Tte();Z_();var Tkr="4.1.0-rc.42";async function y2t(e){let t=await i7(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${n7} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var WB=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function g2t(e){if(!hre(Tkr))return;e.command("register <name>").description(`Register a name on the "${Oi}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await y2t(r)}catch(n){WB("register",n)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await y2t(r)}catch(n){WB("register",n)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(r,n,i)=>{try{let o=jU(i.as),s=await wre(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){WB("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async r=>{try{let n=await vre(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){WB("find",n)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async r=>{try{let n=jU(r.as),i=i8(n,{autoReconnect:!0});await o8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${L_(n)} on "${Oi}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){WB("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=Ere();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var Hkr=_e(require("fs")),D2t=_e(require("os")),ef=_e(require("path")),L2t=require("node:readline/promises");Qh();var Jh=_e(require("fs")),h0=_e(require("path"));var Ikr=1,O4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Pkr=["terminal","claude","claude-code","all"];function zQ(e){let t=e.toLowerCase();return Pkr.includes(t)?t:null}var Okr=50,Ckr=64*1024,b2t=10,sxe=80,ot={get reset(){return Ds().reset},get visaBlue(){return Ds().visaBlue},get visaBlueSoft(){return Ds().visaBlueSoft},get visaGold(){return Ds().visaGold},get green(){return Ds().green},get muted(){return Ds().muted},get chrome(){return Ds().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||uj()?e:`${t}${e}${ot.reset}`}function _2t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function A2t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},Okr);e.on("data",s),e.on("end",a),e.on("error",c)})}function GB(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function JB(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Rkr(e){if(N2t(e))return Nkr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=LQ(e)||"claude",n=e.cwd?uo(h0.basename(e.cwd)):"",i=HQ(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=uo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${JB(v)}/${JB(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${GB(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let _=x2t(e.rate_limits),w=[E];_&&w.push(_);let A=w.join(t);return`${u}
|
|
20939
20939
|
${A}`}function kkr(e){if(N2t(e))return null;let t=` ${ct("\u2502",ot.chrome)} `,r=LQ(e)||"claude",n=e.cwd?uo(h0.basename(e.cwd)):"",i=HQ(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=uo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,l=e.context_window?.current_usage,p=[l?.input_tokens,l?.output_tokens,l?.cache_creation_input_tokens,l?.cache_read_input_tokens].filter(w=>typeof w=="number"&&Number.isFinite(w)),f=p.length>0?p.reduce((w,A)=>w+A,0):null,m=Number(e.context_window?.total_input_tokens??f??l?.input_tokens??0),h=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,m/u)):0,y=d!==null&&u>0?Math.round(h*u):m,v;if(u>0||d!==null){let w=`${String(Math.round(h*100)).padStart(2," ")}%`,A=u>0?` ${ct(`(${JB(y)}/${JB(u)})`,ot.muted)}`:"";v=`${ct("Context",ot.muted)} ${GB(h)} ${ct(w,ot.green)}${A}`}else v=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let E=x2t(e.rate_limits),_=[v];return E&&_.push(E),{identity:a.join(t),metrics:_.join(t)}}function Nkr(e){let t=` ${ct("\u2502",ot.chrome)} `,r=B2t(e),n=r.model||"codex",i=[ct(`[${n}]`,ot.visaBlueSoft)];r.project&&i.push(ct(r.project,ot.visaGold)),r.gitBranch&&i.push(`${ct("git",ot.muted)} ${ct(r.gitBranch,ot.visaGold)}`);let o=i.join(t),s=[];if(typeof r.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,r.contextUsedPercent/100));s.push(`${ct("Context",ot.muted)} ${GB(c)} ${ct(`${Math.round(r.contextUsedPercent)}%`,ot.green)}`)}else if(typeof r.contextRemainingPercent=="number"){let c=100-r.contextRemainingPercent,u=Math.max(0,Math.min(1,c/100));s.push(`${ct("Context",ot.muted)} ${GB(u)} ${ct(`${Math.round(c)}%`,ot.green)}`)}typeof r.usedTokens=="number"&&s.push(`${ct("Tokens",ot.muted)} ${JB(r.usedTokens)}`),r.status&&s.push(`${ct("Status",ot.muted)} ${ct(r.status,ot.visaBlueSoft)}`),r.threadTitle&&s.push(`${ct("Thread",ot.muted)} ${ct(r.threadTitle,ot.visaBlueSoft)}`);let a=s.length>0?s.join(t):`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;return`${o}
|
|
20940
20940
|
${a}`}function Bkr(e){if(typeof e!="number"||e<=0)return"";let r=(e>1e12?e:e*1e3)-Date.now();if(r<=0||r>=10080*60*1e3)return"";let n=Math.floor(r/6e4),i=Math.floor(n/60),o=n%60;return i>0?`${i}h ${o}m`:`${o}m`}function v2t(e,t){if(!e||typeof e.used_percentage!="number")return null;let r=Math.max(0,Math.min(100,e.used_percentage)),n=r/100,i=GB(n),o=r>=90?"\x1B[38;5;196m":r>=70?ot.visaGold:ot.green,s=`${String(Math.round(r)).padStart(2," ")}%`,a=Bkr(e.resets_at),c=a?` ${ct(`(${a} / ${t})`,ot.muted)}`:` ${ct(`(${t})`,ot.muted)}`;return`${i} ${ct(s,o)}${c}`}function x2t(e){if(!e)return null;let t=v2t(e.five_hour,"5h"),r=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,n=r!==null&&r>=90?v2t(e.seven_day,"7d"):null;if(!t&&!n)return null;let i=` ${ct("\u2502",ot.chrome)} `,o=[t,n].filter(Boolean);return`${ct("Usage",ot.muted)} ${o.join(i)}`}function S2t(e){let t;try{let r=Jh.statSync(e);if(!r.isFile())return null;let n=r.size;if(n===0)return null;let i=Math.min(n,Ckr),o=n-i;t=Jh.openSync(e,"r");let s=Buffer.alloc(i);Jh.readSync(t,s,0,i,o);let a=s.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Jh.readSync(t,c,0,1,o-1),c[0]!==10){let u=a.indexOf(`
|
|
20941
20941
|
`);u>=0&&(a=a.slice(u+1))}}return a}catch{return null}finally{if(t!==void 0)try{Jh.closeSync(t)}catch{}}}function jkr(e){if(!e||typeof e!="object")return;let t=e,r=["file_path","path","notebook_path","pattern","command","url"];for(let n of r){let i=t[n];if(typeof i=="string"&&i.length>0){if(n.endsWith("_path")||n==="path"){let o=h0.basename(h0.dirname(i)),s=h0.basename(i);return o&&o!=="."&&o!=="/"?`${o}/${s}`:s}return i}}}function Ukr(e){let t=e.split(`
|