@visa/cli 4.1.0-rc.36 → 4.1.0-rc.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var _0t=Object.create;var tB=Object.defineProperty;var v0t=Object.getOwnPropertyDescriptor;var w0t=Object.getOwnPropertyNames;var E0t=Object.getPrototypeOf,x0t=Object.prototype.hasOwnProperty;var P=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ki=(e,t)=>{for(var r in t)tB(e,r,{get:t[r],enumerable:!0})},u3e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of w0t(t))!x0t.call(e,i)&&i!==r&&tB(e,i,{get:()=>t[i],enumerable:!(n=v0t(t,i))||n.enumerable});return e};var Ze=(e,t,r)=>(r=e!=null?_0t(E0t(e)):{},u3e(t||!e||!e.__esModule?tB(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>u3e(tB({},"__esModule",{value:!0}),e);var iB,y3e,g3e,eZ,nh,tZ=P(()=>{"use strict";iB=Ze(require("fs")),y3e=Ze(require("path")),g3e=Ze(require("os")),eZ=y3e.join(g3e.homedir(),".visa-mcp"),nh=class{static ensureConfigDir(){iB.existsSync(eZ)||iB.mkdirSync(eZ,{recursive:!0,mode:448})}static getConfigDir(){return eZ}}});function P0t(){Da.existsSync(nZ)||Da.mkdirSync(nZ,{recursive:!0,mode:448})}function I0t(){if(!rZ){if(P0t(),Da.existsSync(HA)&&Da.statSync(HA).size>T0t){let t=HA+".1";Da.existsSync(t)&&Da.unlinkSync(t),Da.renameSync(HA,t)}rZ=Da.createWriteStream(HA,{flags:"a"})}return rZ}function O0t(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function oB(e,...t){let r=new Date().toISOString(),n=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${r}] [${e}] ${n}
|
|
3
|
-
`;O0t(e)&&process.stderr.write(i),I0t().write(i)}var Da,iZ,b3e,nZ,HA,T0t,rZ,Be,Hc=P(()=>{"use strict";Da=Ze(require("fs")),iZ=Ze(require("path")),b3e=Ze(require("os")),nZ=iZ.join(b3e.homedir(),".visa-mcp"),HA=iZ.join(nZ,"mcp-server.log"),T0t=5*1024*1024,rZ=null;Be={debug:(...e)=>oB("DEBUG",...e),info:(...e)=>oB("INFO",...e),warn:(...e)=>oB("WARN",...e),error:(...e)=>oB("ERROR",...e)}});var sB=g((Jxr,C0t)=>{C0t.exports={name:"@visa/cli",version:"4.1.0-rc.
|
|
4
|
-
`;ih.writeFileSync(r,n,{mode:384}),ih.renameSync(r,t)}function aZ(e){let t=cB()[e];return typeof t=="string"?t:void 0}function cZ(e){let t=cB()[e];return typeof t=="boolean"?t:void 0}function A3e(e,t){let r=FA[e];if(!r)throw new km(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=cB();return i[e]=n,x3e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:aB()}}function S3e(e){let t=FA[e];if(!t)throw new km(e);let r=cB(),n=e in r;return n&&(delete r[e],x3e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:aB()}}function q0t(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function M0t(){try{let e=sB();return q0t(e.version)}catch{return!1}}function D0t(e){return e.envVar!==void 0&&e.envVar!==""?(oZ(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(oZ(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?U0t:j0t}function Mu(){return D0t({envVar:process.env.VISA_AUTH_URL,settingValue:aZ("auth.serverUrl"),isPrerelease:M0t()})}function T3e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":cZ("ui.suppressBrowser")??!1}var ih,sZ,v3e,w3e,R0t,k0t,FA,km,j0t,U0t,gw=P(()=>{"use strict";ih=Ze(require("fs")),sZ=require("node:net"),v3e=Ze(require("os")),w3e=Ze(require("path"));tZ();Hc();R0t="settings.json",k0t="must use https unless it points at localhost/loopback for local development";FA={"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");oZ(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};km=class extends Error{constructor(t){let r=Object.keys(FA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};j0t="https://auth.visacli.sh",U0t="https://auth-visa-code-preview.up.railway.app"});function uZ(e=V0t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function P3e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ol(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return P3e(t||K0t)}function $A(e){return`${P3e(e)}${W0t}`}var V0t,K0t,W0t,dZ=P(()=>{"use strict";V0t="4.1.0-rc.
|
|
3
|
+
`;O0t(e)&&process.stderr.write(i),I0t().write(i)}var Da,iZ,b3e,nZ,HA,T0t,rZ,Be,Hc=P(()=>{"use strict";Da=Ze(require("fs")),iZ=Ze(require("path")),b3e=Ze(require("os")),nZ=iZ.join(b3e.homedir(),".visa-mcp"),HA=iZ.join(nZ,"mcp-server.log"),T0t=5*1024*1024,rZ=null;Be={debug:(...e)=>oB("DEBUG",...e),info:(...e)=>oB("INFO",...e),warn:(...e)=>oB("WARN",...e),error:(...e)=>oB("ERROR",...e)}});var sB=g((Jxr,C0t)=>{C0t.exports={name:"@visa/cli",version:"4.1.0-rc.37",description:"AI-powered payments for Claude Code",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 _3e(e){let t=v3e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function aB(){return w3e.join(nh.getConfigDir(),R0t)}function E3e(e){if((0,sZ.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function B0t(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 E3e(i)}function N0t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,sZ.isIP)(t);return r===4?E3e(t):r===6?t==="::1"||B0t(t):!1}function oZ(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:"&&N0t(r.hostname)))throw new Error(`${t} ${k0t}`)}function cB(){let e=aB();if(!ih.existsSync(e))return{};try{let t=ih.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Be.warn("settings:corrupt",{path:_3e(e),reason:"not_object"}),{}):r}catch(t){return Be.warn("settings:corrupt",{path:_3e(e),error:t?.message||String(t)}),{}}}function x3e(e){nh.ensureConfigDir();let t=aB(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
|
|
4
|
+
`;ih.writeFileSync(r,n,{mode:384}),ih.renameSync(r,t)}function aZ(e){let t=cB()[e];return typeof t=="string"?t:void 0}function cZ(e){let t=cB()[e];return typeof t=="boolean"?t:void 0}function A3e(e,t){let r=FA[e];if(!r)throw new km(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=cB();return i[e]=n,x3e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:aB()}}function S3e(e){let t=FA[e];if(!t)throw new km(e);let r=cB(),n=e in r;return n&&(delete r[e],x3e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:aB()}}function q0t(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function M0t(){try{let e=sB();return q0t(e.version)}catch{return!1}}function D0t(e){return e.envVar!==void 0&&e.envVar!==""?(oZ(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(oZ(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?U0t:j0t}function Mu(){return D0t({envVar:process.env.VISA_AUTH_URL,settingValue:aZ("auth.serverUrl"),isPrerelease:M0t()})}function T3e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":cZ("ui.suppressBrowser")??!1}var ih,sZ,v3e,w3e,R0t,k0t,FA,km,j0t,U0t,gw=P(()=>{"use strict";ih=Ze(require("fs")),sZ=require("node:net"),v3e=Ze(require("os")),w3e=Ze(require("path"));tZ();Hc();R0t="settings.json",k0t="must use https unless it points at localhost/loopback for local development";FA={"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");oZ(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};km=class extends Error{constructor(t){let r=Object.keys(FA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};j0t="https://auth.visacli.sh",U0t="https://auth-visa-code-preview.up.railway.app"});function uZ(e=V0t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function P3e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ol(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return P3e(t||K0t)}function $A(e){return`${P3e(e)}${W0t}`}var V0t,K0t,W0t,dZ=P(()=>{"use strict";V0t="4.1.0-rc.37",K0t="https://app.visacli.sh",W0t="/agent/enroll"});var Bm,lZ=P(()=>{"use strict";Bm="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function k3e(e){return`${e}-${C3e.randomBytes(24).toString("base64url")}`}function B3e(e=process.env){return e.NODE_ENV==="test"||e[R3e]==="true"}function oh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&B3e(e)}function lB(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&B3e(e)}function pZ(){return`Set ${R3e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function N3e(){return I3e??=k3e("mock-session"),I3e}function j3e(e=process.env){return e.NODE_ENV==="test"?Bm:(O3e??=k3e("mock-rc"),O3e)}var C3e,R3e,I3e,O3e,pB=P(()=>{"use strict";C3e=Ze(require("crypto"));lZ();R3e="VISA_ALLOW_INSECURE_MOCKS"});function J0t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
|
|
5
5
|
`)}function bZ(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=J0t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function ch(){return process.platform!=="darwin"?Promise.resolve(!1):(U3e??=(async()=>{try{return await sl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return bZ(e)}})(),U3e)}async function Y0t(){if(!await ch())return null;try{let{stdout:e}=await sl("security",["find-generic-password","-s",Du,"-a",sh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(bZ(e))throw new mB("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 Z0t(e){if(!await ch())return!1;try{try{await sl("security",["delete-generic-password","-s",Du,"-a",sh],{timeout:5e3})}catch{}return await sl("security",["add-generic-password","-s",Du,"-a",sh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function X0t(){if(await ch())try{await sl("security",["delete-generic-password","-s",Du,"-a",sh],{timeout:5e3})}catch{}}async function Q0t(){if(!_Z())return null;try{let{stdout:e}=await sl("secret-tool",["lookup","service",Du,"account",sh],{timeout:5e3});return e.trim()||null}catch{return null}}async function e1t(e){if(!_Z())return!1;try{let t=(0,hB.execFile)("secret-tool",["store","--label",`${Du} ${sh}`,"service",Du,"account",sh]);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"))},G0t))]),!0):!1}catch{return!1}}async function t1t(){if(_Z())try{await sl("secret-tool",["clear","service",Du,"account",sh],{timeout:5e3})}catch{}}function _Z(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function r1t(){if(!await ch())return null;try{let{stdout:e}=await sl("security",["find-generic-password","-s",Du,"-a",fB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function n1t(e){if(await ch())try{try{await sl("security",["delete-generic-password","-s",Du,"-a",fB],{timeout:5e3})}catch{}await sl("security",["add-generic-password","-s",Du,"-a",fB,"-w",e],{timeout:5e3})}catch{}}async function i1t(){if(await ch())try{await sl("security",["delete-generic-password","-s",Du,"-a",fB],{timeout:5e3})}catch{}}function mZ(){try{return ah.readFileSync(VA,"utf-8").trim()||null}catch(e){if(bZ(e))throw new mB(`Unable to read Visa CLI credentials from ${VA}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function M3e(e){ah.mkdirSync(gZ,{recursive:!0,mode:448}),ah.writeFileSync(VA,e,{mode:384}),process.platform==="win32"&&o1t(VA)}function hZ(){try{ah.unlinkSync(VA)}catch{}}function o1t(e){try{let t=yB.userInfo().username;(0,hB.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 fZ(){switch(process.platform){case"darwin":return{get:Y0t,store:Z0t,delete:X0t};case"linux":return{get:Q0t,store:e1t,delete:t1t};default:return{get:async()=>mZ(),store:async e=>{try{return M3e(e),!0}catch{return!1}},delete:async()=>hZ(),storesInSessionFile:!0}}}var hB,q3e,ah,yB,yZ,sl,gZ,VA,Du,sh,fB,G0t,mB,U3e,zu,KA=P(()=>{"use strict";hB=require("child_process"),q3e=require("util"),ah=Ze(require("fs")),yB=Ze(require("os")),yZ=Ze(require("path"));pB();sl=(0,q3e.promisify)(hB.execFile),gZ=yZ.join(yB.homedir(),".visa-mcp"),VA=yZ.join(gZ,"session-token"),Du="visa-cli",sh="session-token",fB="rc-access",G0t=5e3,mB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};U3e=null;zu=class{static async getSessionToken(){if(oh())return Promise.resolve(N3e());let t=fZ(),r=await t.get();if(r)return r;let n=mZ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(oh())return;let r=fZ();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||hZ();return}await r.delete()}if(M3e(t),mZ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${gZ} is writable.`))}static async getRcAccessToken(){return oh()?j3e():r1t()}static async saveRcAccessToken(t){oh()||await n1t(t)}static async deleteSessionToken(){if(oh())return;await fZ().delete(),hZ()}static async clearAll(){await this.deleteSessionToken(),await i1t()}}});function WA(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 h1t(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(`
|
|
6
6
|
`)}function GA(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 i9e(e,t){let r=GA(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 o9e(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 vB(e,t=process.platform){let r=GA(e);return r?o9e(r,t):null}function r9e(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function wB(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=GA(e),s=t.spawn??((u,d,l)=>{(0,n9e.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 h1t(o??e).split(`
|
|
7
7
|
`))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=WA(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=o9e(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?r9e(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){r9e(r,l instanceof Error?l:new Error(String(l))),u()}})}var n9e,vZ=P(()=>{"use strict";n9e=require("child_process")});function j1t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function k9e(e,t,r=""){let n=j1t(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 f9e(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 U1t(e,t){k9e(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 IZ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function AZ(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function q1t(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 z1t(e,t=!1){return t?{h:Number(e&EB),l:Number(e>>m9e&EB)}:{h:Number(e>>m9e&EB)|0,l:Number(e&EB)|0}}function L1t(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}=z1t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function Um(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function Q1t(){return R1t.randomSecretKey()}function YA(e){return T1t(e)}function CB(){let e=Q1t();return{secretKey:e,publicKey:YA(e)}}function N9e(e){if(e.length!==b9e)throw new Error(`Ed25519 seed must be ${b9e} bytes, got ${e.length}`);return{secretKey:e,publicKey:YA(e)}}function xw(e,t){return O1t(t,e)}function eht(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function tht(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 OZ(e){return eht(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function rht(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return tht(r)}function nht(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Aw(e){let t=YA(e);return{kty:"OKP",crv:"Ed25519",x:OZ(t),d:OZ(e)}}function ph(e){return{kty:"OKP",crv:"Ed25519",x:OZ(e)}}function ZA(e){if(nht(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return rht(e.d)}function q9e(){return XA.default.randomBytes(32).toString("base64url")}function M9e(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return DZ(e)}function oht(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function sht(e){let t=oht(e);return`${t.slice(0,4)}-${t.slice(4)}`}function D9e(){return XA.default.randomBytes(32).toString("base64url")}function MZ(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("claim token must be 32 unpadded base64url bytes");return DZ(`visa-agent-pairing-claim-token:v1:${e}`)}function RB(e,t){MZ(t);let r=XA.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<iht;i+=1)n+=qZ[r[i]&U9e];return sht(n)}function z9e(e){return F9e("visa-agent-pairing-claim:v1",{agentJkt:e.agentJkt,claimTokenHash:e.claimTokenHash,contextLabel:e.runtime.contextLabel,pairingId:e.pairingId,platform:e.runtime.platform??"",runtime:e.runtime.runtime,serverNonce:e.serverNonce,walletPublicKey:e.walletPublicKey})}function L9e(e){return F9e("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function H9e(e){return DZ(`visa-agent-pairing-artifacts:v1:${CZ(e)}`)}function DZ(e){return XA.default.createHash("sha256").update(e,"utf8").digest("base64url")}function F9e(e,t){return`${e}
|
|
@@ -20675,7 +20675,7 @@ ${e.senderName}
|
|
|
20675
20675
|
${e.timestampMs}
|
|
20676
20676
|
${e.messageType}
|
|
20677
20677
|
${t}
|
|
20678
|
-
${e.nonce}`;return T4r.encode(r)}function O4r(e,t,r,n,i,o,s){return I4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function C4r(e){let t=0;for(;t<e.length;){let r=e[t],n=r>>3,i=r&7;if(t++,i===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(i===2){let o=0,s=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<s,s+=7,t++;if(o|=(e[t]&127)<<s,t++,n===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function e8r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Hpt(e,t,r=""){let n=e8r(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 ipt(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 t8r(e,t){Hpt(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 Q4e(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function W4e(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function r8r(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 o8r(e,t=!1){return t?{h:Number(e&rY),l:Number(e>>opt&rY)}:{h:Number(e>>opt&rY)|0,l:Number(e&rY)|0}}function s8r(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}=o8r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function Y1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function b8r(){return Y4r.randomSecretKey()}function $pt(e){return G4r(e)}function _8r(){let e=b8r();return{secretKey:e,publicKey:$pt(e)}}function v8r(e){if((0,c2.existsSync)(e)){let r=(0,c2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:$pt(n)}}let t=_8r();return(0,c2.mkdirSync)((0,dpt.dirname)(e),{recursive:!0}),(0,c2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function w8r(e){let{secretKey:t,publicKey:r}=v8r(e);return{privateKey:t,publicKey:r}}async function E8r(e,t,r,n,i,o,s,a){let c=O4r(t,r,n,i,o,s,a);return{signature:await x4r(e,c),signatureInput:P4r.subwayAgentMsgV1}}function upt(e){return S4r(e)}var c2,dpt,Rwr,kwr,Bwr,Nwr,jwr,lpt,aY,oY,Dlt,zlt,z4e,L4e,Uwr,fY,qwr,_s,Mwr,Dwr,zwr,Z1,mY,e8e,ppt,t8e,W1,Llt,r8e,fpt,Lwr,bA,Hwr,cY,Uv,Pn,Hlt,Ve,mpt,hpt,ypt,gpt,H4e,G4e,Ik,Hv,zv,bpt,_pt,Sm,Fwr,Flt,$wr,J4e,n8e,Vwr,vpt,Kwr,Wwr,Gwr,Jwr,Ywr,Zwr,i8e,wpt,uY,Xwr,Ept,Y4e,Qwr,$lt,Vlt,e4r,Spt,Tpt,r2,na,QJ,Wlt,Glt,Jlt,mA,hA,eY,tY,a4r,c4r,u4r,d4r,l4r,p4r,f4r,n2,m4r,h4r,Ppt,y4r,g4r,i2,o2,b4r,_4r,v4r,w4r,Ylt,A4r,Ipt,T4r,P4r,Opt,R4r,Cpt,dY,sY,Zlt,Xlt,$4e,V4e,k4r,_A,B4r,vs,N4r,j4r,U4r,u2,hY,o8e,Rpt,kpt,J1,Qlt,Bpt,Npt,q4r,s8e,M4r,lY,Mv,$n,ept,Ke,D4r,z4r,jpt,Upt,K4e,Z4e,Ok,vA,Lv,L4r,qpt,Pm,H4r,tpt,F4r,$4r,V4r,K4r,Mpt,W4r,Dpt,G4r,zpt,J4r,Y4r,pY,Z4r,Lpt,X4e,X4r,rpt,npt,Q4r,n8r,i8r,ia,rY,opt,spt,apt,yA,gA,nY,iY,a8r,c8r,u8r,d8r,l8r,p8r,Fpt,f8r,m8r,s2,a2,h8r,y8r,g8r,cpt,x8r,A8r,Vpt,Kpt=P(()=>{"use strict";q4e();q4e();M4e();c2=require("fs"),dpt=require("path");Rwr=1e3,kwr=10,Bwr=3e4,Nwr=3e4,jwr=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Rwr,this.maxReconnectAttempts=e.maxReconnectAttempts??kwr,this.pingInterval=e.pingInterval??Bwr}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let r=Owr();if(!r){t(new ra('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new r(this.url)}catch(i){t(new ra(`Failed to create WebSocket: ${i}`));return}let n=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),n||(n=!0,e())},this.ws.onmessage=i=>{let o;try{o=JSON.parse(typeof i.data=="string"?i.data:i.data.toString())}catch{return}for(let s of this.messageHandlers)s(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),n||(n=!0,t(new ra("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ra(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new ra("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Cwr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Nwr);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},lpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:aY,n:oY,Gx:Dlt,Gy:zlt,a:z4e,d:L4e,h:Uwr}=lpt,fY=32,qwr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw qwr(t,_s),t},Mwr=e=>typeof e=="bigint",Dwr=e=>typeof e=="string",zwr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Z1=(e,t,r="")=>{let n=zwr(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},mY=e=>new Uint8Array(e),e8e=e=>Uint8Array.from(e),ppt=(e,t)=>e.toString(16).padStart(t,"0"),t8e=e=>Array.from(Z1(e)).map(t=>ppt(t,2)).join(""),W1={_0:48,_9:57,A:65,F:70,a:97,f:102},Llt=e=>{if(e>=W1._0&&e<=W1._9)return e-W1._0;if(e>=W1.A&&e<=W1.F)return e-(W1.A-10);if(e>=W1.a&&e<=W1.f)return e-(W1.a-10)},r8e=e=>{let t="hex invalid";if(!Dwr(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=mY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Llt(e.charCodeAt(s)),c=Llt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},fpt=()=>globalThis?.crypto,Lwr=()=>fpt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),bA=(...e)=>{let t=0;for(let i of e)t+=Z1(i).length;let r=mY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Hwr=(e=fY)=>fpt().getRandomValues(mY(e)),cY=BigInt,Uv=(e,t,r,n="bad number: out of range")=>{if(!Mwr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Pn=(e,t=aY)=>{let r=e%t;return r>=0n?r:t+r},Hlt=(1n<<255n)-1n,Ve=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&Hlt);return t=(t>>255n)*19n+(t&Hlt),t%aY},mpt=e=>Pn(e,oY),hpt=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Pn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Pn(i,t):_s("no inverse")},ypt=e=>{let t=wpt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},gpt=e=>Z1(e,64,"digest"),H4e=e=>e instanceof Ik?e:_s("Point expected"),G4e=2n**256n,Ik=class qv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=G4e;this.X=Uv(t,0n,o),this.Y=Uv(r,0n,o),this.Z=Uv(n,1n,o),this.T=Uv(i,0n,o),Object.freeze(this)}static CURVE(){return lpt}static fromAffine(t){return new qv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=L4e,i=e8e(Z1(t,fY)),o=t[31];i[31]=o&-129;let s=_pt(i);Uv(s,0n,r?G4e:aY);let c=Ve(s*s),u=Pn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=$wr(u,d);l||_s("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&_s("bad point: x==0, isLastByteOdd"),m!==f&&(p=Pn(-p)),new qv(p,s,1n,Ve(p*s))}static fromHex(t,r){return qv.fromBytes(r8e(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=z4e,r=L4e,n=this;if(n.is0())return _s("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=Pn(l+Ve(r*Ve(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?_s("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=H4e(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(zv)}negate(){return new qv(Pn(-this.X),this.Y,this.Z,Pn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=z4e,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Pn(t+r),d=Pn(Ve(u*u)-o-s),l=Pn(c+s),p=Pn(l-a),f=Pn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new qv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=H4e(t),d=z4e,l=L4e,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Pn(Ve(Pn(r+n)*Pn(s+a))-p-f),w=Pn(h-m),E=Pn(h+m),_=Pn(f-Ve(d*p)),v=Ve(y*w),x=Ve(E*_),A=Ve(y*_),S=Ve(w*E);return new qv(v,x,S,A)}subtract(t){return this.add(H4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Uv(t,1n,oY),!r&&this.is0()))return zv;if(t===1n)return this;if(this.equals(Hv))return e4r(t).p;let n=zv,i=Hv;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(zv))return{x:0n,y:1n};let i=hpt(n,aY);Ve(n*i)!==1n&&_s("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=bpt(r);return n[31]|=t&1n?128:0,n}toHex(){return t8e(this.toBytes())}clearCofactor(){return this.multiply(cY(Uwr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(oY/2n,!1).double();return oY%2n&&(t=t.add(this)),t.is0()}},Hv=new Ik(Dlt,zlt,1n,Pn(Dlt*zlt)),zv=new Ik(0n,1n,1n,0n);Ik.BASE=Hv;Ik.ZERO=zv;bpt=e=>r8e(ppt(Uv(e,0n,G4e),64)).reverse(),_pt=e=>cY("0x"+t8e(e8e(Z1(e)).reverse())),Sm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Fwr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(Sm(r,2n)*r),i=Ve(Sm(n,1n)*e),o=Ve(Sm(i,5n)*i),s=Ve(Sm(o,10n)*o),a=Ve(Sm(s,20n)*s),c=Ve(Sm(a,40n)*a),u=Ve(Sm(c,80n)*c),d=Ve(Sm(u,80n)*c),l=Ve(Sm(d,10n)*o);return{pow_p_5_8:Ve(Sm(l,2n)*e),b2:r}},Flt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,$wr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Fwr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*Flt),u=s===e,d=s===Pn(-e),l=s===Pn(-e*Flt);return u&&(o=a),(d||l)&&(o=c),(Pn(o)&1n)===1n&&(o=Pn(-o)),{isValid:u||d,value:o}},J4e=e=>mpt(_pt(e)),n8e=(...e)=>Promise.resolve(ypt("sha512Async")(bA(...e))).then(gpt),Vwr=(...e)=>gpt(ypt("sha512")(bA(...e))),vpt=e=>{let t=e8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=J4e(r),o=Hv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Kwr=e=>n8e(Z1(e,fY)).then(vpt),Wwr=e=>vpt(Vwr(Z1(e,fY))),Gwr=e=>Wwr(e).pointBytes,Jwr=e=>n8e(e.hashable).then(e.finish),Ywr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=J4e(t),s=Hv.multiply(o).toBytes();return{hashable:bA(s,n,r),finish:u=>{let d=mpt(o+J4e(u)*i);return Z1(bA(s,bpt(d)),64)}}},Zwr=async(e,t)=>{let r=Z1(e),n=await Kwr(t),i=await n8e(n.prefix,r);return Jwr(Ywr(n,i,r))},i8e=Object.freeze({bytesToHex:t8e,hexToBytes:r8e,concatBytes:bA,mod:Pn,invert:hpt,randomBytes:Hwr}),wpt={sha512Async:async e=>{let t=Lwr(),r=bA(e);return mY(await t.digest("SHA-512",r.buffer))},sha512:void 0},uY=8,Xwr=256,Ept=Math.ceil(Xwr/uY)+1,Y4e=2**(uY-1),Qwr=()=>{let e=[],t=Hv,r=t;for(let n=0;n<Ept;n++){r=t,e.push(r);for(let i=1;i<Y4e;i++)r=r.add(t),e.push(r);t=r.double()}return e},$lt=void 0,Vlt=(e,t)=>{let r=t.negate();return e?r:t},e4r=e=>{let t=$lt||($lt=Qwr()),r=zv,n=Hv,i=2**uY,o=i,s=cY(i-1),a=cY(uY);for(let c=0;c<Ept;c++){let u=Number(e&s);e>>=a,u>Y4e&&(u-=o,e+=1n);let d=c*Y4e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(Vlt(f,t[l])):r=r.add(Vlt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};Spt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Tpt=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=F4e(this.buffer)}update(e){Klt(this),xpt(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=F4e(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){Klt(this),r4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Pk(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=F4e(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()}},r2=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),QJ=BigInt(2**32-1),Wlt=BigInt(32);Glt=(e,t,r)=>e>>>r,Jlt=(e,t,r)=>e<<32-r|t>>>r,mA=(e,t,r)=>e>>>r|t<<32-r,hA=(e,t,r)=>e<<32-r|t>>>r,eY=(e,t,r)=>e<<64-r|t>>>r-32,tY=(e,t,r)=>e>>>r-32|t<<64-r;a4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),c4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,u4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),d4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,l4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),p4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,f4r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),n2=new Uint32Array(64),m4r=class extends Tpt{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)n2[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=n2[d-15],p=n2[d-2],f=Tm(l,7)^Tm(l,18)^l>>>3,m=Tm(p,17)^Tm(p,19)^p>>>10;n2[d]=m+n2[d-7]+f+n2[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Tm(s,6)^Tm(s,11)^Tm(s,25),p=u+l+n4r(s,a,c)+f4r[d]+n2[d]|0,m=(Tm(r,2)^Tm(r,13)^Tm(r,22))+i4r(r,n,i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){Pk(n2)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Pk(this.buffer)}},h4r=class extends m4r{A=r2[0]|0;B=r2[1]|0;C=r2[2]|0;D=r2[3]|0;E=r2[4]|0;F=r2[5]|0;G=r2[6]|0;H=r2[7]|0;constructor(){super(32)}},Ppt=s4r(["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))),y4r=Ppt[0],g4r=Ppt[1],i2=new Uint32Array(80),o2=new Uint32Array(80),b4r=class extends Tpt{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)i2[E]=e.getUint32(t),o2[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=i2[E-15]|0,v=o2[E-15]|0,x=mA(_,v,1)^mA(_,v,8)^Glt(_,v,7),A=hA(_,v,1)^hA(_,v,8)^Jlt(_,v,7),S=i2[E-2]|0,C=o2[E-2]|0,I=mA(S,C,19)^eY(S,C,61)^Glt(S,C,6),R=hA(S,C,19)^tY(S,C,61)^Jlt(S,C,6),q=u4r(A,R,o2[E-7],o2[E-16]),j=d4r(q,x,I,i2[E-7],i2[E-16]);i2[E]=j|0,o2[E]=q|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:w}=this;for(let E=0;E<80;E++){let _=mA(d,l,14)^mA(d,l,18)^eY(d,l,41),v=hA(d,l,14)^hA(d,l,18)^tY(d,l,41),x=d&p^~d&m,A=l&f^~l&h,S=l4r(w,v,A,g4r[E],o2[E]),C=p4r(S,y,_,x,y4r[E],i2[E]),I=S|0,R=mA(r,n,28)^eY(r,n,34)^eY(r,n,39),q=hA(r,n,28)^tY(r,n,34)^tY(r,n,39),j=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=G1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=a4r(I,q,U);r=c4r(B,C,R,j),n=B|0}({h:r,l:n}=G1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=G1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=G1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=G1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=G1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=G1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=G1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=G1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Pk(i2,o2)}destroy(){this.destroyed=!0,Pk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_4r=class extends b4r{Ah=na[0]|0;Al=na[1]|0;Bh=na[2]|0;Bl=na[3]|0;Ch=na[4]|0;Cl=na[5]|0;Dh=na[6]|0;Dl=na[7]|0;Eh=na[8]|0;El=na[9]|0;Fh=na[10]|0;Fl=na[11]|0;Gh=na[12]|0;Gl=na[13]|0;Hh=na[14]|0;Hl=na[15]|0;constructor(){super(64)}},v4r=Apt(()=>new h4r,Spt(1)),w4r=Apt(()=>new _4r,Spt(3)),Ylt=wpt;Ylt.sha512||(Ylt.sha512=e=>w4r(e));A4r=i8e.bytesToHex,Ipt=i8e.hexToBytes;i8e.concatBytes;T4r=new TextEncoder,P4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Ipt("302e020100300506032b657004220420");Ipt("302a300506032b6570032100");Opt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",R4r=Opt.length-1;if((Opt.length&R4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");new TextEncoder;Cpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:dY,n:sY,Gx:Zlt,Gy:Xlt,a:$4e,d:V4e,h:k4r}=Cpt,_A=32,B4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},vs=(e="")=>{let t=new Error(e);throw B4r(t,vs),t},N4r=e=>typeof e=="bigint",j4r=e=>typeof e=="string",U4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,u2=(e,t,r="")=>{let n=U4r(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},hY=e=>new Uint8Array(e),o8e=e=>Uint8Array.from(e),Rpt=(e,t)=>e.toString(16).padStart(t,"0"),kpt=e=>Array.from(u2(e)).map(t=>Rpt(t,2)).join(""),J1={_0:48,_9:57,A:65,F:70,a:97,f:102},Qlt=e=>{if(e>=J1._0&&e<=J1._9)return e-J1._0;if(e>=J1.A&&e<=J1.F)return e-(J1.A-10);if(e>=J1.a&&e<=J1.f)return e-(J1.a-10)},Bpt=e=>{let t="hex invalid";if(!j4r(e))return vs(t);let r=e.length,n=r/2;if(r%2)return vs(t);let i=hY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Qlt(e.charCodeAt(s)),c=Qlt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return vs(t);i[o]=a*16+c}return i},Npt=()=>globalThis?.crypto,q4r=()=>Npt()?.subtle??vs("crypto.subtle must be defined, consider polyfill"),s8e=(...e)=>{let t=0;for(let i of e)t+=u2(i).length;let r=hY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},M4r=(e=_A)=>Npt().getRandomValues(hY(e)),lY=BigInt,Mv=(e,t,r,n="bad number: out of range")=>{if(!N4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},$n=(e,t=dY)=>{let r=e%t;return r>=0n?r:t+r},ept=(1n<<255n)-1n,Ke=e=>{e<0n&&vs("negative coordinate");let t=(e>>255n)*19n+(e&ept);return t=(t>>255n)*19n+(t&ept),t%dY},D4r=e=>$n(e,sY),z4r=(e,t)=>{(e===0n||t<=0n)&&vs("no inverse n="+e+" mod="+t);let r=$n(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?$n(i,t):vs("no inverse")},jpt=e=>{let t=zpt[e];return typeof t!="function"&&vs("hashes."+e+" not set"),t},Upt=e=>u2(e,64,"digest"),K4e=e=>e instanceof Ok?e:vs("Point expected"),Z4e=2n**256n,Ok=class Dv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Z4e;this.X=Mv(t,0n,o),this.Y=Mv(r,0n,o),this.Z=Mv(n,1n,o),this.T=Mv(i,0n,o),Object.freeze(this)}static CURVE(){return Cpt}static fromAffine(t){return new Dv(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=V4e,i=o8e(u2(t,_A)),o=t[31];i[31]=o&-129;let s=qpt(i);Mv(s,0n,r?Z4e:dY);let c=Ke(s*s),u=$n(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=F4r(u,d);l||vs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&vs("bad point: x==0, isLastByteOdd"),m!==f&&(p=$n(-p)),new Dv(p,s,1n,Ke(p*s))}static fromHex(t,r){return Dv.fromBytes(Bpt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=$4e,r=V4e,n=this;if(n.is0())return vs("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ke(i*i),u=Ke(o*o),d=Ke(s*s),l=Ke(d*d),p=Ke(c*t),f=Ke(d*(p+u)),m=$n(l+Ke(r*Ke(c*u)));if(f!==m)return vs("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(s*a);return h!==y?vs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=K4e(t),c=Ke(r*a),u=Ke(o*i),d=Ke(n*a),l=Ke(s*i);return c===u&&d===l}is0(){return this.equals(Lv)}negate(){return new Dv($n(-this.X),this.Y,this.Z,$n(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=$4e,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=$n(t+r),d=$n(Ke(u*u)-o-s),l=$n(c+s),p=$n(l-a),f=$n(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Dv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=K4e(t),d=$4e,l=V4e,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=$n(Ke($n(r+n)*$n(s+a))-p-f),w=$n(h-m),E=$n(h+m),_=$n(f-Ke(d*p)),v=Ke(y*w),x=Ke(E*_),A=Ke(y*_),S=Ke(w*E);return new Dv(v,x,S,A)}subtract(t){return this.add(K4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Mv(t,1n,sY),!r&&this.is0()))return Lv;if(t===1n)return this;if(this.equals(vA))return Q4r(t).p;let n=Lv,i=vA;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(Lv))return{x:0n,y:1n};let i=z4r(n,dY);Ke(n*i)!==1n&&vs("invalid inverse");let o=Ke(t*i),s=Ke(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=L4r(r);return n[31]|=t&1n?128:0,n}toHex(){return kpt(this.toBytes())}clearCofactor(){return this.multiply(lY(k4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(sY/2n,!1).double();return sY%2n&&(t=t.add(this)),t.is0()}},vA=new Ok(Zlt,Xlt,1n,$n(Zlt*Xlt)),Lv=new Ok(0n,1n,1n,0n);Ok.BASE=vA;Ok.ZERO=Lv;L4r=e=>Bpt(Rpt(Mv(e,0n,Z4e),64)).reverse(),qpt=e=>lY("0x"+kpt(o8e(u2(e)).reverse())),Pm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},H4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Pm(r,2n)*r),i=Ke(Pm(n,1n)*e),o=Ke(Pm(i,5n)*i),s=Ke(Pm(o,10n)*o),a=Ke(Pm(s,20n)*s),c=Ke(Pm(a,40n)*a),u=Ke(Pm(c,80n)*c),d=Ke(Pm(u,80n)*c),l=Ke(Pm(d,10n)*o);return{pow_p_5_8:Ke(Pm(l,2n)*e),b2:r}},tpt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,F4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=H4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*tpt),u=s===e,d=s===$n(-e),l=s===$n(-e*tpt);return u&&(o=a),(d||l)&&(o=c),($n(o)&1n)===1n&&(o=$n(-o)),{isValid:u||d,value:o}},$4r=e=>D4r(qpt(e)),V4r=(...e)=>Promise.resolve(jpt("sha512Async")(s8e(...e))).then(Upt),K4r=(...e)=>Upt(jpt("sha512")(s8e(...e))),Mpt=e=>{let t=o8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=$4r(r),o=vA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},W4r=e=>V4r(u2(e,_A)).then(Mpt),Dpt=e=>Mpt(K4r(u2(e,_A))),G4r=e=>Dpt(e).pointBytes,zpt={sha512Async:async e=>{let t=q4r(),r=s8e(e);return hY(await t.digest("SHA-512",r.buffer))},sha512:void 0},J4r=e=>(e=e===void 0?M4r(_A):e,u2(e,_A)),Y4r=Object.freeze({getExtendedPublicKeyAsync:W4r,getExtendedPublicKey:Dpt,randomSecretKey:J4r}),pY=8,Z4r=256,Lpt=Math.ceil(Z4r/pY)+1,X4e=2**(pY-1),X4r=()=>{let e=[],t=vA,r=t;for(let n=0;n<Lpt;n++){r=t,e.push(r);for(let i=1;i<X4e;i++)r=r.add(t),e.push(r);t=r.double()}return e},rpt=void 0,npt=(e,t)=>{let r=t.negate();return e?r:t},Q4r=e=>{let t=rpt||(rpt=X4r()),r=Lv,n=vA,i=2**pY,o=i,s=lY(i-1),a=lY(pY);for(let c=0;c<Lpt;c++){let u=Number(e&s);e>>=a,u>X4e&&(u-=o,e+=1n);let d=c*X4e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(npt(f,t[l])):r=r.add(npt(m,t[p]))}return e!==0n&&vs("invalid wnaf"),{p:r,f:n}};n8r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),i8r=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=W4e(this.buffer)}update(e){ipt(this),Hpt(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=W4e(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){ipt(this),t8r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Q4e(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=W4e(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()}},ia=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),rY=BigInt(2**32-1),opt=BigInt(32);spt=(e,t,r)=>e>>>r,apt=(e,t,r)=>e<<32-r|t>>>r,yA=(e,t,r)=>e>>>r|t<<32-r,gA=(e,t,r)=>e<<32-r|t>>>r,nY=(e,t,r)=>e<<64-r|t>>>r-32,iY=(e,t,r)=>e>>>r-32|t<<64-r;a8r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),c8r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,u8r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),d8r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,l8r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),p8r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Fpt=s8r(["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))),f8r=Fpt[0],m8r=Fpt[1],s2=new Uint32Array(80),a2=new Uint32Array(80),h8r=class extends i8r{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)s2[E]=e.getUint32(t),a2[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=s2[E-15]|0,v=a2[E-15]|0,x=yA(_,v,1)^yA(_,v,8)^spt(_,v,7),A=gA(_,v,1)^gA(_,v,8)^apt(_,v,7),S=s2[E-2]|0,C=a2[E-2]|0,I=yA(S,C,19)^nY(S,C,61)^spt(S,C,6),R=gA(S,C,19)^iY(S,C,61)^apt(S,C,6),q=u8r(A,R,a2[E-7],a2[E-16]),j=d8r(q,x,I,s2[E-7],s2[E-16]);s2[E]=j|0,a2[E]=q|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:w}=this;for(let E=0;E<80;E++){let _=yA(d,l,14)^yA(d,l,18)^nY(d,l,41),v=gA(d,l,14)^gA(d,l,18)^iY(d,l,41),x=d&p^~d&m,A=l&f^~l&h,S=l8r(w,v,A,m8r[E],a2[E]),C=p8r(S,y,_,x,f8r[E],s2[E]),I=S|0,R=yA(r,n,28)^nY(r,n,34)^nY(r,n,39),q=gA(r,n,28)^iY(r,n,34)^iY(r,n,39),j=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=Y1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=a8r(I,q,U);r=c8r(B,C,R,j),n=B|0}({h:r,l:n}=Y1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Y1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Y1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Y1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Y1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=Y1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Y1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=Y1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Q4e(s2,a2)}destroy(){this.destroyed=!0,Q4e(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},y8r=class extends h8r{Ah=ia[0]|0;Al=ia[1]|0;Bh=ia[2]|0;Bl=ia[3]|0;Ch=ia[4]|0;Cl=ia[5]|0;Dh=ia[6]|0;Dl=ia[7]|0;Eh=ia[8]|0;El=ia[9]|0;Fh=ia[10]|0;Fl=ia[11]|0;Gh=ia[12]|0;Gl=ia[13]|0;Hh=ia[14]|0;Hl=ia[15]|0;constructor(){super(64)}},g8r=r8r(()=>new y8r,n8r(3)),cpt=zpt;cpt.sha512||(cpt.sha512=e=>g8r(e));x8r="ws://localhost:9001/ws",A8r=3e4,Vpt=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=Tk(e.name),e.keyPath)try{this._keypair=w8r(e.keyPath)}catch{}this.options={name:this._name,url:e.url??x8r,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??A8r,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new jwr({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),r=C4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:E4r(r)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let r={type:"register",name:this._name};this.options.relay&&(r.relay=this.options.relay),this._keypair&&(r.public_key=upt(this._keypair.publicKey)),this.options.binding&&(r.binding=this.options.binding);try{this.transport.send(r)}catch(n){this.registerPromise=null,t(n instanceof Error?n:new ra(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ra("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ra("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ra("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ra("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=Tk(e),o=D4e();return new Promise((s,a)=>{this.pendingSend.set(i,{resolve:s,reject:a});try{this.transport.send({type:"send",to:i,message_type:t,payload:r,metadata:n})}catch(c){this.pendingSend.delete(i),a(c instanceof Error?c:new ra(String(c)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),s({messageId:o,to:i}))},5e3)})}async sendSigned(e,t,r,n){if(!this._keypair||!this._peerId)return this.send(e,t,r,n);let i=Tk(e),o=D4e(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await E8r(this._keypair.privateKey,o,this._peerId,this._name,s,t,c,a);return new Promise((l,p)=>{this.pendingSend.set(i,{resolve:l,reject:p});try{this.transport.send({type:"send_signed",to:i,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:s,message_type:t,payload:r,metadata:n,signature:Buffer.from(u).toString("base64"),signature_input:d,nonce:a})}catch(f){this.pendingSend.delete(i),p(f instanceof Error?f:new ra(String(f)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),l({messageId:o,to:i}))},5e3)})}async call(e,t,r,n){let i=Tk(e),o=n?.correlationId??D4e(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new Sk(`RPC call to ${i}.${t} timed out after ${s}ms`))},s);this.pendingCalls.set(o,{resolve:a,reject:c,timer:u});try{this.transport.send({type:"call",to:i,method:t,payload:r??"",correlation_id:o})}catch(d){clearTimeout(u),this.pendingCalls.delete(o),c(d instanceof Error?d:new ra(String(d)))}})}async broadcast(e,t,r){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:r})}subscribe(e,t){let r=this.topicHandlers.get(e);if(!r){r=new Set,this.topicHandlers.set(e,r);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return r.add(t),()=>{r.delete(t),r.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=Tk(e);return new Promise((r,n)=>{this.pendingResolve.set(t,{resolve:r,reject:n});try{this.transport.send({type:"resolve",name:t})}catch(i){this.pendingResolve.delete(t),n(i instanceof Error?i:new ra(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new Sk(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>r.delete(t)}off(e,t){let r=this.eventListeners.get(e);r&&r.delete(t)}emit(e,...t){let r=this.eventListeners.get(e);if(r)for(let n of r)try{n(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let r of this.messageHandlers)try{r(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},r=this.topicHandlers.get(e.topic);if(r)for(let n of r)try{n(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=U4e(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new XJ(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},r=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,n;if(!r)n={success:!1,error:`No handler for method: ${e.method}`};else try{n=await r(t)}catch(i){n={success:!1,error:i instanceof Error?i.message:String(i)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:n.success,payload:n.payload??"",error:n.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=upt(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});var f8e={};ki(f8e,{SUBWAY_PROTOCOL:()=>nft,registerDirect:()=>q8r,resolveDirect:()=>M8r});function u8e(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 Yd(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 d8e(e,t){return e<<3|t}function Ck(e,t,r){e.push(d8e(t,2)),u8e(e,r.length);for(let n of r)e.push(n)}function S8r(e,t){let r=[];return Ck(r,1,c8e.encode(e)),t&&t.length>0&&Ck(r,2,c8e.encode(t)),Uint8Array.from(r)}function T8r(e,t,r){let n=[];return r!==0n&&(n.push(d8e(1,0)),u8e(n,r)),Ck(n,2,S8r(e,t)),Uint8Array.from(n)}function P8r(e){let t=[];return Ck(t,1,c8e.encode(e)),Uint8Array.from(t)}function I8r(e,t){let r=[];return t!==0n&&(r.push(d8e(1,0)),u8e(r,t)),Ck(r,3,P8r(e)),Uint8Array.from(r)}function O8r(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Yd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.error=tft.decode(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function C8r(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Yd(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]=Yd(e,t),u=c,d=u+Number(a);r.error=tft.decode(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function l8e(e,t,r){if(r===0)return Yd(e,t)[1];if(r===2){let[n,i]=Yd(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 rft(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Yd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.registerNameResponse=O8r(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=C8r(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function R8r(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function p8e(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function k8r(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=p8e(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:rft(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function B8r(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=p8e(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:rft(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function a8e(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 U8r(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>Wpt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+p8e(a8e(t).subarray(0,4)),n>Wpt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return a8e(t).subarray(0,n)}return a8e(t)}async function ift(e){return(0,Gpt.createLibp2p)({...e?{privateKey:await(0,Xpt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Jpt.tcp)()],connectionEncrypters:[(0,Ypt.noise)()],streamMuxers:[(0,Zpt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function oft(e,t,r){let n=await e.dialProtocol((0,Qpt.multiaddr)(t),nft,{signal:AbortSignal.timeout(N8r)});n.send(R8r(r));let i;return Promise.race([U8r(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),j8r)})]).finally(()=>clearTimeout(i))}async function q8r(e){let t=await ift(e.seed);try{let r=await oft(t,e.relayMultiaddr,T8r(e.name,e.binding,e.requestId??1n)),n=k8r(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function M8r(e){let t=await ift(e.seed);try{let r=await oft(t,e.relayMultiaddr,I8r(e.name,e.requestId??1n)),n=B8r(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,eft.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Gpt,Jpt,Ypt,Zpt,Xpt,Qpt,eft,c8e,tft,nft,N8r,j8r,Wpt,m8e=P(()=>{"use strict";M4e();Gpt=require("libp2p"),Jpt=require("@libp2p/tcp"),Ypt=require("@chainsafe/libp2p-noise"),Zpt=require("@chainsafe/libp2p-yamux"),Xpt=require("@libp2p/crypto/keys"),Qpt=require("@multiformats/multiaddr"),eft=require("uint8arrays/to-string"),c8e=new TextEncoder,tft=new TextDecoder;nft="/subway/p2p/1.0.0",N8r=15e3,j8r=15e3,Wpt=1<<20});var kk={};ki(kk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>aft,MESH:()=>ws,RELAY_URL:()=>v8e,connectOrThrow:()=>_Y,ensureMailbox:()=>T8e,isSubwayEnabled:()=>w8e,listRegistered:()=>F8r,loadBindingFor:()=>A8e,loadRegistry:()=>Fv,makeClient:()=>bY,maybeMintVisaBinding:()=>uft,meshName:()=>vp,pairedVisaBinding:()=>dft,readInbox:()=>V8r,registerName:()=>S8e,resolveActingName:()=>z8r,resolveMeshName:()=>L8r,seedSubwayKeyFromTapAgent:()=>cft,sendMessage:()=>H8r,sendVia:()=>K8r,subwayKeyPath:()=>gY,visaRelayMultiaddr:()=>_8e});function _8e(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??aft}function vp(e){return e.includes(".")?e:`${e}.${ws}`}function w8e(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 x8e(){uo.mkdirSync(E8e,{recursive:!0,mode:448})}function D8r(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function gY(e){return wA.join(E8e,`${D8r(e)}.key`)}function Fv(){if(!uo.existsSync(b8e))return{};try{return JSON.parse(uo.readFileSync(b8e,"utf8"))}catch{return{}}}function y8e(e){x8e(),uo.writeFileSync(b8e,JSON.stringify(e,null,2),{mode:384})}function g8e(){try{return Rk.userInfo().username}catch{return"local"}}function cft(e){if(uo.existsSync(e)||!uo.existsSync(h8e))return null;let t=uo.readdirSync(h8e).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>wA.join(h8e,n)).sort((n,i)=>uo.statSync(i).mtimeMs-uo.statSync(n).mtimeMs)[0];try{let n=JSON.parse(uo.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=ZA(n.private_key_jwk);return x8e(),uo.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function bY(e,t={}){return new Vpt({name:vp(e),url:v8e,keyPath:gY(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function A8e(e){if(ws!=="visa")return;let t=Fv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function _Y(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${v8e})`)),t))])}function z8r(e){if(e)return e;let t=Object.keys(Fv());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>.`)}async function uft(e){if(ws!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new E2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await zZ({authUrl:Mu(),apiKey:t,seed:BB(gY(e)),name:vp(e)})}catch(r){if(r instanceof E2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function dft(e=Date.now()){let t=P8e();if(!t?.binding_jwt)return null;let r=Bk(t.binding_jwt);if(!r||r.mesh!=="visa")return null;let n=typeof r.exp=="number"?r.exp:NaN;return!Number.isFinite(n)||n*1e3<=e?null:{binding:t.binding_jwt,bindingExpiresAt:new Date(n*1e3).toISOString()}}async function S8e(e){let t=gY(e),r=cft(t),n=vp(e);ws==="visa"&&!uo.existsSync(t)&&(x8e(),uo.writeFileSync(t,(0,sft.randomBytes)(32),{mode:384}));let i=ws==="visa"?dft():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await uft(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=ws==="visa"?_8e():process.env.SUBWAY_RELAY_MULTIADDR;if(ws==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(m8e(),f8e)),d=await u({relayMultiaddr:a,seed:BB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=Fv();return l[e]={relayName:n,mesh:ws,peerId:d.peerId,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(l),{relayName:n,mesh:ws,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(ws==="visa"&&!process.env.SUBWAY_RELAY){let u=Fv();return u[e]={relayName:n,mesh:ws,peerId:null,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(u),{relayName:n,mesh:ws,peerId:null,tapAgentId:r,...o?{binding:o}:{},note:o?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding; pair/enroll this agent, or set VISA_CLI_API_KEY (card on file), for a .visa binding."}}let c=bY(e,{autoReconnect:!1,binding:o});try{await _Y(c);let u=Fv();return u[e]={relayName:n,mesh:ws,peerId:c.peerId,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(u),{relayName:n,mesh:ws,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function L8r(e){let t=vp(e),r=ws==="visa"?_8e():process.env.SUBWAY_RELAY_MULTIADDR;if(ws==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(m8e(),f8e)),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 H8r(e,t,r){let n=bY(e,{autoReconnect:!1,binding:A8e(e)});try{await _Y(n);let i=vp(t);return await n.sendSigned(i,"chat",r),{to:i,as:vp(e)}}finally{n.disconnect()}}function F8r(){let e=Fv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function T8e(e){let t=yY.get(e);if(t)return{relayName:vp(e),peerId:t.client.peerId};let r=bY(e,{autoReconnect:!0,binding:A8e(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>$8r&&n.shift()}),yY.set(e,{client:r,buffer:n}),await _Y(r),{relayName:vp(e),peerId:r.peerId}}async function V8r(e,t=20,r=!1){await T8e(e);let n=yY.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function K8r(e,t,r){await T8e(e);let n=yY.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=vp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:vp(e)}}var uo,Rk,wA,sft,ws,aft,v8e,E8e,b8e,h8e,yY,$8r,$v=P(()=>{"use strict";Kpt();w2();uo=Ze(require("fs")),Rk=Ze(require("os")),wA=Ze(require("path")),sft=require("crypto");gw();QA();vY();ws=process.env.SUBWAY_MESH??"relay",aft="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";v8e=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";E8e=wA.join(Rk.homedir(),".visa-cli","subway"),b8e=wA.join(E8e,"registry.json"),h8e=wA.join(Rk.homedir(),".visa-cli","agents");yY=new Map,$8r=200});var mft={};ki(mft,{PAIRING_DIR:()=>xA,cancelPairing:()=>C8e,claimPairing:()=>TY,generateWalletCredential:()=>yk,getPairingStatus:()=>SY,initiatePairing:()=>AY,latestPendingHumanPairing:()=>xY,loadPairingMailbox:()=>pft,pairingFilePath:()=>EY,pollAndActivatePairing:()=>Uk,readPendingPairing:()=>Nk,registerOnVisaMeshIfEnabled:()=>wY,removePendingPairing:()=>AA,verifyPairing:()=>jk,writePendingPairing:()=>O8e});async function wY(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await S8e(e),!0}catch(t){return Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function pft(e=process.env.VISA_V4_HOME||EA.join(I8e.homedir(),".visa-v4")){try{let t=Dc.readFileSync(EA.join(e,"identity","mailbox.json"),"utf8"),r=JSON.parse(t);return typeof r.email!="string"||!r.email.includes("@")||typeof r.inboxId!="string"||r.inboxId.length===0?null:{email:r.email,inboxId:r.inboxId}}catch{return null}}function EY(e,t,r=xA){return EA.join(r,`${e}.${t}.json`)}function O8e(e,t=xA){Dc.mkdirSync(t,{recursive:!0,mode:448}),Dc.writeFileSync(EY(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function AA(e,t,r=xA){Dc.rmSync(EY(e,t,r),{force:!0})}function Nk(e,t,r=xA){try{let n=JSON.parse(Dc.readFileSync(EY(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function xY(e=xA){return Dc.existsSync(e)?Dc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(Dc.readFileSync(EA.join(e,r),"utf8"))}catch{return null}}).filter(r=>r?.role==="human").sort((r,n)=>n.createdAt.localeCompare(r.createdAt))[0]??null:null}async function Vv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":lft,...t.headers??{}}}),i=await n.json().catch(()=>({}));if(!n.ok&&n.status!==202)throw new Error(i.error??i.detail??`pairing server returned ${n.status}`);return{status:n.status,body:i}}async function AY(e={}){let t=(e.authUrl??Mu()).replace(/\/+$/,""),r=q9e(),n=pft(),{body:i}=await Vv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:M9e(r),...n?{mailbox:n}:{}})},e.fetchImpl??fetch);if(!i.pairingId||!i.skillUrl||!i.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let o={role:"human",pairingId:i.pairingId,verifier:r,authUrl:t,skillUrl:i.skillUrl,expiresAt:i.expiresAt,createdAt:new Date().toISOString()};return O8e(o,e.pairingDir),o}async function jk(e){let{pairing:t}=e,{body:r}=await Vv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return r}async function SY(e){let t=(e.authUrl??Mu()).replace(/\/+$/,""),{body:r}=await Vv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function fft(e,t){return Buffer.from(xw(e,Buffer.from(t,"utf8"))).toString("base64url")}async function TY(e){let t=(e.authUrl??Mu()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await SY({pairingId:e.pairingId,authUrl:t,fetchImpl:r});if(n.state!=="awaiting_agent"||!n.serverNonce)throw new Error(`pairing cannot be claimed from state ${n.state}`);let i,o,s;if(e.existingCredential)s=e.existingCredential.privateKeyJwk,o=e.existingCredential.publicKeyJwk,i=Buffer.from(s.d,"base64url");else{let m=CB();i=m.secretKey,s=Aw(i),o=ph(m.publicKey)}let a=Sw(o),c=yk(),u=D9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:lft},l=fft(i,z9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:MZ(u),agentJkt:a,walletPublicKey:c.publicKey,runtime:d})),p={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:a,publicKeyJwk:o,privateKeyJwk:s,walletPublicKey:c.publicKey,walletPrivateKey:c.privateKey,createdAt:new Date().toISOString()};O8e(p,e.pairingDir);let{body:f}=await Vv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:o,walletPublicKey:c.publicKey,runtime:d,signature:l,claimToken:u})},r);if(!f.verificationCode||f.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(f.verificationCode!==RB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function Uk(e){let t=e.fetchImpl??fetch,r=e.wait??(o=>new Promise(s=>setTimeout(s,o))),n=e.maxPolls??450,i="";for(let o=0;o<n;o+=1){let{body:s,status:a}=await Vv(`${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);if(s.state!==i&&(i=s.state,e.onState?.(s.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(s.state))throw new Error(`pairing ended in state ${s.state}`);await r(e.pollIntervalMs??2e3);continue}if(!s.artifacts||!s.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=s.artifacts,u=c.terms?.name,d=c.wallet?.turnkey,l=c.terms?.mode==="wallet"||c.terms?.mode==="both",p=KJ(d?.network);if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof u!="string"||c.wallet?.credentialPublicKey!==e.pending.walletPublicKey||l&&(!d||typeof d.organizationId!="string"||typeof d.walletId!="string"||typeof d.address!="string"||!/^0x[0-9a-f]{40}$/i.test(d.address)||!p||!Number.isSafeInteger(c.terms?.dailyLimitCents)||!Number.isSafeInteger(c.terms?.perTransactionLimitCents))||H9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=fft(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),L9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await Vv(`${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({signature:f})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let h={agent_jkt:e.pending.agentJkt,name:u,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:s.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return l&&d&&await VJ({apiPublicKey:e.pending.walletPublicKey,apiPrivateKey:e.pending.walletPrivateKey,organizationId:d.organizationId,walletId:d.walletId,address:d.address,network:p,perTransactionLimitCents:c.terms?.perTransactionLimitCents,dailyLimitCents:c.terms?.dailyLimitCents,...e.walletHome?{homeDir:e.walletHome}:{}}),k8e(h,e.agentDir),await wY(u),AA(e.pending.pairingId,"runtime",e.pairingDir),{record:h,name:u,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function C8e(e){let{pairing:t}=e,{body:r}=await Vv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return r.state==="cancelled"&&AA(t.pairingId,"human",e.pairingDir),r}var Dc,I8e,EA,lft,xA,R8e=P(()=>{"use strict";Dc=Ze(require("node:fs")),I8e=Ze(require("node:os")),EA=Ze(require("node:path"));w2();QA();$v();gw();Hc();v4e();vY();lft="4.1.0-rc.36",xA=EA.join(I8e.homedir(),".visa-cli","pairings")});var Eft={};ki(Eft,{agentFilePath:()=>Mk,agentFormatIsJson:()=>qk,attachAgentCommand:()=>Z8r,claimOptsFromFlags:()=>j8e,decodeBindingClaims:()=>Bk,enrollClaimEnvelope:()=>vft,isAgentCommandEnabled:()=>_ft,isAgentRecord:()=>Dk,listAgentFiles:()=>PY,newestAgentRecord:()=>P8e,readAgent:()=>U8e,resolveAgentByRef:()=>wft,writeAgent:()=>k8e});function Dk(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function _ft(){return!0}function qk(e){return e==="json"}function vft(e){switch(e.status){case"claimed":return{json:{status:"claimed",...e.name?{name:e.name}:{},tokenId:e.tokenId,credentialPath:e.credentialPath,keyBound:e.keyBound,sessionSaved:e.sessionSaved,walletProvisioned:e.walletProvisioned},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute enrollment window has likely expired":"not ready yet \u2014 finish the browser flow through the final minted screen"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no enrollment hand-off in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this enrollment hand-off did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function j8e(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function B8e(e){return`${e.opened?`\u2713 Enrollment link opened in your browser.
|
|
20678
|
+
${e.nonce}`;return T4r.encode(r)}function O4r(e,t,r,n,i,o,s){return I4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function C4r(e){let t=0;for(;t<e.length;){let r=e[t],n=r>>3,i=r&7;if(t++,i===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(i===2){let o=0,s=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<s,s+=7,t++;if(o|=(e[t]&127)<<s,t++,n===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function e8r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Hpt(e,t,r=""){let n=e8r(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 ipt(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 t8r(e,t){Hpt(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 Q4e(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function W4e(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function r8r(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 o8r(e,t=!1){return t?{h:Number(e&rY),l:Number(e>>opt&rY)}:{h:Number(e>>opt&rY)|0,l:Number(e&rY)|0}}function s8r(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}=o8r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function Y1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function b8r(){return Y4r.randomSecretKey()}function $pt(e){return G4r(e)}function _8r(){let e=b8r();return{secretKey:e,publicKey:$pt(e)}}function v8r(e){if((0,c2.existsSync)(e)){let r=(0,c2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:$pt(n)}}let t=_8r();return(0,c2.mkdirSync)((0,dpt.dirname)(e),{recursive:!0}),(0,c2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function w8r(e){let{secretKey:t,publicKey:r}=v8r(e);return{privateKey:t,publicKey:r}}async function E8r(e,t,r,n,i,o,s,a){let c=O4r(t,r,n,i,o,s,a);return{signature:await x4r(e,c),signatureInput:P4r.subwayAgentMsgV1}}function upt(e){return S4r(e)}var c2,dpt,Rwr,kwr,Bwr,Nwr,jwr,lpt,aY,oY,Dlt,zlt,z4e,L4e,Uwr,fY,qwr,_s,Mwr,Dwr,zwr,Z1,mY,e8e,ppt,t8e,W1,Llt,r8e,fpt,Lwr,bA,Hwr,cY,Uv,Pn,Hlt,Ve,mpt,hpt,ypt,gpt,H4e,G4e,Ik,Hv,zv,bpt,_pt,Sm,Fwr,Flt,$wr,J4e,n8e,Vwr,vpt,Kwr,Wwr,Gwr,Jwr,Ywr,Zwr,i8e,wpt,uY,Xwr,Ept,Y4e,Qwr,$lt,Vlt,e4r,Spt,Tpt,r2,na,QJ,Wlt,Glt,Jlt,mA,hA,eY,tY,a4r,c4r,u4r,d4r,l4r,p4r,f4r,n2,m4r,h4r,Ppt,y4r,g4r,i2,o2,b4r,_4r,v4r,w4r,Ylt,A4r,Ipt,T4r,P4r,Opt,R4r,Cpt,dY,sY,Zlt,Xlt,$4e,V4e,k4r,_A,B4r,vs,N4r,j4r,U4r,u2,hY,o8e,Rpt,kpt,J1,Qlt,Bpt,Npt,q4r,s8e,M4r,lY,Mv,$n,ept,Ke,D4r,z4r,jpt,Upt,K4e,Z4e,Ok,vA,Lv,L4r,qpt,Pm,H4r,tpt,F4r,$4r,V4r,K4r,Mpt,W4r,Dpt,G4r,zpt,J4r,Y4r,pY,Z4r,Lpt,X4e,X4r,rpt,npt,Q4r,n8r,i8r,ia,rY,opt,spt,apt,yA,gA,nY,iY,a8r,c8r,u8r,d8r,l8r,p8r,Fpt,f8r,m8r,s2,a2,h8r,y8r,g8r,cpt,x8r,A8r,Vpt,Kpt=P(()=>{"use strict";q4e();q4e();M4e();c2=require("fs"),dpt=require("path");Rwr=1e3,kwr=10,Bwr=3e4,Nwr=3e4,jwr=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Rwr,this.maxReconnectAttempts=e.maxReconnectAttempts??kwr,this.pingInterval=e.pingInterval??Bwr}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let r=Owr();if(!r){t(new ra('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new r(this.url)}catch(i){t(new ra(`Failed to create WebSocket: ${i}`));return}let n=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),n||(n=!0,e())},this.ws.onmessage=i=>{let o;try{o=JSON.parse(typeof i.data=="string"?i.data:i.data.toString())}catch{return}for(let s of this.messageHandlers)s(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),n||(n=!0,t(new ra("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ra(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new ra("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Cwr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Nwr);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},lpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:aY,n:oY,Gx:Dlt,Gy:zlt,a:z4e,d:L4e,h:Uwr}=lpt,fY=32,qwr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw qwr(t,_s),t},Mwr=e=>typeof e=="bigint",Dwr=e=>typeof e=="string",zwr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Z1=(e,t,r="")=>{let n=zwr(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},mY=e=>new Uint8Array(e),e8e=e=>Uint8Array.from(e),ppt=(e,t)=>e.toString(16).padStart(t,"0"),t8e=e=>Array.from(Z1(e)).map(t=>ppt(t,2)).join(""),W1={_0:48,_9:57,A:65,F:70,a:97,f:102},Llt=e=>{if(e>=W1._0&&e<=W1._9)return e-W1._0;if(e>=W1.A&&e<=W1.F)return e-(W1.A-10);if(e>=W1.a&&e<=W1.f)return e-(W1.a-10)},r8e=e=>{let t="hex invalid";if(!Dwr(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=mY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Llt(e.charCodeAt(s)),c=Llt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},fpt=()=>globalThis?.crypto,Lwr=()=>fpt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),bA=(...e)=>{let t=0;for(let i of e)t+=Z1(i).length;let r=mY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Hwr=(e=fY)=>fpt().getRandomValues(mY(e)),cY=BigInt,Uv=(e,t,r,n="bad number: out of range")=>{if(!Mwr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Pn=(e,t=aY)=>{let r=e%t;return r>=0n?r:t+r},Hlt=(1n<<255n)-1n,Ve=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&Hlt);return t=(t>>255n)*19n+(t&Hlt),t%aY},mpt=e=>Pn(e,oY),hpt=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Pn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Pn(i,t):_s("no inverse")},ypt=e=>{let t=wpt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},gpt=e=>Z1(e,64,"digest"),H4e=e=>e instanceof Ik?e:_s("Point expected"),G4e=2n**256n,Ik=class qv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=G4e;this.X=Uv(t,0n,o),this.Y=Uv(r,0n,o),this.Z=Uv(n,1n,o),this.T=Uv(i,0n,o),Object.freeze(this)}static CURVE(){return lpt}static fromAffine(t){return new qv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=L4e,i=e8e(Z1(t,fY)),o=t[31];i[31]=o&-129;let s=_pt(i);Uv(s,0n,r?G4e:aY);let c=Ve(s*s),u=Pn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=$wr(u,d);l||_s("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&_s("bad point: x==0, isLastByteOdd"),m!==f&&(p=Pn(-p)),new qv(p,s,1n,Ve(p*s))}static fromHex(t,r){return qv.fromBytes(r8e(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=z4e,r=L4e,n=this;if(n.is0())return _s("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=Pn(l+Ve(r*Ve(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?_s("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=H4e(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(zv)}negate(){return new qv(Pn(-this.X),this.Y,this.Z,Pn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=z4e,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Pn(t+r),d=Pn(Ve(u*u)-o-s),l=Pn(c+s),p=Pn(l-a),f=Pn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new qv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=H4e(t),d=z4e,l=L4e,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Pn(Ve(Pn(r+n)*Pn(s+a))-p-f),w=Pn(h-m),E=Pn(h+m),_=Pn(f-Ve(d*p)),v=Ve(y*w),x=Ve(E*_),A=Ve(y*_),S=Ve(w*E);return new qv(v,x,S,A)}subtract(t){return this.add(H4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Uv(t,1n,oY),!r&&this.is0()))return zv;if(t===1n)return this;if(this.equals(Hv))return e4r(t).p;let n=zv,i=Hv;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(zv))return{x:0n,y:1n};let i=hpt(n,aY);Ve(n*i)!==1n&&_s("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=bpt(r);return n[31]|=t&1n?128:0,n}toHex(){return t8e(this.toBytes())}clearCofactor(){return this.multiply(cY(Uwr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(oY/2n,!1).double();return oY%2n&&(t=t.add(this)),t.is0()}},Hv=new Ik(Dlt,zlt,1n,Pn(Dlt*zlt)),zv=new Ik(0n,1n,1n,0n);Ik.BASE=Hv;Ik.ZERO=zv;bpt=e=>r8e(ppt(Uv(e,0n,G4e),64)).reverse(),_pt=e=>cY("0x"+t8e(e8e(Z1(e)).reverse())),Sm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Fwr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(Sm(r,2n)*r),i=Ve(Sm(n,1n)*e),o=Ve(Sm(i,5n)*i),s=Ve(Sm(o,10n)*o),a=Ve(Sm(s,20n)*s),c=Ve(Sm(a,40n)*a),u=Ve(Sm(c,80n)*c),d=Ve(Sm(u,80n)*c),l=Ve(Sm(d,10n)*o);return{pow_p_5_8:Ve(Sm(l,2n)*e),b2:r}},Flt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,$wr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Fwr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*Flt),u=s===e,d=s===Pn(-e),l=s===Pn(-e*Flt);return u&&(o=a),(d||l)&&(o=c),(Pn(o)&1n)===1n&&(o=Pn(-o)),{isValid:u||d,value:o}},J4e=e=>mpt(_pt(e)),n8e=(...e)=>Promise.resolve(ypt("sha512Async")(bA(...e))).then(gpt),Vwr=(...e)=>gpt(ypt("sha512")(bA(...e))),vpt=e=>{let t=e8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=J4e(r),o=Hv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Kwr=e=>n8e(Z1(e,fY)).then(vpt),Wwr=e=>vpt(Vwr(Z1(e,fY))),Gwr=e=>Wwr(e).pointBytes,Jwr=e=>n8e(e.hashable).then(e.finish),Ywr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=J4e(t),s=Hv.multiply(o).toBytes();return{hashable:bA(s,n,r),finish:u=>{let d=mpt(o+J4e(u)*i);return Z1(bA(s,bpt(d)),64)}}},Zwr=async(e,t)=>{let r=Z1(e),n=await Kwr(t),i=await n8e(n.prefix,r);return Jwr(Ywr(n,i,r))},i8e=Object.freeze({bytesToHex:t8e,hexToBytes:r8e,concatBytes:bA,mod:Pn,invert:hpt,randomBytes:Hwr}),wpt={sha512Async:async e=>{let t=Lwr(),r=bA(e);return mY(await t.digest("SHA-512",r.buffer))},sha512:void 0},uY=8,Xwr=256,Ept=Math.ceil(Xwr/uY)+1,Y4e=2**(uY-1),Qwr=()=>{let e=[],t=Hv,r=t;for(let n=0;n<Ept;n++){r=t,e.push(r);for(let i=1;i<Y4e;i++)r=r.add(t),e.push(r);t=r.double()}return e},$lt=void 0,Vlt=(e,t)=>{let r=t.negate();return e?r:t},e4r=e=>{let t=$lt||($lt=Qwr()),r=zv,n=Hv,i=2**uY,o=i,s=cY(i-1),a=cY(uY);for(let c=0;c<Ept;c++){let u=Number(e&s);e>>=a,u>Y4e&&(u-=o,e+=1n);let d=c*Y4e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(Vlt(f,t[l])):r=r.add(Vlt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};Spt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Tpt=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=F4e(this.buffer)}update(e){Klt(this),xpt(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=F4e(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){Klt(this),r4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Pk(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=F4e(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()}},r2=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),QJ=BigInt(2**32-1),Wlt=BigInt(32);Glt=(e,t,r)=>e>>>r,Jlt=(e,t,r)=>e<<32-r|t>>>r,mA=(e,t,r)=>e>>>r|t<<32-r,hA=(e,t,r)=>e<<32-r|t>>>r,eY=(e,t,r)=>e<<64-r|t>>>r-32,tY=(e,t,r)=>e>>>r-32|t<<64-r;a4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),c4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,u4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),d4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,l4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),p4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,f4r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),n2=new Uint32Array(64),m4r=class extends Tpt{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)n2[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=n2[d-15],p=n2[d-2],f=Tm(l,7)^Tm(l,18)^l>>>3,m=Tm(p,17)^Tm(p,19)^p>>>10;n2[d]=m+n2[d-7]+f+n2[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Tm(s,6)^Tm(s,11)^Tm(s,25),p=u+l+n4r(s,a,c)+f4r[d]+n2[d]|0,m=(Tm(r,2)^Tm(r,13)^Tm(r,22))+i4r(r,n,i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){Pk(n2)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Pk(this.buffer)}},h4r=class extends m4r{A=r2[0]|0;B=r2[1]|0;C=r2[2]|0;D=r2[3]|0;E=r2[4]|0;F=r2[5]|0;G=r2[6]|0;H=r2[7]|0;constructor(){super(32)}},Ppt=s4r(["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))),y4r=Ppt[0],g4r=Ppt[1],i2=new Uint32Array(80),o2=new Uint32Array(80),b4r=class extends Tpt{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)i2[E]=e.getUint32(t),o2[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=i2[E-15]|0,v=o2[E-15]|0,x=mA(_,v,1)^mA(_,v,8)^Glt(_,v,7),A=hA(_,v,1)^hA(_,v,8)^Jlt(_,v,7),S=i2[E-2]|0,C=o2[E-2]|0,I=mA(S,C,19)^eY(S,C,61)^Glt(S,C,6),R=hA(S,C,19)^tY(S,C,61)^Jlt(S,C,6),q=u4r(A,R,o2[E-7],o2[E-16]),j=d4r(q,x,I,i2[E-7],i2[E-16]);i2[E]=j|0,o2[E]=q|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:w}=this;for(let E=0;E<80;E++){let _=mA(d,l,14)^mA(d,l,18)^eY(d,l,41),v=hA(d,l,14)^hA(d,l,18)^tY(d,l,41),x=d&p^~d&m,A=l&f^~l&h,S=l4r(w,v,A,g4r[E],o2[E]),C=p4r(S,y,_,x,y4r[E],i2[E]),I=S|0,R=mA(r,n,28)^eY(r,n,34)^eY(r,n,39),q=hA(r,n,28)^tY(r,n,34)^tY(r,n,39),j=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=G1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=a4r(I,q,U);r=c4r(B,C,R,j),n=B|0}({h:r,l:n}=G1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=G1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=G1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=G1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=G1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=G1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=G1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=G1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Pk(i2,o2)}destroy(){this.destroyed=!0,Pk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_4r=class extends b4r{Ah=na[0]|0;Al=na[1]|0;Bh=na[2]|0;Bl=na[3]|0;Ch=na[4]|0;Cl=na[5]|0;Dh=na[6]|0;Dl=na[7]|0;Eh=na[8]|0;El=na[9]|0;Fh=na[10]|0;Fl=na[11]|0;Gh=na[12]|0;Gl=na[13]|0;Hh=na[14]|0;Hl=na[15]|0;constructor(){super(64)}},v4r=Apt(()=>new h4r,Spt(1)),w4r=Apt(()=>new _4r,Spt(3)),Ylt=wpt;Ylt.sha512||(Ylt.sha512=e=>w4r(e));A4r=i8e.bytesToHex,Ipt=i8e.hexToBytes;i8e.concatBytes;T4r=new TextEncoder,P4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Ipt("302e020100300506032b657004220420");Ipt("302a300506032b6570032100");Opt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",R4r=Opt.length-1;if((Opt.length&R4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");new TextEncoder;Cpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:dY,n:sY,Gx:Zlt,Gy:Xlt,a:$4e,d:V4e,h:k4r}=Cpt,_A=32,B4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},vs=(e="")=>{let t=new Error(e);throw B4r(t,vs),t},N4r=e=>typeof e=="bigint",j4r=e=>typeof e=="string",U4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,u2=(e,t,r="")=>{let n=U4r(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},hY=e=>new Uint8Array(e),o8e=e=>Uint8Array.from(e),Rpt=(e,t)=>e.toString(16).padStart(t,"0"),kpt=e=>Array.from(u2(e)).map(t=>Rpt(t,2)).join(""),J1={_0:48,_9:57,A:65,F:70,a:97,f:102},Qlt=e=>{if(e>=J1._0&&e<=J1._9)return e-J1._0;if(e>=J1.A&&e<=J1.F)return e-(J1.A-10);if(e>=J1.a&&e<=J1.f)return e-(J1.a-10)},Bpt=e=>{let t="hex invalid";if(!j4r(e))return vs(t);let r=e.length,n=r/2;if(r%2)return vs(t);let i=hY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Qlt(e.charCodeAt(s)),c=Qlt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return vs(t);i[o]=a*16+c}return i},Npt=()=>globalThis?.crypto,q4r=()=>Npt()?.subtle??vs("crypto.subtle must be defined, consider polyfill"),s8e=(...e)=>{let t=0;for(let i of e)t+=u2(i).length;let r=hY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},M4r=(e=_A)=>Npt().getRandomValues(hY(e)),lY=BigInt,Mv=(e,t,r,n="bad number: out of range")=>{if(!N4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},$n=(e,t=dY)=>{let r=e%t;return r>=0n?r:t+r},ept=(1n<<255n)-1n,Ke=e=>{e<0n&&vs("negative coordinate");let t=(e>>255n)*19n+(e&ept);return t=(t>>255n)*19n+(t&ept),t%dY},D4r=e=>$n(e,sY),z4r=(e,t)=>{(e===0n||t<=0n)&&vs("no inverse n="+e+" mod="+t);let r=$n(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?$n(i,t):vs("no inverse")},jpt=e=>{let t=zpt[e];return typeof t!="function"&&vs("hashes."+e+" not set"),t},Upt=e=>u2(e,64,"digest"),K4e=e=>e instanceof Ok?e:vs("Point expected"),Z4e=2n**256n,Ok=class Dv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Z4e;this.X=Mv(t,0n,o),this.Y=Mv(r,0n,o),this.Z=Mv(n,1n,o),this.T=Mv(i,0n,o),Object.freeze(this)}static CURVE(){return Cpt}static fromAffine(t){return new Dv(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=V4e,i=o8e(u2(t,_A)),o=t[31];i[31]=o&-129;let s=qpt(i);Mv(s,0n,r?Z4e:dY);let c=Ke(s*s),u=$n(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=F4r(u,d);l||vs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&vs("bad point: x==0, isLastByteOdd"),m!==f&&(p=$n(-p)),new Dv(p,s,1n,Ke(p*s))}static fromHex(t,r){return Dv.fromBytes(Bpt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=$4e,r=V4e,n=this;if(n.is0())return vs("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ke(i*i),u=Ke(o*o),d=Ke(s*s),l=Ke(d*d),p=Ke(c*t),f=Ke(d*(p+u)),m=$n(l+Ke(r*Ke(c*u)));if(f!==m)return vs("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(s*a);return h!==y?vs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=K4e(t),c=Ke(r*a),u=Ke(o*i),d=Ke(n*a),l=Ke(s*i);return c===u&&d===l}is0(){return this.equals(Lv)}negate(){return new Dv($n(-this.X),this.Y,this.Z,$n(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=$4e,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=$n(t+r),d=$n(Ke(u*u)-o-s),l=$n(c+s),p=$n(l-a),f=$n(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Dv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=K4e(t),d=$4e,l=V4e,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=$n(Ke($n(r+n)*$n(s+a))-p-f),w=$n(h-m),E=$n(h+m),_=$n(f-Ke(d*p)),v=Ke(y*w),x=Ke(E*_),A=Ke(y*_),S=Ke(w*E);return new Dv(v,x,S,A)}subtract(t){return this.add(K4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Mv(t,1n,sY),!r&&this.is0()))return Lv;if(t===1n)return this;if(this.equals(vA))return Q4r(t).p;let n=Lv,i=vA;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(Lv))return{x:0n,y:1n};let i=z4r(n,dY);Ke(n*i)!==1n&&vs("invalid inverse");let o=Ke(t*i),s=Ke(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=L4r(r);return n[31]|=t&1n?128:0,n}toHex(){return kpt(this.toBytes())}clearCofactor(){return this.multiply(lY(k4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(sY/2n,!1).double();return sY%2n&&(t=t.add(this)),t.is0()}},vA=new Ok(Zlt,Xlt,1n,$n(Zlt*Xlt)),Lv=new Ok(0n,1n,1n,0n);Ok.BASE=vA;Ok.ZERO=Lv;L4r=e=>Bpt(Rpt(Mv(e,0n,Z4e),64)).reverse(),qpt=e=>lY("0x"+kpt(o8e(u2(e)).reverse())),Pm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},H4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Pm(r,2n)*r),i=Ke(Pm(n,1n)*e),o=Ke(Pm(i,5n)*i),s=Ke(Pm(o,10n)*o),a=Ke(Pm(s,20n)*s),c=Ke(Pm(a,40n)*a),u=Ke(Pm(c,80n)*c),d=Ke(Pm(u,80n)*c),l=Ke(Pm(d,10n)*o);return{pow_p_5_8:Ke(Pm(l,2n)*e),b2:r}},tpt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,F4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=H4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*tpt),u=s===e,d=s===$n(-e),l=s===$n(-e*tpt);return u&&(o=a),(d||l)&&(o=c),($n(o)&1n)===1n&&(o=$n(-o)),{isValid:u||d,value:o}},$4r=e=>D4r(qpt(e)),V4r=(...e)=>Promise.resolve(jpt("sha512Async")(s8e(...e))).then(Upt),K4r=(...e)=>Upt(jpt("sha512")(s8e(...e))),Mpt=e=>{let t=o8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=$4r(r),o=vA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},W4r=e=>V4r(u2(e,_A)).then(Mpt),Dpt=e=>Mpt(K4r(u2(e,_A))),G4r=e=>Dpt(e).pointBytes,zpt={sha512Async:async e=>{let t=q4r(),r=s8e(e);return hY(await t.digest("SHA-512",r.buffer))},sha512:void 0},J4r=e=>(e=e===void 0?M4r(_A):e,u2(e,_A)),Y4r=Object.freeze({getExtendedPublicKeyAsync:W4r,getExtendedPublicKey:Dpt,randomSecretKey:J4r}),pY=8,Z4r=256,Lpt=Math.ceil(Z4r/pY)+1,X4e=2**(pY-1),X4r=()=>{let e=[],t=vA,r=t;for(let n=0;n<Lpt;n++){r=t,e.push(r);for(let i=1;i<X4e;i++)r=r.add(t),e.push(r);t=r.double()}return e},rpt=void 0,npt=(e,t)=>{let r=t.negate();return e?r:t},Q4r=e=>{let t=rpt||(rpt=X4r()),r=Lv,n=vA,i=2**pY,o=i,s=lY(i-1),a=lY(pY);for(let c=0;c<Lpt;c++){let u=Number(e&s);e>>=a,u>X4e&&(u-=o,e+=1n);let d=c*X4e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(npt(f,t[l])):r=r.add(npt(m,t[p]))}return e!==0n&&vs("invalid wnaf"),{p:r,f:n}};n8r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),i8r=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=W4e(this.buffer)}update(e){ipt(this),Hpt(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=W4e(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){ipt(this),t8r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Q4e(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=W4e(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()}},ia=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),rY=BigInt(2**32-1),opt=BigInt(32);spt=(e,t,r)=>e>>>r,apt=(e,t,r)=>e<<32-r|t>>>r,yA=(e,t,r)=>e>>>r|t<<32-r,gA=(e,t,r)=>e<<32-r|t>>>r,nY=(e,t,r)=>e<<64-r|t>>>r-32,iY=(e,t,r)=>e>>>r-32|t<<64-r;a8r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),c8r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,u8r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),d8r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,l8r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),p8r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Fpt=s8r(["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))),f8r=Fpt[0],m8r=Fpt[1],s2=new Uint32Array(80),a2=new Uint32Array(80),h8r=class extends i8r{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)s2[E]=e.getUint32(t),a2[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=s2[E-15]|0,v=a2[E-15]|0,x=yA(_,v,1)^yA(_,v,8)^spt(_,v,7),A=gA(_,v,1)^gA(_,v,8)^apt(_,v,7),S=s2[E-2]|0,C=a2[E-2]|0,I=yA(S,C,19)^nY(S,C,61)^spt(S,C,6),R=gA(S,C,19)^iY(S,C,61)^apt(S,C,6),q=u8r(A,R,a2[E-7],a2[E-16]),j=d8r(q,x,I,s2[E-7],s2[E-16]);s2[E]=j|0,a2[E]=q|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:w}=this;for(let E=0;E<80;E++){let _=yA(d,l,14)^yA(d,l,18)^nY(d,l,41),v=gA(d,l,14)^gA(d,l,18)^iY(d,l,41),x=d&p^~d&m,A=l&f^~l&h,S=l8r(w,v,A,m8r[E],a2[E]),C=p8r(S,y,_,x,f8r[E],s2[E]),I=S|0,R=yA(r,n,28)^nY(r,n,34)^nY(r,n,39),q=gA(r,n,28)^iY(r,n,34)^iY(r,n,39),j=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=Y1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=a8r(I,q,U);r=c8r(B,C,R,j),n=B|0}({h:r,l:n}=Y1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Y1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Y1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Y1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Y1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=Y1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Y1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=Y1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Q4e(s2,a2)}destroy(){this.destroyed=!0,Q4e(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},y8r=class extends h8r{Ah=ia[0]|0;Al=ia[1]|0;Bh=ia[2]|0;Bl=ia[3]|0;Ch=ia[4]|0;Cl=ia[5]|0;Dh=ia[6]|0;Dl=ia[7]|0;Eh=ia[8]|0;El=ia[9]|0;Fh=ia[10]|0;Fl=ia[11]|0;Gh=ia[12]|0;Gl=ia[13]|0;Hh=ia[14]|0;Hl=ia[15]|0;constructor(){super(64)}},g8r=r8r(()=>new y8r,n8r(3)),cpt=zpt;cpt.sha512||(cpt.sha512=e=>g8r(e));x8r="ws://localhost:9001/ws",A8r=3e4,Vpt=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=Tk(e.name),e.keyPath)try{this._keypair=w8r(e.keyPath)}catch{}this.options={name:this._name,url:e.url??x8r,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??A8r,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new jwr({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),r=C4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:E4r(r)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let r={type:"register",name:this._name};this.options.relay&&(r.relay=this.options.relay),this._keypair&&(r.public_key=upt(this._keypair.publicKey)),this.options.binding&&(r.binding=this.options.binding);try{this.transport.send(r)}catch(n){this.registerPromise=null,t(n instanceof Error?n:new ra(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ra("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ra("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ra("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ra("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=Tk(e),o=D4e();return new Promise((s,a)=>{this.pendingSend.set(i,{resolve:s,reject:a});try{this.transport.send({type:"send",to:i,message_type:t,payload:r,metadata:n})}catch(c){this.pendingSend.delete(i),a(c instanceof Error?c:new ra(String(c)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),s({messageId:o,to:i}))},5e3)})}async sendSigned(e,t,r,n){if(!this._keypair||!this._peerId)return this.send(e,t,r,n);let i=Tk(e),o=D4e(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await E8r(this._keypair.privateKey,o,this._peerId,this._name,s,t,c,a);return new Promise((l,p)=>{this.pendingSend.set(i,{resolve:l,reject:p});try{this.transport.send({type:"send_signed",to:i,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:s,message_type:t,payload:r,metadata:n,signature:Buffer.from(u).toString("base64"),signature_input:d,nonce:a})}catch(f){this.pendingSend.delete(i),p(f instanceof Error?f:new ra(String(f)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),l({messageId:o,to:i}))},5e3)})}async call(e,t,r,n){let i=Tk(e),o=n?.correlationId??D4e(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new Sk(`RPC call to ${i}.${t} timed out after ${s}ms`))},s);this.pendingCalls.set(o,{resolve:a,reject:c,timer:u});try{this.transport.send({type:"call",to:i,method:t,payload:r??"",correlation_id:o})}catch(d){clearTimeout(u),this.pendingCalls.delete(o),c(d instanceof Error?d:new ra(String(d)))}})}async broadcast(e,t,r){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:r})}subscribe(e,t){let r=this.topicHandlers.get(e);if(!r){r=new Set,this.topicHandlers.set(e,r);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return r.add(t),()=>{r.delete(t),r.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=Tk(e);return new Promise((r,n)=>{this.pendingResolve.set(t,{resolve:r,reject:n});try{this.transport.send({type:"resolve",name:t})}catch(i){this.pendingResolve.delete(t),n(i instanceof Error?i:new ra(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new Sk(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>r.delete(t)}off(e,t){let r=this.eventListeners.get(e);r&&r.delete(t)}emit(e,...t){let r=this.eventListeners.get(e);if(r)for(let n of r)try{n(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let r of this.messageHandlers)try{r(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},r=this.topicHandlers.get(e.topic);if(r)for(let n of r)try{n(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=U4e(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new XJ(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},r=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,n;if(!r)n={success:!1,error:`No handler for method: ${e.method}`};else try{n=await r(t)}catch(i){n={success:!1,error:i instanceof Error?i.message:String(i)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:n.success,payload:n.payload??"",error:n.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=upt(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});var f8e={};ki(f8e,{SUBWAY_PROTOCOL:()=>nft,registerDirect:()=>q8r,resolveDirect:()=>M8r});function u8e(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 Yd(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 d8e(e,t){return e<<3|t}function Ck(e,t,r){e.push(d8e(t,2)),u8e(e,r.length);for(let n of r)e.push(n)}function S8r(e,t){let r=[];return Ck(r,1,c8e.encode(e)),t&&t.length>0&&Ck(r,2,c8e.encode(t)),Uint8Array.from(r)}function T8r(e,t,r){let n=[];return r!==0n&&(n.push(d8e(1,0)),u8e(n,r)),Ck(n,2,S8r(e,t)),Uint8Array.from(n)}function P8r(e){let t=[];return Ck(t,1,c8e.encode(e)),Uint8Array.from(t)}function I8r(e,t){let r=[];return t!==0n&&(r.push(d8e(1,0)),u8e(r,t)),Ck(r,3,P8r(e)),Uint8Array.from(r)}function O8r(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Yd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.error=tft.decode(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function C8r(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Yd(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]=Yd(e,t),u=c,d=u+Number(a);r.error=tft.decode(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function l8e(e,t,r){if(r===0)return Yd(e,t)[1];if(r===2){let[n,i]=Yd(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 rft(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Yd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.registerNameResponse=O8r(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Yd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=C8r(e.subarray(u,d)),t=d}else t=l8e(e,t,s)}return r}function R8r(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function p8e(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function k8r(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=p8e(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:rft(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function B8r(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=p8e(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:rft(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function a8e(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 U8r(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>Wpt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+p8e(a8e(t).subarray(0,4)),n>Wpt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return a8e(t).subarray(0,n)}return a8e(t)}async function ift(e){return(0,Gpt.createLibp2p)({...e?{privateKey:await(0,Xpt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Jpt.tcp)()],connectionEncrypters:[(0,Ypt.noise)()],streamMuxers:[(0,Zpt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function oft(e,t,r){let n=await e.dialProtocol((0,Qpt.multiaddr)(t),nft,{signal:AbortSignal.timeout(N8r)});n.send(R8r(r));let i;return Promise.race([U8r(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),j8r)})]).finally(()=>clearTimeout(i))}async function q8r(e){let t=await ift(e.seed);try{let r=await oft(t,e.relayMultiaddr,T8r(e.name,e.binding,e.requestId??1n)),n=k8r(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function M8r(e){let t=await ift(e.seed);try{let r=await oft(t,e.relayMultiaddr,I8r(e.name,e.requestId??1n)),n=B8r(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,eft.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Gpt,Jpt,Ypt,Zpt,Xpt,Qpt,eft,c8e,tft,nft,N8r,j8r,Wpt,m8e=P(()=>{"use strict";M4e();Gpt=require("libp2p"),Jpt=require("@libp2p/tcp"),Ypt=require("@chainsafe/libp2p-noise"),Zpt=require("@chainsafe/libp2p-yamux"),Xpt=require("@libp2p/crypto/keys"),Qpt=require("@multiformats/multiaddr"),eft=require("uint8arrays/to-string"),c8e=new TextEncoder,tft=new TextDecoder;nft="/subway/p2p/1.0.0",N8r=15e3,j8r=15e3,Wpt=1<<20});var kk={};ki(kk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>aft,MESH:()=>ws,RELAY_URL:()=>v8e,connectOrThrow:()=>_Y,ensureMailbox:()=>T8e,isSubwayEnabled:()=>w8e,listRegistered:()=>F8r,loadBindingFor:()=>A8e,loadRegistry:()=>Fv,makeClient:()=>bY,maybeMintVisaBinding:()=>uft,meshName:()=>vp,pairedVisaBinding:()=>dft,readInbox:()=>V8r,registerName:()=>S8e,resolveActingName:()=>z8r,resolveMeshName:()=>L8r,seedSubwayKeyFromTapAgent:()=>cft,sendMessage:()=>H8r,sendVia:()=>K8r,subwayKeyPath:()=>gY,visaRelayMultiaddr:()=>_8e});function _8e(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??aft}function vp(e){return e.includes(".")?e:`${e}.${ws}`}function w8e(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 x8e(){uo.mkdirSync(E8e,{recursive:!0,mode:448})}function D8r(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function gY(e){return wA.join(E8e,`${D8r(e)}.key`)}function Fv(){if(!uo.existsSync(b8e))return{};try{return JSON.parse(uo.readFileSync(b8e,"utf8"))}catch{return{}}}function y8e(e){x8e(),uo.writeFileSync(b8e,JSON.stringify(e,null,2),{mode:384})}function g8e(){try{return Rk.userInfo().username}catch{return"local"}}function cft(e){if(uo.existsSync(e)||!uo.existsSync(h8e))return null;let t=uo.readdirSync(h8e).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>wA.join(h8e,n)).sort((n,i)=>uo.statSync(i).mtimeMs-uo.statSync(n).mtimeMs)[0];try{let n=JSON.parse(uo.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=ZA(n.private_key_jwk);return x8e(),uo.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function bY(e,t={}){return new Vpt({name:vp(e),url:v8e,keyPath:gY(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function A8e(e){if(ws!=="visa")return;let t=Fv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function _Y(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${v8e})`)),t))])}function z8r(e){if(e)return e;let t=Object.keys(Fv());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>.`)}async function uft(e){if(ws!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new E2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await zZ({authUrl:Mu(),apiKey:t,seed:BB(gY(e)),name:vp(e)})}catch(r){if(r instanceof E2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function dft(e=Date.now()){let t=P8e();if(!t?.binding_jwt)return null;let r=Bk(t.binding_jwt);if(!r||r.mesh!=="visa")return null;let n=typeof r.exp=="number"?r.exp:NaN;return!Number.isFinite(n)||n*1e3<=e?null:{binding:t.binding_jwt,bindingExpiresAt:new Date(n*1e3).toISOString()}}async function S8e(e){let t=gY(e),r=cft(t),n=vp(e);ws==="visa"&&!uo.existsSync(t)&&(x8e(),uo.writeFileSync(t,(0,sft.randomBytes)(32),{mode:384}));let i=ws==="visa"?dft():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await uft(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=ws==="visa"?_8e():process.env.SUBWAY_RELAY_MULTIADDR;if(ws==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(m8e(),f8e)),d=await u({relayMultiaddr:a,seed:BB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=Fv();return l[e]={relayName:n,mesh:ws,peerId:d.peerId,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(l),{relayName:n,mesh:ws,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(ws==="visa"&&!process.env.SUBWAY_RELAY){let u=Fv();return u[e]={relayName:n,mesh:ws,peerId:null,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(u),{relayName:n,mesh:ws,peerId:null,tapAgentId:r,...o?{binding:o}:{},note:o?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding; pair/enroll this agent, or set VISA_CLI_API_KEY (card on file), for a .visa binding."}}let c=bY(e,{autoReconnect:!1,binding:o});try{await _Y(c);let u=Fv();return u[e]={relayName:n,mesh:ws,peerId:c.peerId,owner:g8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},y8e(u),{relayName:n,mesh:ws,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function L8r(e){let t=vp(e),r=ws==="visa"?_8e():process.env.SUBWAY_RELAY_MULTIADDR;if(ws==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(m8e(),f8e)),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 H8r(e,t,r){let n=bY(e,{autoReconnect:!1,binding:A8e(e)});try{await _Y(n);let i=vp(t);return await n.sendSigned(i,"chat",r),{to:i,as:vp(e)}}finally{n.disconnect()}}function F8r(){let e=Fv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function T8e(e){let t=yY.get(e);if(t)return{relayName:vp(e),peerId:t.client.peerId};let r=bY(e,{autoReconnect:!0,binding:A8e(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>$8r&&n.shift()}),yY.set(e,{client:r,buffer:n}),await _Y(r),{relayName:vp(e),peerId:r.peerId}}async function V8r(e,t=20,r=!1){await T8e(e);let n=yY.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function K8r(e,t,r){await T8e(e);let n=yY.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=vp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:vp(e)}}var uo,Rk,wA,sft,ws,aft,v8e,E8e,b8e,h8e,yY,$8r,$v=P(()=>{"use strict";Kpt();w2();uo=Ze(require("fs")),Rk=Ze(require("os")),wA=Ze(require("path")),sft=require("crypto");gw();QA();vY();ws=process.env.SUBWAY_MESH??"relay",aft="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";v8e=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";E8e=wA.join(Rk.homedir(),".visa-cli","subway"),b8e=wA.join(E8e,"registry.json"),h8e=wA.join(Rk.homedir(),".visa-cli","agents");yY=new Map,$8r=200});var mft={};ki(mft,{PAIRING_DIR:()=>xA,cancelPairing:()=>C8e,claimPairing:()=>TY,generateWalletCredential:()=>yk,getPairingStatus:()=>SY,initiatePairing:()=>AY,latestPendingHumanPairing:()=>xY,loadPairingMailbox:()=>pft,pairingFilePath:()=>EY,pollAndActivatePairing:()=>Uk,readPendingPairing:()=>Nk,registerOnVisaMeshIfEnabled:()=>wY,removePendingPairing:()=>AA,verifyPairing:()=>jk,writePendingPairing:()=>O8e});async function wY(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await S8e(e),!0}catch(t){return Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function pft(e=process.env.VISA_V4_HOME||EA.join(I8e.homedir(),".visa-v4")){try{let t=Dc.readFileSync(EA.join(e,"identity","mailbox.json"),"utf8"),r=JSON.parse(t);return typeof r.email!="string"||!r.email.includes("@")||typeof r.inboxId!="string"||r.inboxId.length===0?null:{email:r.email,inboxId:r.inboxId}}catch{return null}}function EY(e,t,r=xA){return EA.join(r,`${e}.${t}.json`)}function O8e(e,t=xA){Dc.mkdirSync(t,{recursive:!0,mode:448}),Dc.writeFileSync(EY(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function AA(e,t,r=xA){Dc.rmSync(EY(e,t,r),{force:!0})}function Nk(e,t,r=xA){try{let n=JSON.parse(Dc.readFileSync(EY(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function xY(e=xA){return Dc.existsSync(e)?Dc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(Dc.readFileSync(EA.join(e,r),"utf8"))}catch{return null}}).filter(r=>r?.role==="human").sort((r,n)=>n.createdAt.localeCompare(r.createdAt))[0]??null:null}async function Vv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":lft,...t.headers??{}}}),i=await n.json().catch(()=>({}));if(!n.ok&&n.status!==202)throw new Error(i.error??i.detail??`pairing server returned ${n.status}`);return{status:n.status,body:i}}async function AY(e={}){let t=(e.authUrl??Mu()).replace(/\/+$/,""),r=q9e(),n=pft(),{body:i}=await Vv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:M9e(r),...n?{mailbox:n}:{}})},e.fetchImpl??fetch);if(!i.pairingId||!i.skillUrl||!i.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let o={role:"human",pairingId:i.pairingId,verifier:r,authUrl:t,skillUrl:i.skillUrl,expiresAt:i.expiresAt,createdAt:new Date().toISOString()};return O8e(o,e.pairingDir),o}async function jk(e){let{pairing:t}=e,{body:r}=await Vv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return r}async function SY(e){let t=(e.authUrl??Mu()).replace(/\/+$/,""),{body:r}=await Vv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function fft(e,t){return Buffer.from(xw(e,Buffer.from(t,"utf8"))).toString("base64url")}async function TY(e){let t=(e.authUrl??Mu()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await SY({pairingId:e.pairingId,authUrl:t,fetchImpl:r});if(n.state!=="awaiting_agent"||!n.serverNonce)throw new Error(`pairing cannot be claimed from state ${n.state}`);let i,o,s;if(e.existingCredential)s=e.existingCredential.privateKeyJwk,o=e.existingCredential.publicKeyJwk,i=Buffer.from(s.d,"base64url");else{let m=CB();i=m.secretKey,s=Aw(i),o=ph(m.publicKey)}let a=Sw(o),c=yk(),u=D9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:lft},l=fft(i,z9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:MZ(u),agentJkt:a,walletPublicKey:c.publicKey,runtime:d})),p={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:a,publicKeyJwk:o,privateKeyJwk:s,walletPublicKey:c.publicKey,walletPrivateKey:c.privateKey,createdAt:new Date().toISOString()};O8e(p,e.pairingDir);let{body:f}=await Vv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:o,walletPublicKey:c.publicKey,runtime:d,signature:l,claimToken:u})},r);if(!f.verificationCode||f.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(f.verificationCode!==RB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function Uk(e){let t=e.fetchImpl??fetch,r=e.wait??(o=>new Promise(s=>setTimeout(s,o))),n=e.maxPolls??450,i="";for(let o=0;o<n;o+=1){let{body:s,status:a}=await Vv(`${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);if(s.state!==i&&(i=s.state,e.onState?.(s.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(s.state))throw new Error(`pairing ended in state ${s.state}`);await r(e.pollIntervalMs??2e3);continue}if(!s.artifacts||!s.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=s.artifacts,u=c.terms?.name,d=c.wallet?.turnkey,l=c.terms?.mode==="wallet"||c.terms?.mode==="both",p=KJ(d?.network);if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof u!="string"||c.wallet?.credentialPublicKey!==e.pending.walletPublicKey||l&&(!d||typeof d.organizationId!="string"||typeof d.walletId!="string"||typeof d.address!="string"||!/^0x[0-9a-f]{40}$/i.test(d.address)||!p||!Number.isSafeInteger(c.terms?.dailyLimitCents)||!Number.isSafeInteger(c.terms?.perTransactionLimitCents))||H9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=fft(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),L9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await Vv(`${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({signature:f})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let h={agent_jkt:e.pending.agentJkt,name:u,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:s.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return l&&d&&await VJ({apiPublicKey:e.pending.walletPublicKey,apiPrivateKey:e.pending.walletPrivateKey,organizationId:d.organizationId,walletId:d.walletId,address:d.address,network:p,perTransactionLimitCents:c.terms?.perTransactionLimitCents,dailyLimitCents:c.terms?.dailyLimitCents,...e.walletHome?{homeDir:e.walletHome}:{}}),k8e(h,e.agentDir),await wY(u),AA(e.pending.pairingId,"runtime",e.pairingDir),{record:h,name:u,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function C8e(e){let{pairing:t}=e,{body:r}=await Vv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return r.state==="cancelled"&&AA(t.pairingId,"human",e.pairingDir),r}var Dc,I8e,EA,lft,xA,R8e=P(()=>{"use strict";Dc=Ze(require("node:fs")),I8e=Ze(require("node:os")),EA=Ze(require("node:path"));w2();QA();$v();gw();Hc();v4e();vY();lft="4.1.0-rc.37",xA=EA.join(I8e.homedir(),".visa-cli","pairings")});var Eft={};ki(Eft,{agentFilePath:()=>Mk,agentFormatIsJson:()=>qk,attachAgentCommand:()=>Z8r,claimOptsFromFlags:()=>j8e,decodeBindingClaims:()=>Bk,enrollClaimEnvelope:()=>vft,isAgentCommandEnabled:()=>_ft,isAgentRecord:()=>Dk,listAgentFiles:()=>PY,newestAgentRecord:()=>P8e,readAgent:()=>U8e,resolveAgentByRef:()=>wft,writeAgent:()=>k8e});function Dk(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function _ft(){return!0}function qk(e){return e==="json"}function vft(e){switch(e.status){case"claimed":return{json:{status:"claimed",...e.name?{name:e.name}:{},tokenId:e.tokenId,credentialPath:e.credentialPath,keyBound:e.keyBound,sessionSaved:e.sessionSaved,walletProvisioned:e.walletProvisioned},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute enrollment window has likely expired":"not ready yet \u2014 finish the browser flow through the final minted screen"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no enrollment hand-off in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this enrollment hand-off did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function j8e(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function B8e(e){return`${e.opened?`\u2713 Enrollment link opened in your browser.
|
|
20679
20679
|
If it did not open, paste this into your phone or browser:
|
|
20680
20680
|
`:`Enrollment link (open on your phone):
|
|
20681
20681
|
`}
|
|
@@ -20771,12 +20771,12 @@ Approve it in your browser \u2014 grant the new rail to your existing agent.
|
|
|
20771
20771
|
`)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(r=>{let n=U8e(r);if(!n){let o=Mk(r);process.stderr.write(zo.existsSync(o)?`Invalid or unreadable agent record: ${r}
|
|
20772
20772
|
`:`Agent not found: ${r}
|
|
20773
20773
|
`),process.exit(1)}let i=n.binding_jwt?Bk(n.binding_jwt):null;process.stdout.write([`agent 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)`,`wallet key: ${n.wallet_public_key}`,"registration: stored",`key file: ${Mk(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
|
|
20774
|
-
`))})}var gft,zo,bft,Kv,N8e,Wv,vY=P(()=>{"use strict";gft=require("node:child_process"),zo=Ze(require("fs")),bft=Ze(require("os")),Kv=Ze(require("path")),N8e=require("node:readline/promises");w2();vZ();dZ();S4e();Olt();klt();R8e();Wv=Kv.join(bft.homedir(),".visa-cli","agents")});var D8e={};ki(D8e,{CardDrawRefusedError:()=>Gv,cardDrawIntentHash:()=>Tft,decimalUsdToCents:()=>M8e,fetchCardDrawVerdict:()=>o3r,loadCardMandateCapability:()=>i3r,registerCardMandate:()=>s3r});function Q8r(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,q8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function e3r(e){let{secretKey:t,publicKey:r}=N9e(e),n=Aw(t),i=ph(r);return{privateJwk:n,publicJwk:i,jkt:Q8r(i)}}async function Aft(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:X8r},o=`${xft(i)}.${xft(n)}`,s=ZA(e.privateJwk),a=xw(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Sft(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(!t3r.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:r3r,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,q8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function n3r(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 M8e(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 Tft(e,t){let r=M8e(e.amount);return r===null?null:Sft({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function i3r(e={}){let t=e.record!==void 0?e.record:(vY(),ie(Eft)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=n3r(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=e3r(ZA(t.private_key_jwk))}catch{return null}return n.jkt!==t.agent_jkt?null:{agentKey:n,agentJkt:t.agent_jkt,authBaseUrl:t.auth_url}}function Pft(e){return e.replace(/\/+$/,"")}async function o3r(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Pft(e.authBaseUrl),i=Tft(e.draw,e.drawId);if(i===null)throw new Gv(400,["invalid_amount"]);let o=await t(`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Gv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Gv(502,["challenge_malformed"]);let a=await Aft(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await 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 Gv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function s3r(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Pft(e.authBaseUrl),i=M8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Sft({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await 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 Aft(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await 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 q8e,X8r,xft,t3r,r3r,Gv,z8e=P(()=>{"use strict";q8e=require("node:crypto");w2();X8r="visa-agent-pop+jwt",xft=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");t3r=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),r3r=1;Gv=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}});var JY={};ki(JY,{initSentry:()=>Bxr,isSentryConfigured:()=>kxr,reportFatal:()=>Nxr});function kxr(){return!1}async function Bxr(){return null}async function Nxr(e,t){process.exit(t?.exitCode??1)}var YY=P(()=>{});var a0t=require("@modelcontextprotocol/sdk/server/index.js"),c0t=require("@modelcontextprotocol/sdk/server/stdio.js"),Rm=require("@modelcontextprotocol/sdk/types.js");async function d3e(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 rB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var l3e={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 p3e(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&&l3e[r]?l3e[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 A0t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function m3e(e,t){let r=f3e(e),n=f3e(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:S0t(r.pre,n.pre)>0}function f3e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(A0t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function S0t(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 nB(){return!!(h3e(process.env.VISA_CLI_NO_UPDATE_CHECK)||h3e(process.env.CI)||process.env.NODE_ENV==="test")}function h3e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}gw();var uB="4.1.0-rc.36",z0t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function L0t(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 H0t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function bw(e){return typeof e=="string"?e.trim():""}function F0t(e){let t=e&&typeof e=="object"?e:{},r=bw(t.error)||bw(t.message);if(!r)return H0t;let n=bw(t.error_code),i=[["surface",bw(t.disabled_surface)],["flag",bw(t.flag)],["correlation_id",bw(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 $0t(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?z0t.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(`
|
|
20774
|
+
`))})}var gft,zo,bft,Kv,N8e,Wv,vY=P(()=>{"use strict";gft=require("node:child_process"),zo=Ze(require("fs")),bft=Ze(require("os")),Kv=Ze(require("path")),N8e=require("node:readline/promises");w2();vZ();dZ();S4e();Olt();klt();R8e();Wv=Kv.join(bft.homedir(),".visa-cli","agents")});var D8e={};ki(D8e,{CardDrawRefusedError:()=>Gv,cardDrawIntentHash:()=>Tft,decimalUsdToCents:()=>M8e,fetchCardDrawVerdict:()=>o3r,loadCardMandateCapability:()=>i3r,registerCardMandate:()=>s3r});function Q8r(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,q8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function e3r(e){let{secretKey:t,publicKey:r}=N9e(e),n=Aw(t),i=ph(r);return{privateJwk:n,publicJwk:i,jkt:Q8r(i)}}async function Aft(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:X8r},o=`${xft(i)}.${xft(n)}`,s=ZA(e.privateJwk),a=xw(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Sft(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(!t3r.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:r3r,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,q8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function n3r(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 M8e(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 Tft(e,t){let r=M8e(e.amount);return r===null?null:Sft({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function i3r(e={}){let t=e.record!==void 0?e.record:(vY(),ie(Eft)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=n3r(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=e3r(ZA(t.private_key_jwk))}catch{return null}return n.jkt!==t.agent_jkt?null:{agentKey:n,agentJkt:t.agent_jkt,authBaseUrl:t.auth_url}}function Pft(e){return e.replace(/\/+$/,"")}async function o3r(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Pft(e.authBaseUrl),i=Tft(e.draw,e.drawId);if(i===null)throw new Gv(400,["invalid_amount"]);let o=await t(`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Gv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Gv(502,["challenge_malformed"]);let a=await Aft(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await 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 Gv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function s3r(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Pft(e.authBaseUrl),i=M8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Sft({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await 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 Aft(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await 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 q8e,X8r,xft,t3r,r3r,Gv,z8e=P(()=>{"use strict";q8e=require("node:crypto");w2();X8r="visa-agent-pop+jwt",xft=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");t3r=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),r3r=1;Gv=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}});var JY={};ki(JY,{initSentry:()=>Bxr,isSentryConfigured:()=>kxr,reportFatal:()=>Nxr});function kxr(){return!1}async function Bxr(){return null}async function Nxr(e,t){process.exit(t?.exitCode??1)}var YY=P(()=>{});var a0t=require("@modelcontextprotocol/sdk/server/index.js"),c0t=require("@modelcontextprotocol/sdk/server/stdio.js"),Rm=require("@modelcontextprotocol/sdk/types.js");async function d3e(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 rB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var l3e={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 p3e(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&&l3e[r]?l3e[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 A0t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function m3e(e,t){let r=f3e(e),n=f3e(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:S0t(r.pre,n.pre)>0}function f3e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(A0t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function S0t(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 nB(){return!!(h3e(process.env.VISA_CLI_NO_UPDATE_CHECK)||h3e(process.env.CI)||process.env.NODE_ENV==="test")}function h3e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}gw();var uB="4.1.0-rc.37",z0t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function L0t(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 H0t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function bw(e){return typeof e=="string"?e.trim():""}function F0t(e){let t=e&&typeof e=="object"?e:{},r=bw(t.error)||bw(t.message);if(!r)return H0t;let n=bw(t.error_code),i=[["surface",bw(t.disabled_surface)],["flag",bw(t.flag)],["correlation_id",bw(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 $0t(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?z0t.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(`
|
|
20775
20775
|
`)}var dB=class{constructor(t){this.getSessionToken=t;this.baseUrl=Mu()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!nB()){let n=t.headers.get("X-Latest-Version");n&&m3e(n,uB)&&(this.lastSignals.updateAvailable={currentVersion:uB,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return uB}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new rB(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(F0t(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error($0t());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 d3e(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":uB,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(p3e(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),L0t(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)}};dZ();var K3e=require("child_process"),W3e=require("util"),G3e=Ze(require("crypto")),$r=Ze(require("fs")),J3e=Ze(require("os")),xs=Ze(require("path"));Hc();pB();KA();var gB=(0,W3e.promisify)(K3e.execFile);var s1t=()=>process.platform==="darwin",_B=()=>process.platform==="win32",uh=xs.join(J3e.homedir(),".visa-mcp","bin"),y2=xs.join(uh,"Visa CLI"),Nm=xs.join(uh,"visa-keychain-win.exe"),Y3e=xs.join(__dirname,"..","native"),D3e="6",z3e=xs.join(uh,"visa-keychain.version"),L3e=xs.join(uh,"visa-keychain.sha256"),H3e="1",F3e=xs.join(uh,"visa-keychain-win.version"),$3e=xs.join(uh,"visa-keychain-win.sha256"),Z3e=[xs.join(Y3e,"bin","win32-x64","visa-keychain-win.exe"),xs.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),xs.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function bB(e){let t=$r.readFileSync(e);return G3e.createHash("sha256").update(t).digest("hex")}function a1t(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)}async function c1t(){try{if($r.readFileSync(z3e,"utf-8").trim()===D3e&&$r.existsSync(y2)){let n=$r.readFileSync(L3e,"utf-8").trim();if(bB(y2)!==n)Be.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),$r.unlinkSync(y2);else return y2}}catch{}let e=xs.join(Y3e,"visa-keychain.m");if($r.existsSync(e)||(e=xs.resolve(__dirname,"..","..","native","visa-keychain.m")),$r.existsSync(e)||(e=xs.resolve(__dirname,"..","native","visa-keychain.m")),!$r.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");$r.mkdirSync(uh,{recursive:!0,mode:448});try{await gB("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",y2,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=bB(y2);return $r.writeFileSync(L3e,t,{mode:384}),$r.writeFileSync(z3e,D3e,{mode:384}),y2}function X3e(){for(let e of Z3e)if($r.existsSync(e))return e;return null}async function Q3e(){try{if($r.readFileSync(F3e,"utf-8").trim()===H3e&&$r.existsSync(Nm)){let n=$r.readFileSync($3e,"utf-8").trim();if(bB(Nm)!==n)Be.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),$r.unlinkSync(Nm);else return Nm}}catch{}let e=X3e();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
20776
20776
|
If building from source, run native/build-win.bat first.`);$r.mkdirSync(uh,{recursive:!0}),$r.copyFileSync(e,Nm);let t=bB(Nm);return $r.writeFileSync($3e,t,{mode:384}),$r.writeFileSync(F3e,H3e,{mode:384}),Nm}async function u1t(){return _B()?Q3e():c1t()}var d1t="visa-cli",l1t="attestation-key";async function p1t(e){let t=await u1t(),r;try{r=(await gB(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 a1t(r)}var V3e=!1;function f1t(){if(!_B())return!1;try{return $r.existsSync(Nm)||X3e()!==null?!0:(V3e||(V3e=!0,Be.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Nm,searchedPrebuiltPaths:Z3e})),!1)}catch{return!1}}function e9e(){return lB()||s1t()?!0:_B()?f1t():!1}async function t9e(){if(_B()){try{let e=await Q3e();await gB(e,["delete-key"],{timeout:1e4})}catch{}return}if(await ch())try{await gB("security",["delete-generic-password","-s",d1t,"-a",l1t],{timeout:5e3})}catch{}try{await p1t(["delete-key"])}catch{}}KA();Hc();vZ();S4e();var Umt=require("child_process"),$Y=Ze(require("fs")),VY=Ze(require("os")),qmt=Ze(require("path"));var Em=Ze(require("fs")),WJ=Ze(require("os")),_p=Ze(require("path"));var Yvr="# >>> visa-cli shell hud v2 >>>",Zvr="# <<< visa-cli shell hud v2 <<<";function Xvr(e){let t=e??process.env.SHELL;if(!t)return null;let r=_p.basename(t.replace(/\\/g,"/")).toLowerCase();return r==="zsh"?"zsh":r==="bash"?"bash":r==="pwsh"||r==="pwsh.exe"||r==="powershell"||r==="powershell.exe"?"powershell":null}function Qvr(e){let t=iwr();if(e==="zsh")return _p.join(t,".zshrc");if(e==="bash")return _p.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return _p.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function ewr(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function twr(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${clt(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${clt(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!ewr(a))return i;let l=d>0?e[d-1]:"";return o===`
|
|
20777
20777
|
`&&l!==`
|
|
20778
20778
|
`?`
|
|
20779
|
-
`:""})}function rwr(e){return twr(e,Yvr,Zvr).trimEnd()}function nwr(e){return rwr(e)!==e.trimEnd()}function GJ(e=Xvr()){if(!e)return!1;try{let t=Qvr(e),r=Em.readFileSync(t,"utf-8");return nwr(r)}catch{return!1}}function clt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iwr(){let e=WJ.homedir();if(!e||!_p.isAbsolute(e))throw new Error("unable to determine a valid home directory");return _p.resolve(e)}var wvn=1440*60*1e3;var owr="# visa-cli-hud-v1";function ult(e){return typeof e!="string"?!1:e.includes(owr)?!0:e.includes("visa-cli")&&e.includes("statusline")}gw();pB();var dlt="4.1.0-rc.36";function T4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function swr(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=cZ(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function pA(e){return e==null?"\u2014":e?"yes":"no"}async function llt(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=aZ("auth.serverUrl"),s=Mu(),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:pA(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=swr("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:pA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=nB(),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:pA(!u),source:d}),n.push({key:"client.version",value:dlt,formatted:dlt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=oh();n.push({key:"dev.mockKeychain",value:p,formatted:pA(p),source:T4e("VISA_MOCK_KEYCHAIN",!!l),hint:pZ()});let f=process.env.VISA_MOCK_TOUCHID,m=lB();n.push({key:"dev.mockTouchid",value:m,formatted:pA(m),source:T4e("VISA_MOCK_TOUCHID",!!f),hint:pZ()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:pA(!!h),source:T4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var H8e=require("node:os"),zk=require("node:path"),Lk=require("node:fs/promises"),Oft=require("node:fs"),Cft=require("node:url"),Rft=require("node:crypto");Hc();var awr=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function P4e(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!awr.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var V1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function I4e(e){let t;try{t=new URL(e)}catch{throw new V1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new V1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Hc();var cwr={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},plt=300*1e3,O4e={},C4e=0,Ek=null;function R4e(){return Ek||(Ek=(async()=>{try{let e=await ea.getFeatureFlags();O4e=e&&e.flags||{},C4e=Date.now()}catch(e){O4e={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{Ek=null}})(),Ek)}async function flt(){await R4e()}function mlt(){Date.now()-C4e<plt||R4e()}async function fA(){Date.now()-C4e<plt||await R4e()}function xm(e){let t=cwr[e];return t?O4e[t]!==!0:!1}var hlt=require("node:crypto"),xk=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},JJ=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 xk(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??hlt.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 kft(e){return[(0,zk.join)(e,"checkout-engine","index.js"),(0,zk.join)(e,"..","checkout-engine","index.js")]}function a3r(e,t=Oft.existsSync){return kft(e).find(r=>t(r))??null}var IY=null,Bft=async()=>{if(IY)return IY;let e=a3r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${kft(__dirname).join(" and ")}).`);return IY=(await import((0,Cft.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await c3r(),cardMandateRegister:await u3r()}),IY};async function c3r(){let e=await Promise.resolve().then(()=>(z8e(),D8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function u3r(){let e=await Promise.resolve().then(()=>(z8e(),D8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function F8e(){return xm("pay_merchant")?(await fA(),xm("pay_merchant")):!1}var Nft=(0,zk.join)((0,H8e.homedir)(),".visa-mcp","agent-credential.json"),jft=(0,zk.join)((0,H8e.homedir)(),".visa-mcp","contact.json"),Uft=new JJ;function Hk(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var d3r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function qft(e){return d3r.has(e)?e:null}async function OY(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,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?Hk(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:qft(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){Be.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function Ift(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?Hk(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:qft(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){Be.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function L8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new V1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Mft(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=Hk(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 Dft(e={},t={}){if(await(t.flagDisabled??F8e)())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??Uft).get(n);return o?Mft(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 zft(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:uZ()&&!process.env.VISA_VERIFY_WEB_URL?null:ol();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??F8e)())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??Uft,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=I4e(e.url??"").toString(),c=L8e(e.amount)}catch(C){if(C instanceof V1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Nft,l=t.contactPath??jft;try{await(0,Lk.readFile)(d,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry pay_merchant."}}let p;try{p=JSON.parse(await(0,Lk.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",I=/^PAY (\S+)$/.exec(C);if(!I)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=I[1]}let m=t.loadEngine??Bft,h;try{h=await m()}catch(C){let I=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(I))return{success:!1,message:/checkout engine was not packaged/.test(I)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let y={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},w=t.emitTelemetry??(C=>ea.emitTelemetry(C)),E=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:E,currency:u});let C;try{C=await h.review(y)}catch(I){throw await OY({emitTelemetry:w,action:"review",merchantHost:E,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await OY({emitTelemetry:w,action:"review",merchantHost:E,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${P4e(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:x,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:x,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await OY({emitTelemetry:w,action:"pay",merchantHost:E,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:v,submit:A}),j}let R=I.outcome==="confirmed"||I.outcome==="filled-dry-run";await OY({emitTelemetry:w,action:"pay",merchantHost:E,amountMinor:_,currency:u,outcome:I.outcome,confirmationRef:I.confirmationRef,success:R,errorMessage:R?null:I.detail??I.outcome,startedAt:v,submit:A,source:I.source??null,remainingMinor:I.remainingMinor??null,drawId:I.source==="mandate"?x:null});let q=I.source==="mandate"?` Drawn tap-free from an active card mandate${typeof I.remainingMinor=="number"?` (${I.remainingMinor} ${u} minor units remaining)`:""}.`:I.source==="fresh-tap"?" Paid with a fresh per-purchase passkey.":"";return{success:R,action:"pay",reviewId:x,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${q}`:`Outcome: ${I.outcome}${I.detail?` \u2014 ${I.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,Rft.createHash)("sha256").update(JSON.stringify([x,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:E,currency:u,submit:A});try{let I=await s.start({reviewId:x,fingerprint:C,run:async R=>{try{let q=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:x}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:q.success===!0}),q}catch(q){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:Hk(q instanceof Error?q.message:String(q))}),q}}});return Mft(I,"authorize")}catch(I){if(I instanceof xk)return Be.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 I}}return S()}async function Lft(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`start_card_mandate only supports the "card" rail (got ${JSON.stringify(r)}). For x402/stablecoin payments, use wallet_policy_set and wallet_pay.`};let n=t.verifyUrl!==void 0?t.verifyUrl:ol();if(n===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??F8e)())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 o=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(o))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};let s=e.anyMerchant===!0,a,c;try{a=s?void 0:I4e(e.url??"").toString(),c=L8e(e.ceiling??e.amount)}catch(A){if(A instanceof V1)return{success:!1,message:A.message};throw A}if(e.expiresAt!==void 0){let A=Date.parse(e.expiresAt);if(!Number.isFinite(A)||A<=Date.now())return{success:!1,message:`Invalid expiresAt ${JSON.stringify(e.expiresAt)}. Expected a future ISO 8601 timestamp.`}}if(e.maxDraws!==void 0&&(!Number.isSafeInteger(e.maxDraws)||e.maxDraws<1))return{success:!1,message:"maxDraws must be a positive integer."};let u;if(e.perTransaction!==void 0){try{u=L8e(e.perTransaction)}catch(A){if(A instanceof V1)return{success:!1,message:A.message};throw A}if(Number(u)>Number(c))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let d;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let A=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();d=A.length>0?A:void 0}let l=t.credentialPath??Nft,p=t.contactPath??jft;try{await(0,Lk.readFile)(l,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry start_card_mandate."}}let f;try{f=JSON.parse(await(0,Lk.readFile)(p,"utf8"))}catch{return{success:!1,message:`No contact details at ${p}. Write your name/email/address there (chmod 600) first.`}}let m=t.loadEngine??Bft,h;try{h=await m()}catch(A){let S=A instanceof Error?A.message:String(A);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(S))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 A}let y=s?"any-merchant":new URL(a).hostname,w=Math.round(Number(c)*100),E=t.emitTelemetry??(A=>ea.emitTelemetry(A)),_=Date.now();Be.info("start_card_mandate:create",{host:y,currency:o});let v;try{v=await h.startCardMandate({...a?{url:a}:{},ceiling:c,currency:o,credentialPath:l,contact:f,approvalBaseUrl:n,...s?{anyMerchant:!0}:{},...e.merchantName?{merchantName:e.merchantName}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.maxDraws!==void 0?{maxDraws:e.maxDraws}:{},...u!==void 0?{perTransaction:u}:{},...d!==void 0?{intent:d}:{}})}catch(A){let S=A instanceof Error?Hk(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await Ift({emitTelemetry:E,merchantHost:y,ceilingMinor:w,currency:o,outcome:"engine-error",success:!1,errorMessage:A instanceof Error?A.message:String(A),startedAt:_}),{success:!1,message:`Could not create the mandate: ${S}`}}let x=v.registerFailed===!0;return x&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await Ift({emitTelemetry:E,merchantHost:y,ceilingMinor:w,currency:o,outcome:x?"created-register-failed":"created",success:!x,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),x?{success:!1,mandateId:v.mandateId,ceiling:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,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:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${P4e(w,v.currencyCode)} at ${v.merchantHost} until ${v.expiresAt}. pay_merchant will now draw against it tap-free (no fresh passkey) until the budget is spent or it expires. NOTE: honoring a ceiling-scoped assurance across multiple draws is unproven live \u2014 if the network declines a draw, the budget is left untouched and that mandate is disabled, so your next pay_merchant uses a fresh per-purchase tap (it does NOT fall back within the same call).`}}var Bmt=require("node:crypto");var Omt=require("node:crypto");var jr={};ki(jr,{BRAND:()=>U3r,DIRTY:()=>Jv,EMPTY_PATH:()=>m3r,INVALID:()=>ht,NEVER:()=>p9r,OK:()=>oa,ParseStatus:()=>Es,Schema:()=>qt,ZodAny:()=>p2,ZodArray:()=>th,ZodBigInt:()=>Zv,ZodBoolean:()=>Xv,ZodBranded:()=>$k,ZodCatch:()=>uw,ZodDate:()=>Qv,ZodDefault:()=>cw,ZodDiscriminatedUnion:()=>kY,ZodEffects:()=>Qd,ZodEnum:()=>sw,ZodError:()=>zc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>NY,ZodIntersection:()=>nw,ZodIssueCode:()=>ye,ZodLazy:()=>iw,ZodLiteral:()=>ow,ZodMap:()=>CA,ZodNaN:()=>kA,ZodNativeEnum:()=>aw,ZodNever:()=>wp,ZodNull:()=>tw,ZodNullable:()=>Cm,ZodNumber:()=>Yv,ZodObject:()=>Lc,ZodOptional:()=>Zd,ZodParsedType:()=>Ce,ZodPipeline:()=>Vk,ZodPromise:()=>f2,ZodReadonly:()=>dw,ZodRecord:()=>BY,ZodSchema:()=>qt,ZodSet:()=>RA,ZodString:()=>l2,ZodSymbol:()=>IA,ZodTransformer:()=>Qd,ZodTuple:()=>Om,ZodType:()=>qt,ZodUndefined:()=>ew,ZodUnion:()=>rw,ZodUnknown:()=>eh,ZodVoid:()=>OA,addIssueToContext:()=>Ae,any:()=>tl,array:()=>ue,bigint:()=>z3r,boolean:()=>el,coerce:()=>qu,custom:()=>Jft,date:()=>L3r,datetimeRegex:()=>Wft,defaultErrorMap:()=>X1,discriminatedUnion:()=>G3r,effect:()=>i9r,enum:()=>rl,function:()=>Q3r,getErrorMap:()=>SA,getParsedType:()=>Im,instanceof:()=>M3r,intersection:()=>J3r,isAborted:()=>CY,isAsync:()=>TA,isDirty:()=>RY,isValid:()=>d2,late:()=>q3r,lazy:()=>e9r,literal:()=>t9r,makeIssue:()=>Fk,map:()=>Z3r,nan:()=>D3r,nativeEnum:()=>r9r,never:()=>V3r,null:()=>BA,nullable:()=>s9r,number:()=>Ir,object:()=>fe,objectUtil:()=>$8e,oboolean:()=>l9r,onumber:()=>d9r,optional:()=>o9r,ostring:()=>u9r,pipeline:()=>c9r,preprocess:()=>a9r,promise:()=>n9r,quotelessJson:()=>l3r,record:()=>Zt,set:()=>X3r,setErrorMap:()=>f3r,strictObject:()=>W3r,string:()=>z,symbol:()=>H3r,transformer:()=>i9r,tuple:()=>Y3r,undefined:()=>F3r,union:()=>NA,unknown:()=>$3r,util:()=>Yt,void:()=>K3r});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 $8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})($8e||($8e={}));var Ce=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Im=e=>{switch(typeof e){case"undefined":return Ce.undefined;case"string":return Ce.string;case"number":return Number.isNaN(e)?Ce.nan:Ce.number;case"boolean":return Ce.boolean;case"function":return Ce.function;case"bigint":return Ce.bigint;case"symbol":return Ce.symbol;case"object":return Array.isArray(e)?Ce.array:e===null?Ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ce.promise:typeof Map<"u"&&e instanceof Map?Ce.map:typeof Set<"u"&&e instanceof Set?Ce.set:typeof Date<"u"&&e instanceof Date?Ce.date:Ce.object;default:return Ce.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"]),l3r=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),zc=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()}};zc.create=e=>new zc(e);var p3r=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Ce.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}},X1=p3r;var Hft=X1;function f3r(e){Hft=e}function SA(){return Hft}var Fk=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}},m3r=[];function Ae(e,t){let r=SA(),n=Fk({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===X1?void 0:X1].filter(i=>!!i)});e.common.issues.push(n)}var Es=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 ht;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 ht;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}}},ht=Object.freeze({status:"aborted"}),Jv=e=>({status:"dirty",value:e}),oa=e=>({status:"valid",value:e}),CY=e=>e.status==="aborted",RY=e=>e.status==="dirty",d2=e=>e.status==="valid",TA=e=>typeof Promise<"u"&&e instanceof Promise;var Qe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Qe||(Qe={}));var Xd=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}},Fft=(e,t)=>{if(d2(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 zc(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return Im(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Im(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Es,ctx:{common:t.parent.common,data:t.data,parsedType:Im(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(TA(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:Im(t)},i=this._parseSync({data:t,path:n.path,parent:n});return Fft(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Im(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return d2(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=>d2(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:Im(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(TA(i)?i:Promise.resolve(i));return Fft(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 Qd({schema:this,typeName:wt.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 Zd.create(this,this._def)}nullable(){return Cm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return th.create(this)}promise(){return f2.create(this,this._def)}or(t){return rw.create([this,t],this._def)}and(t){return nw.create(this,t,this._def)}transform(t){return new Qd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new cw({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new $k({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new uw({...Bt(this._def),innerType:this,catchValue:r,typeName:wt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Vk.create(this,t)}readonly(){return dw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},h3r=/^c[^\s-]{8,}$/i,y3r=/^[0-9a-z]+$/,g3r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,b3r=/^[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,_3r=/^[a-z0-9_-]{21}$/i,v3r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,w3r=/^[-+]?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)?)??$/,E3r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,x3r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",V8e,A3r=/^(?:(?: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])$/,S3r=/^(?:(?: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])$/,T3r=/^(([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]))$/,P3r=/^(([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])$/,I3r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,O3r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vft="((\\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])))",C3r=new RegExp(`^${Vft}$`);function Kft(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 R3r(e){return new RegExp(`^${Kft(e)}$`)}function Wft(e){let t=`${Vft}T${Kft(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 k3r(e,t){return!!((t==="v4"||!t)&&A3r.test(e)||(t==="v6"||!t)&&T3r.test(e))}function B3r(e,t){if(!v3r.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 N3r(e,t){return!!((t==="v4"||!t)&&S3r.test(e)||(t==="v6"||!t)&&P3r.test(e))}var l2=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.string,received:o.parsedType}),ht}let n=new Es,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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?Ae(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ae(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")E3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")V8e||(V8e=new RegExp(x3r,"u")),V8e.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")b3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")_3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")h3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")y3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")g3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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),Ae(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),Ae(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),Ae(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),Ae(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Wft(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?C3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?R3r(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?w3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?k3r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?B3r(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?N3r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?I3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?O3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Qe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Qe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Qe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Qe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Qe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Qe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Qe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Qe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Qe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Qe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Qe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Qe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Qe.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,...Qe.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,...Qe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Qe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Qe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Qe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Qe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Qe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Qe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Qe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Qe.errToObj(r)})}nonempty(t){return this.min(1,Qe.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}};l2.create=e=>new l2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function j3r(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 Yv=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ce.number){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.number,received:o.parsedType}),ht}let n,i=new Es;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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),Ae(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?j3r(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Qe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Qe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.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)}};Yv.create=e=>new Yv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var Zv=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ce.bigint)return this._getInvalidInput(t);let n,i=new Es;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),Ae(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),Ae(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),Ae(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 Ae(r,{code:ye.invalid_type,expected:Ce.bigint,received:r.parsedType}),ht}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.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:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.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}};Zv.create=e=>new Zv({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var Xv=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.boolean,received:n.parsedType}),ht}return oa(t.data)}};Xv.create=e=>new Xv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Qv=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.date,received:o.parsedType}),ht}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_date}),ht}let n=new Es,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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:Qe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Qe.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}};Qv.create=e=>new Qv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var IA=class extends qt{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.symbol,received:n.parsedType}),ht}return oa(t.data)}};IA.create=e=>new IA({typeName:wt.ZodSymbol,...Bt(e)});var ew=class extends qt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.undefined,received:n.parsedType}),ht}return oa(t.data)}};ew.create=e=>new ew({typeName:wt.ZodUndefined,...Bt(e)});var tw=class extends qt{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.null,received:n.parsedType}),ht}return oa(t.data)}};tw.create=e=>new tw({typeName:wt.ZodNull,...Bt(e)});var p2=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return oa(t.data)}};p2.create=e=>new p2({typeName:wt.ZodAny,...Bt(e)});var eh=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return oa(t.data)}};eh.create=e=>new eh({typeName:wt.ZodUnknown,...Bt(e)});var wp=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};wp.create=e=>new wp({typeName:wt.ZodNever,...Bt(e)});var OA=class extends qt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.void,received:n.parsedType}),ht}return oa(t.data)}};OA.create=e=>new OA({typeName:wt.ZodVoid,...Bt(e)});var th=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ae(r,{code:ye.invalid_type,expected:Ce.array,received:r.parsedType}),ht;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ae(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&&(Ae(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&&(Ae(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 Xd(r,s,r.path,a)))).then(s=>Es.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Xd(r,s,r.path,a)));return Es.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Qe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Qe.toString(r)}})}nonempty(t){return this.min(1,t)}};th.create=(e,t)=>new th({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function PA(e){if(e instanceof Lc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Zd.create(PA(n))}return new Lc({...e._def,shape:()=>t})}else return e instanceof th?new th({...e._def,type:PA(e.element)}):e instanceof Zd?Zd.create(PA(e.unwrap())):e instanceof Cm?Cm.create(PA(e.unwrap())):e instanceof Om?Om.create(e.items.map(t=>PA(t))):e}var Lc=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Yt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ce.object){let u=this._getOrReturnCtx(t);return Ae(u,{code:ye.invalid_type,expected:Ce.object,received:u.parsedType}),ht}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof wp&&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 Xd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof wp){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&&(Ae(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 Xd(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=>Es.mergeObjectSync(n,u)):Es.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Qe.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:Qe.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:wt.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 PA(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 Zd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return Gft(Yt.objectKeys(this.shape))}};Lc.create=(e,t)=>new Lc({shape:()=>e,unknownKeys:"strip",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});Lc.strictCreate=(e,t)=>new Lc({shape:()=>e,unknownKeys:"strict",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});Lc.lazycreate=(e,t)=>new Lc({shape:e,unknownKeys:"strip",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});var rw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new zc(a.ctx.common.issues));return Ae(r,{code:ye.invalid_union,unionErrors:s}),ht}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 zc(c));return Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};rw.create=(e,t)=>new rw({options:e,typeName:wt.ZodUnion,...Bt(t)});var Q1=e=>e instanceof iw?Q1(e.schema):e instanceof Qd?Q1(e.innerType()):e instanceof ow?[e.value]:e instanceof sw?e.options:e instanceof aw?Yt.objectValues(e.enum):e instanceof cw?Q1(e._def.innerType):e instanceof ew?[void 0]:e instanceof tw?[null]:e instanceof Zd?[void 0,...Q1(e.unwrap())]:e instanceof Cm?[null,...Q1(e.unwrap())]:e instanceof $k||e instanceof dw?Q1(e.unwrap()):e instanceof uw?Q1(e._def.innerType):[],kY=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ae(r,{code:ye.invalid_type,expected:Ce.object,received:r.parsedType}),ht;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}):(Ae(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ht)}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=Q1(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:wt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function K8e(e,t){let r=Im(e),n=Im(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.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=K8e(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Ce.array&&n===Ce.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=K8e(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Ce.date&&n===Ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nw=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(CY(o)||CY(s))return ht;let a=K8e(o.value,s.value);return a.valid?((RY(o)||RY(s))&&r.dirty(),{status:r.value,value:a.data}):(Ae(n,{code:ye.invalid_intersection_types}),ht)};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}))}};nw.create=(e,t,r)=>new nw({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Om=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ae(n,{code:ye.invalid_type,expected:Ce.array,received:n.parsedType}),ht;if(n.data.length<this._def.items.length)return Ae(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ht;!this._def.rest&&n.data.length>this._def.items.length&&(Ae(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 Xd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Es.mergeArray(r,s)):Es.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Om.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Om({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var BY=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.object)return Ae(n,{code:ye.invalid_type,expected:Ce.object,received:n.parsedType}),ht;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Xd(n,a,n.path,a)),value:s._parse(new Xd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Es.mergeObjectAsync(r,i):Es.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:l2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},CA=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.map)return Ae(n,{code:ye.invalid_type,expected:Ce.map,received:n.parsedType}),ht;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Xd(n,a,n.path,[u,"key"])),value:o._parse(new Xd(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 ht;(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 ht;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};CA.create=(e,t,r)=>new CA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var RA=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ae(n,{code:ye.invalid_type,expected:Ce.set,received:n.parsedType}),ht;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ae(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&&(Ae(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 ht;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 Xd(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:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Qe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};RA.create=(e,t)=>new RA({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var NY=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ae(r,{code:ye.invalid_type,expected:Ce.function,received:r.parsedType}),ht;function n(a,c){return Fk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,SA(),X1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Fk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,SA(),X1].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 f2){let a=this;return oa(async function(...c){let u=new zc([]),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 oa(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new zc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new zc([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:Om.create(t).rest(eh.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||Om.create([]).rest(eh.create()),returns:r||eh.create(),typeName:wt.ZodFunction,...Bt(n)})}},iw=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};iw.create=(e,t)=>new iw({getter:e,typeName:wt.ZodLazy,...Bt(t)});var ow=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ae(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),ht}return{status:"valid",value:t.data}}get value(){return this._def.value}};ow.create=(e,t)=>new ow({value:e,typeName:wt.ZodLiteral,...Bt(t)});function Gft(e,t){return new sw({values:e,typeName:wt.ZodEnum,...Bt(t)})}var sw=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),ht}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 Ae(r,{received:r.data,code:ye.invalid_enum_value,options:n}),ht}return oa(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})}};sw.create=Gft;var aw=class extends qt{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Yt.objectValues(r);return Ae(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return oa(t.data)}get enum(){return this._def.values}};aw.create=(e,t)=>new aw({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var f2=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ae(r,{code:ye.invalid_type,expected:Ce.promise,received:r.parsedType}),ht;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return oa(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};f2.create=(e,t)=>new f2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Qd=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.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=>{Ae(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 ht;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ht:c.status==="dirty"?Jv(c.value):r.value==="dirty"?Jv(c.value):c});{if(r.value==="aborted")return ht;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ht:a.status==="dirty"?Jv(a.value):r.value==="dirty"?Jv(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"?ht:(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"?ht:(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(!d2(s))return ht;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=>d2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Yt.assertNever(i)}};Qd.create=(e,t,r)=>new Qd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Qd.createWithPreprocess=(e,t,r)=>new Qd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Zd=class extends qt{_parse(t){return this._getType(t)===Ce.undefined?oa(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Zd.create=(e,t)=>new Zd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Cm=class extends qt{_parse(t){return this._getType(t)===Ce.null?oa(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Cm.create=(e,t)=>new Cm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var cw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};cw.create=(e,t)=>new cw({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var uw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return TA(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new zc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new zc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};uw.create=(e,t)=>new uw({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var kA=class extends qt{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.nan,received:n.parsedType}),ht}return{status:"valid",value:t.data}}};kA.create=e=>new kA({typeName:wt.ZodNaN,...Bt(e)});var U3r=Symbol("zod_brand"),$k=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Vk=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ht:o.status==="dirty"?(r.dirty(),Jv(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"?ht: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:wt.ZodPipeline})}},dw=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(d2(i)&&(i.value=Object.freeze(i.value)),i);return TA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};dw.create=(e,t)=>new dw({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function $ft(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Jft(e,t={},r){return e?p2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=$ft(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=$ft(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):p2.create()}var q3r={object:Lc.lazycreate},wt;(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"})(wt||(wt={}));var M3r=(e,t={message:`Input not instance of ${e.name}`})=>Jft(r=>r instanceof e,t),z=l2.create,Ir=Yv.create,D3r=kA.create,z3r=Zv.create,el=Xv.create,L3r=Qv.create,H3r=IA.create,F3r=ew.create,BA=tw.create,tl=p2.create,$3r=eh.create,V3r=wp.create,K3r=OA.create,ue=th.create,fe=Lc.create,W3r=Lc.strictCreate,NA=rw.create,G3r=kY.create,J3r=nw.create,Y3r=Om.create,Zt=BY.create,Z3r=CA.create,X3r=RA.create,Q3r=NY.create,e9r=iw.create,t9r=ow.create,rl=sw.create,r9r=aw.create,n9r=f2.create,i9r=Qd.create,o9r=Zd.create,s9r=Cm.create,a9r=Qd.createWithPreprocess,c9r=Vk.create,u9r=()=>z().optional(),d9r=()=>Ir().optional(),l9r=()=>el().optional(),qu={string:(e=>l2.create({...e,coerce:!0})),number:(e=>Yv.create({...e,coerce:!0})),boolean:(e=>Xv.create({...e,coerce:!0})),bigint:(e=>Zv.create({...e,coerce:!0})),date:(e=>Qv.create({...e,coerce:!0}))};var p9r=ht;var m9r=rl(["enc","sig"]),h9r=rl(["markdown","plain"]),y9r=rl(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),g9r=rl(["error","info","warning"]),qA=rl(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),b9r=rl(["completed","failed","pending"]),_9r=rl(["digital","pickup","shipping"]),v9r=rl(["fulfilled","partial","processing","removed"]),w9r=rl(["across","each"]),W8e=rl(["pickup","shipping"]),E9r=fe({config:Zt(z(),tl()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),x9r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:m9r.optional(),x:z().optional(),y:z().optional()}),A9r=fe({config:Zt(z(),tl()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),S9r=fe({endpoint:z()}),T9r=fe({schema:z()}),Yft=fe({endpoint:z(),schema:z()}),P9r=Yft,I9r=Yft,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),lo=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()}),G8e=lo,Zft=fe({id:z()}),O9r=Zft,C9r=Zft,Kk=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()}),jY=fe({type:z()}),Gi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),J8e=Gi,Xft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),UY=fe({amount:Ir(),display_text:z().optional(),type:z()}),m2=fe({title:z().optional(),type:z(),url:z()}),rh=fe({code:z().optional(),content:z(),content_type:h9r.optional(),path:z().optional(),severity:y9r.optional(),type:g9r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Y8e=rh,MA=fe({id:z(),label:z().optional(),permalink_url:z()}),R9r=fe({amount:Ir(),display_text:z()}),k9r=fe({config:Zt(z(),tl()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Z8e=fe({id:z(),quantity:Ir()}),B9r=Z8e,N9r=Z8e,j9r=Z8e,U9r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),q9r=fe({billing_address:Kk.optional(),credential:jY.optional(),display:Zt(z(),tl()).optional(),handler_id:z(),id:z(),type:z()}),M9r=fe({checkout_mandate:z()}),D9r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),z9r=fe({analytics:el().optional(),marketing:el().optional(),preferences:el().optional(),sale_of_data:el().optional()});var L9r=z9r;var Qft=fe({codes:ue(z()).optional()}),H9r=Qft,F9r=fe({amount:Ir(),path:z()}),$9r=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:Kk.optional(),name:z().optional()}),V9r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:qu.date().optional(),id:z(),latest_fulfillment_time:qu.date().optional(),title:z(),totals:ue(UY)}),K9r=fe({description:z().optional(),fulfillable_on:NA([BA(),z()]).optional(),line_item_ids:ue(z()),type:W8e}),W9r=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:Kk.optional(),name:z().optional()}),G9r=fe({max:Ir().optional(),min:Ir().optional()}),Wk=fe({taxonomy:z().optional(),value:z()}),Gk=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),jA=fe({amount:Ir(),currency:z()}),Jk=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),J9r=fe({id:z().optional(),label:z()}),Yk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),emt=fe({available:el().optional(),status:z().optional()}),Y9r=emt,tmt=fe({type:z(),value:z()}),Z9r=tmt,X9r=fe({id:z(),match:z().optional()}),X8e=fe({id:z().optional(),label:z(),name:z()}),rmt=X8e,nmt=fe({links:ue(m2).optional(),name:z().optional()}),Q9r=nmt,imt=fe({unit:z(),value:Ir()});var eEr=imt,tEr=fe({cursor:z().optional(),limit:Ir().optional()}),rEr=fe({cursor:z().optional(),has_next_page:el(),total_count:Ir().optional()}),nEr=fe({handlers:ue(E9r).optional()}),iEr=fe({a2a:S9r.optional(),embedded:T9r.optional(),mcp:P9r.optional(),rest:I9r.optional(),spec:z(),version:z()}),DA=fe({item:O9r,quantity:Ir()}),oEr=fe({billing_address:Kk.optional(),credential:jY.optional(),display:Zt(z(),tl()).optional(),handler_id:z(),id:z(),type:z(),selected:el().optional()}),Zk=fe({id:z().optional(),item:C9r,parent_id:z().optional(),quantity:Ir()}),qY=fe({instruments:ue(oEr).optional()}),sEr=qY,Xk=qY,zA=qY,MY=qY,lw=fe({id:z(),item:Xft,parent_id:z().optional(),quantity:Ir(),totals:ue(UY)}),h2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(R9r).optional()}),Ep=fe({capabilities:Zt(z(),ue(k9r)),version:z()}),aEr=fe({description:z().optional(),id:z(),line_items:ue(B9r).optional(),occurred_at:qu.date(),status:b9r,totals:ue(UY).optional(),type:z()}),cEr=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(N9r),occurred_at:qu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),uEr=fe({description:z().optional(),destination:Kk,fulfillable_on:z().optional(),id:z(),line_items:ue(j9r),method_type:_9r}),dEr=fe({id:z(),item:Xft,parent_id:z().optional(),quantity:U9r,status:v9r,totals:ue(UY)}),c4n=fe({payment_data:q9r}),u4n=fe({ap2:M9r.optional()}),d4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,ap2:D9r.optional()}),Q8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:L9r.optional()}),lEr=Q8e,pEr=Q8e,omt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional(),discounts:H9r.optional()}),fEr=fe({allocations:ue(F9r).optional(),amount:Ir(),automatic:el().optional(),code:z().optional(),eligibility:z().optional(),method:w9r.optional(),priority:Ir().optional(),provisional:el().optional(),title:z()}),smt=fe({id:z(),line_item_ids:ue(z()),options:ue(V9r).optional(),selected_option_id:NA([BA(),z()]).optional()}),mEr=fe({destinations:ue(W9r).optional(),groups:ue(smt).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:NA([BA(),z()]).optional(),type:W8e}),l4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),signals:Gi.optional()}),p4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),id:z(),line_items:ue(Zk),signals:Gi.optional()}),f4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2).optional(),messages:ue(rh).optional(),signals:Gi.optional(),totals:ue(h2),ucp:Ep}),hEr=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional()}),amt=hEr,m4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,cart_id:z().optional()}),e3e=fe({categories:ue(z()).optional(),price:G9r.optional()}),UA=fe({max:jA,min:jA}),t3e=fe({name:z(),values:ue(J9r)}),cmt=fe({amount:Ir(),currency:z(),measure:imt,reference:eEr}),yEr=cmt,h4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(rmt).optional(),signals:J8e.optional()}),y4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),pagination:tEr.optional(),query:z().optional(),signals:J8e.optional()}),gEr=fe({capabilities:ue(A9r),services:Zt(z(),iEr),version:z()}),g4n=fe({attribution:Zt(z(),z()).optional(),payment:sEr,signals:Gi.optional()}),umt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep}),bEr=fe({events:ue(cEr).optional(),expectations:ue(uEr).optional()}),dmt=fe({attribution:Zt(z(),z()).optional(),buyer:Q8e.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional()}),lmt=fe({attribution:Zt(z(),z()).optional(),buyer:pEr.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional()}),pmt=fe({attribution:Zt(z(),z()).optional(),buyer:lEr.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep}),fmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),discounts:Qft.optional()}),_Er=fe({applied:ue(fEr).optional(),codes:ue(z()).optional()}),vEr=fe({destinations:ue($9r).optional(),groups:ue(smt).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:NA([BA(),z()]).optional(),type:W8e}),wEr=fe({available_methods:ue(K9r).optional(),methods:ue(mEr).optional()}),mmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),cart_id:z().optional()}),b4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),ids:ue(z()),signals:J8e.optional()}),EEr=fe({availability:emt.optional(),barcodes:ue(tmt).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price:jA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(X8e).optional(),price:jA,rating:Yk.optional(),seller:nmt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:cmt.optional(),url:z().optional(),inputs:ue(X9r)}),hmt=fe({availability:Y9r.optional(),barcodes:ue(Z9r).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price:jA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(X8e).optional(),price:jA,rating:Yk.optional(),seller:Q9r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:yEr.optional(),url:z().optional()}),xEr=fe({categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(t3e).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(hmt)}),_4n=fe({payment:nEr.optional(),signing_keys:ue(x9r).optional(),ucp:gEr}),ymt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional()}),AEr=fe({adjustments:ue(aEr).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:bEr,id:z(),label:z().optional(),line_items:ue(dEr),messages:ue(rh).optional(),permalink_url:z(),totals:ue(h2),ucp:Ep}),gmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,discounts:_Er.optional()}),bmt=fe({methods:ue(vEr).optional()}),_mt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional(),fulfillment:bmt.optional()}),vmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,fulfillment:wEr.optional()}),SEr=fe({categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(t3e).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(EEr)}),TEr=fe({options:ue(t3e).optional(),selected:ue(rmt).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(hmt)}),v4n=fe({messages:ue(Y8e).optional(),pagination:rEr.optional(),products:ue(xEr),ucp:Ep}),wmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),fulfillment:bmt.optional()}),w4n=fe({messages:ue(Y8e).optional(),products:ue(SEr),ucp:Ep}),E4n=fe({messages:ue(Y8e).optional(),product:TEr,ucp:Ep});var T4n=jY.extend({token:jr.string().optional()}),PEr=jr.object({webhook_url:jr.string().url().optional()}),Emt=umt.extend(vmt.pick({fulfillment:!0}).shape).extend(gmt.pick({discounts:!0}).shape).extend(pmt.pick({buyer:!0}).shape).extend({platform:PEr.optional()}),xmt=ymt.extend(wmt.pick({fulfillment:!0}).shape).extend(fmt.pick({discounts:!0}).shape).extend(dmt.pick({buyer:!0}).shape).extend(mmt.pick({cart_id:!0}).shape),Amt=amt.extend(_mt.pick({fulfillment:!0}).shape).extend(omt.pick({discounts:!0}).shape).extend(lmt.pick({buyer:!0}).shape);Hc();async function DY(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 zY(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 IEr=3e4,Smt=2*1024*1024,xp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Tmt(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 Pmt(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"?xmt:Amt).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function OEr(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 Imt(e,t,r,n){try{e[t](r,n)}catch{}}function CEr(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 LY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Tmt(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Tmt(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??IEr,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Pmt(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:Pmt(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=zY(this.timeoutMs,this.signal),o=(0,Omt.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 DY(u,Smt,"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 xp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Smt)throw new xp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new xp("UCP MCP response is not valid JSON",void 0,u.status)}if(!OEr(l))throw new xp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new xp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new xp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new xp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new xp("UCP MCP response is missing result.structuredContent");if(!Emt.safeParse(CEr(p.structuredContent)).success)throw new xp("UCP checkout response failed schema validation");return Imt(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Imt(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 Rmt=require("node:crypto");Hc();var FY="2026-04-08",REr="dev.ucp.shopping",kEr="dev.ucp.shopping.checkout",BEr=1024*1024,NEr=1e4,jEr="https://ucp.dev",Qk=jr.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"),UEr=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Qk,schema:Qk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Qk.optional()}).passthrough(),qEr=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Qk,schema:Qk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),MEr=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(UEr)),capabilities:jr.record(jr.array(qEr)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function DEr(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 HY(e,t){if(new URL(e).origin!==jEr)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Cmt(e,t,r,n){try{e[t](r,n)}catch{}}async function zEr(e,t={}){let r=DEr(e,"UCP business URL"),n=zY(t.timeoutMs??NEr,t.signal),i=t.logger??Be,o=(0,Rmt.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 DY(c,BEr,"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=MEr.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Cmt(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 Cmt(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 LEr(e){if(e.ucp.version!==FY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[kEr]?.find(i=>i.version===FY);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");HY(t.spec,"Checkout capability spec"),HY(t.schema,"Checkout capability schema");let r=e.ucp.services[REr]?.find(i=>i.version===FY&&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");HY(r.spec,"Shopping service spec"),HY(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 kmt(e,t={}){let r=await zEr(e,t);return{...r,endpoint:LEr(r.profile),version:FY}}var HEr="https://app.visacli.sh/.well-known/ucp";function FEr(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 $Er(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 r3e(e,t=new Set){if(Array.isArray(e))for(let r of e)r3e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?$Er(n,t):r3e(n,t);return t}function VEr(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=r3e(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 KEr(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 WEr(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 Nmt(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??kmt)(e.business),i=await(t.getCheckout??(async(u,d)=>await new LY({endpoint:u.endpoint,platformProfileUrl:FEr(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??HEr)}).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=KEr(i),a=VEr(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Bmt.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:WEr(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>."}}gw();function GEr(){return Mu()}var ea=new dB(()=>zu.getSessionToken()),JEr="4.1.0-rc.36",o8n=["","","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(`
|
|
20779
|
+
`:""})}function rwr(e){return twr(e,Yvr,Zvr).trimEnd()}function nwr(e){return rwr(e)!==e.trimEnd()}function GJ(e=Xvr()){if(!e)return!1;try{let t=Qvr(e),r=Em.readFileSync(t,"utf-8");return nwr(r)}catch{return!1}}function clt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iwr(){let e=WJ.homedir();if(!e||!_p.isAbsolute(e))throw new Error("unable to determine a valid home directory");return _p.resolve(e)}var wvn=1440*60*1e3;var owr="# visa-cli-hud-v1";function ult(e){return typeof e!="string"?!1:e.includes(owr)?!0:e.includes("visa-cli")&&e.includes("statusline")}gw();pB();var dlt="4.1.0-rc.37";function T4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function swr(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=cZ(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function pA(e){return e==null?"\u2014":e?"yes":"no"}async function llt(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=aZ("auth.serverUrl"),s=Mu(),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:pA(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=swr("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:pA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=nB(),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:pA(!u),source:d}),n.push({key:"client.version",value:dlt,formatted:dlt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=oh();n.push({key:"dev.mockKeychain",value:p,formatted:pA(p),source:T4e("VISA_MOCK_KEYCHAIN",!!l),hint:pZ()});let f=process.env.VISA_MOCK_TOUCHID,m=lB();n.push({key:"dev.mockTouchid",value:m,formatted:pA(m),source:T4e("VISA_MOCK_TOUCHID",!!f),hint:pZ()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:pA(!!h),source:T4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var H8e=require("node:os"),zk=require("node:path"),Lk=require("node:fs/promises"),Oft=require("node:fs"),Cft=require("node:url"),Rft=require("node:crypto");Hc();var awr=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function P4e(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!awr.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var V1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function I4e(e){let t;try{t=new URL(e)}catch{throw new V1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new V1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Hc();var cwr={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},plt=300*1e3,O4e={},C4e=0,Ek=null;function R4e(){return Ek||(Ek=(async()=>{try{let e=await ea.getFeatureFlags();O4e=e&&e.flags||{},C4e=Date.now()}catch(e){O4e={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{Ek=null}})(),Ek)}async function flt(){await R4e()}function mlt(){Date.now()-C4e<plt||R4e()}async function fA(){Date.now()-C4e<plt||await R4e()}function xm(e){let t=cwr[e];return t?O4e[t]!==!0:!1}var hlt=require("node:crypto"),xk=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},JJ=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 xk(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??hlt.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 kft(e){return[(0,zk.join)(e,"checkout-engine","index.js"),(0,zk.join)(e,"..","checkout-engine","index.js")]}function a3r(e,t=Oft.existsSync){return kft(e).find(r=>t(r))??null}var IY=null,Bft=async()=>{if(IY)return IY;let e=a3r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${kft(__dirname).join(" and ")}).`);return IY=(await import((0,Cft.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await c3r(),cardMandateRegister:await u3r()}),IY};async function c3r(){let e=await Promise.resolve().then(()=>(z8e(),D8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function u3r(){let e=await Promise.resolve().then(()=>(z8e(),D8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function F8e(){return xm("pay_merchant")?(await fA(),xm("pay_merchant")):!1}var Nft=(0,zk.join)((0,H8e.homedir)(),".visa-mcp","agent-credential.json"),jft=(0,zk.join)((0,H8e.homedir)(),".visa-mcp","contact.json"),Uft=new JJ;function Hk(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var d3r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function qft(e){return d3r.has(e)?e:null}async function OY(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,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?Hk(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:qft(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){Be.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function Ift(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?Hk(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:qft(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){Be.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function L8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new V1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Mft(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=Hk(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 Dft(e={},t={}){if(await(t.flagDisabled??F8e)())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??Uft).get(n);return o?Mft(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 zft(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:uZ()&&!process.env.VISA_VERIFY_WEB_URL?null:ol();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??F8e)())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??Uft,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=I4e(e.url??"").toString(),c=L8e(e.amount)}catch(C){if(C instanceof V1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Nft,l=t.contactPath??jft;try{await(0,Lk.readFile)(d,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry pay_merchant."}}let p;try{p=JSON.parse(await(0,Lk.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",I=/^PAY (\S+)$/.exec(C);if(!I)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=I[1]}let m=t.loadEngine??Bft,h;try{h=await m()}catch(C){let I=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(I))return{success:!1,message:/checkout engine was not packaged/.test(I)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let y={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},w=t.emitTelemetry??(C=>ea.emitTelemetry(C)),E=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:E,currency:u});let C;try{C=await h.review(y)}catch(I){throw await OY({emitTelemetry:w,action:"review",merchantHost:E,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await OY({emitTelemetry:w,action:"review",merchantHost:E,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${P4e(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:x,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:x,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await OY({emitTelemetry:w,action:"pay",merchantHost:E,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:v,submit:A}),j}let R=I.outcome==="confirmed"||I.outcome==="filled-dry-run";await OY({emitTelemetry:w,action:"pay",merchantHost:E,amountMinor:_,currency:u,outcome:I.outcome,confirmationRef:I.confirmationRef,success:R,errorMessage:R?null:I.detail??I.outcome,startedAt:v,submit:A,source:I.source??null,remainingMinor:I.remainingMinor??null,drawId:I.source==="mandate"?x:null});let q=I.source==="mandate"?` Drawn tap-free from an active card mandate${typeof I.remainingMinor=="number"?` (${I.remainingMinor} ${u} minor units remaining)`:""}.`:I.source==="fresh-tap"?" Paid with a fresh per-purchase passkey.":"";return{success:R,action:"pay",reviewId:x,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${q}`:`Outcome: ${I.outcome}${I.detail?` \u2014 ${I.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,Rft.createHash)("sha256").update(JSON.stringify([x,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:E,currency:u,submit:A});try{let I=await s.start({reviewId:x,fingerprint:C,run:async R=>{try{let q=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:x}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:q.success===!0}),q}catch(q){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:Hk(q instanceof Error?q.message:String(q))}),q}}});return Mft(I,"authorize")}catch(I){if(I instanceof xk)return Be.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 I}}return S()}async function Lft(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`start_card_mandate only supports the "card" rail (got ${JSON.stringify(r)}). For x402/stablecoin payments, use wallet_policy_set and wallet_pay.`};let n=t.verifyUrl!==void 0?t.verifyUrl:ol();if(n===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??F8e)())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 o=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(o))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};let s=e.anyMerchant===!0,a,c;try{a=s?void 0:I4e(e.url??"").toString(),c=L8e(e.ceiling??e.amount)}catch(A){if(A instanceof V1)return{success:!1,message:A.message};throw A}if(e.expiresAt!==void 0){let A=Date.parse(e.expiresAt);if(!Number.isFinite(A)||A<=Date.now())return{success:!1,message:`Invalid expiresAt ${JSON.stringify(e.expiresAt)}. Expected a future ISO 8601 timestamp.`}}if(e.maxDraws!==void 0&&(!Number.isSafeInteger(e.maxDraws)||e.maxDraws<1))return{success:!1,message:"maxDraws must be a positive integer."};let u;if(e.perTransaction!==void 0){try{u=L8e(e.perTransaction)}catch(A){if(A instanceof V1)return{success:!1,message:A.message};throw A}if(Number(u)>Number(c))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let d;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let A=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();d=A.length>0?A:void 0}let l=t.credentialPath??Nft,p=t.contactPath??jft;try{await(0,Lk.readFile)(l,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry start_card_mandate."}}let f;try{f=JSON.parse(await(0,Lk.readFile)(p,"utf8"))}catch{return{success:!1,message:`No contact details at ${p}. Write your name/email/address there (chmod 600) first.`}}let m=t.loadEngine??Bft,h;try{h=await m()}catch(A){let S=A instanceof Error?A.message:String(A);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(S))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 A}let y=s?"any-merchant":new URL(a).hostname,w=Math.round(Number(c)*100),E=t.emitTelemetry??(A=>ea.emitTelemetry(A)),_=Date.now();Be.info("start_card_mandate:create",{host:y,currency:o});let v;try{v=await h.startCardMandate({...a?{url:a}:{},ceiling:c,currency:o,credentialPath:l,contact:f,approvalBaseUrl:n,...s?{anyMerchant:!0}:{},...e.merchantName?{merchantName:e.merchantName}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.maxDraws!==void 0?{maxDraws:e.maxDraws}:{},...u!==void 0?{perTransaction:u}:{},...d!==void 0?{intent:d}:{}})}catch(A){let S=A instanceof Error?Hk(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await Ift({emitTelemetry:E,merchantHost:y,ceilingMinor:w,currency:o,outcome:"engine-error",success:!1,errorMessage:A instanceof Error?A.message:String(A),startedAt:_}),{success:!1,message:`Could not create the mandate: ${S}`}}let x=v.registerFailed===!0;return x&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await Ift({emitTelemetry:E,merchantHost:y,ceilingMinor:w,currency:o,outcome:x?"created-register-failed":"created",success:!x,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),x?{success:!1,mandateId:v.mandateId,ceiling:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,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:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${P4e(w,v.currencyCode)} at ${v.merchantHost} until ${v.expiresAt}. pay_merchant will now draw against it tap-free (no fresh passkey) until the budget is spent or it expires. NOTE: honoring a ceiling-scoped assurance across multiple draws is unproven live \u2014 if the network declines a draw, the budget is left untouched and that mandate is disabled, so your next pay_merchant uses a fresh per-purchase tap (it does NOT fall back within the same call).`}}var Bmt=require("node:crypto");var Omt=require("node:crypto");var jr={};ki(jr,{BRAND:()=>U3r,DIRTY:()=>Jv,EMPTY_PATH:()=>m3r,INVALID:()=>ht,NEVER:()=>p9r,OK:()=>oa,ParseStatus:()=>Es,Schema:()=>qt,ZodAny:()=>p2,ZodArray:()=>th,ZodBigInt:()=>Zv,ZodBoolean:()=>Xv,ZodBranded:()=>$k,ZodCatch:()=>uw,ZodDate:()=>Qv,ZodDefault:()=>cw,ZodDiscriminatedUnion:()=>kY,ZodEffects:()=>Qd,ZodEnum:()=>sw,ZodError:()=>zc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>NY,ZodIntersection:()=>nw,ZodIssueCode:()=>ye,ZodLazy:()=>iw,ZodLiteral:()=>ow,ZodMap:()=>CA,ZodNaN:()=>kA,ZodNativeEnum:()=>aw,ZodNever:()=>wp,ZodNull:()=>tw,ZodNullable:()=>Cm,ZodNumber:()=>Yv,ZodObject:()=>Lc,ZodOptional:()=>Zd,ZodParsedType:()=>Ce,ZodPipeline:()=>Vk,ZodPromise:()=>f2,ZodReadonly:()=>dw,ZodRecord:()=>BY,ZodSchema:()=>qt,ZodSet:()=>RA,ZodString:()=>l2,ZodSymbol:()=>IA,ZodTransformer:()=>Qd,ZodTuple:()=>Om,ZodType:()=>qt,ZodUndefined:()=>ew,ZodUnion:()=>rw,ZodUnknown:()=>eh,ZodVoid:()=>OA,addIssueToContext:()=>Ae,any:()=>tl,array:()=>ue,bigint:()=>z3r,boolean:()=>el,coerce:()=>qu,custom:()=>Jft,date:()=>L3r,datetimeRegex:()=>Wft,defaultErrorMap:()=>X1,discriminatedUnion:()=>G3r,effect:()=>i9r,enum:()=>rl,function:()=>Q3r,getErrorMap:()=>SA,getParsedType:()=>Im,instanceof:()=>M3r,intersection:()=>J3r,isAborted:()=>CY,isAsync:()=>TA,isDirty:()=>RY,isValid:()=>d2,late:()=>q3r,lazy:()=>e9r,literal:()=>t9r,makeIssue:()=>Fk,map:()=>Z3r,nan:()=>D3r,nativeEnum:()=>r9r,never:()=>V3r,null:()=>BA,nullable:()=>s9r,number:()=>Ir,object:()=>fe,objectUtil:()=>$8e,oboolean:()=>l9r,onumber:()=>d9r,optional:()=>o9r,ostring:()=>u9r,pipeline:()=>c9r,preprocess:()=>a9r,promise:()=>n9r,quotelessJson:()=>l3r,record:()=>Zt,set:()=>X3r,setErrorMap:()=>f3r,strictObject:()=>W3r,string:()=>z,symbol:()=>H3r,transformer:()=>i9r,tuple:()=>Y3r,undefined:()=>F3r,union:()=>NA,unknown:()=>$3r,util:()=>Yt,void:()=>K3r});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 $8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})($8e||($8e={}));var Ce=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Im=e=>{switch(typeof e){case"undefined":return Ce.undefined;case"string":return Ce.string;case"number":return Number.isNaN(e)?Ce.nan:Ce.number;case"boolean":return Ce.boolean;case"function":return Ce.function;case"bigint":return Ce.bigint;case"symbol":return Ce.symbol;case"object":return Array.isArray(e)?Ce.array:e===null?Ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ce.promise:typeof Map<"u"&&e instanceof Map?Ce.map:typeof Set<"u"&&e instanceof Set?Ce.set:typeof Date<"u"&&e instanceof Date?Ce.date:Ce.object;default:return Ce.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"]),l3r=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),zc=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()}};zc.create=e=>new zc(e);var p3r=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Ce.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}},X1=p3r;var Hft=X1;function f3r(e){Hft=e}function SA(){return Hft}var Fk=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}},m3r=[];function Ae(e,t){let r=SA(),n=Fk({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===X1?void 0:X1].filter(i=>!!i)});e.common.issues.push(n)}var Es=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 ht;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 ht;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}}},ht=Object.freeze({status:"aborted"}),Jv=e=>({status:"dirty",value:e}),oa=e=>({status:"valid",value:e}),CY=e=>e.status==="aborted",RY=e=>e.status==="dirty",d2=e=>e.status==="valid",TA=e=>typeof Promise<"u"&&e instanceof Promise;var Qe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Qe||(Qe={}));var Xd=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}},Fft=(e,t)=>{if(d2(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 zc(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return Im(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Im(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Es,ctx:{common:t.parent.common,data:t.data,parsedType:Im(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(TA(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:Im(t)},i=this._parseSync({data:t,path:n.path,parent:n});return Fft(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Im(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return d2(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=>d2(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:Im(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(TA(i)?i:Promise.resolve(i));return Fft(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 Qd({schema:this,typeName:wt.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 Zd.create(this,this._def)}nullable(){return Cm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return th.create(this)}promise(){return f2.create(this,this._def)}or(t){return rw.create([this,t],this._def)}and(t){return nw.create(this,t,this._def)}transform(t){return new Qd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new cw({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new $k({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new uw({...Bt(this._def),innerType:this,catchValue:r,typeName:wt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Vk.create(this,t)}readonly(){return dw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},h3r=/^c[^\s-]{8,}$/i,y3r=/^[0-9a-z]+$/,g3r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,b3r=/^[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,_3r=/^[a-z0-9_-]{21}$/i,v3r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,w3r=/^[-+]?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)?)??$/,E3r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,x3r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",V8e,A3r=/^(?:(?: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])$/,S3r=/^(?:(?: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])$/,T3r=/^(([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]))$/,P3r=/^(([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])$/,I3r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,O3r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vft="((\\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])))",C3r=new RegExp(`^${Vft}$`);function Kft(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 R3r(e){return new RegExp(`^${Kft(e)}$`)}function Wft(e){let t=`${Vft}T${Kft(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 k3r(e,t){return!!((t==="v4"||!t)&&A3r.test(e)||(t==="v6"||!t)&&T3r.test(e))}function B3r(e,t){if(!v3r.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 N3r(e,t){return!!((t==="v4"||!t)&&S3r.test(e)||(t==="v6"||!t)&&P3r.test(e))}var l2=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.string,received:o.parsedType}),ht}let n=new Es,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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?Ae(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ae(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")E3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")V8e||(V8e=new RegExp(x3r,"u")),V8e.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")b3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")_3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")h3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")y3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")g3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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),Ae(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),Ae(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),Ae(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),Ae(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Wft(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?C3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?R3r(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?w3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?k3r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?B3r(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?N3r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?I3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?O3r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Qe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Qe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Qe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Qe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Qe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Qe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Qe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Qe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Qe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Qe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Qe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Qe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Qe.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,...Qe.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,...Qe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Qe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Qe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Qe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Qe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Qe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Qe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Qe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Qe.errToObj(r)})}nonempty(t){return this.min(1,Qe.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}};l2.create=e=>new l2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function j3r(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 Yv=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ce.number){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.number,received:o.parsedType}),ht}let n,i=new Es;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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),Ae(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?j3r(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Qe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Qe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.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)}};Yv.create=e=>new Yv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var Zv=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ce.bigint)return this._getInvalidInput(t);let n,i=new Es;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),Ae(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),Ae(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),Ae(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 Ae(r,{code:ye.invalid_type,expected:Ce.bigint,received:r.parsedType}),ht}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.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:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.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}};Zv.create=e=>new Zv({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var Xv=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.boolean,received:n.parsedType}),ht}return oa(t.data)}};Xv.create=e=>new Xv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Qv=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.date,received:o.parsedType}),ht}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_date}),ht}let n=new Es,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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:Qe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Qe.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}};Qv.create=e=>new Qv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var IA=class extends qt{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.symbol,received:n.parsedType}),ht}return oa(t.data)}};IA.create=e=>new IA({typeName:wt.ZodSymbol,...Bt(e)});var ew=class extends qt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.undefined,received:n.parsedType}),ht}return oa(t.data)}};ew.create=e=>new ew({typeName:wt.ZodUndefined,...Bt(e)});var tw=class extends qt{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.null,received:n.parsedType}),ht}return oa(t.data)}};tw.create=e=>new tw({typeName:wt.ZodNull,...Bt(e)});var p2=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return oa(t.data)}};p2.create=e=>new p2({typeName:wt.ZodAny,...Bt(e)});var eh=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return oa(t.data)}};eh.create=e=>new eh({typeName:wt.ZodUnknown,...Bt(e)});var wp=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};wp.create=e=>new wp({typeName:wt.ZodNever,...Bt(e)});var OA=class extends qt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.void,received:n.parsedType}),ht}return oa(t.data)}};OA.create=e=>new OA({typeName:wt.ZodVoid,...Bt(e)});var th=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ae(r,{code:ye.invalid_type,expected:Ce.array,received:r.parsedType}),ht;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ae(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&&(Ae(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&&(Ae(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 Xd(r,s,r.path,a)))).then(s=>Es.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Xd(r,s,r.path,a)));return Es.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Qe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Qe.toString(r)}})}nonempty(t){return this.min(1,t)}};th.create=(e,t)=>new th({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function PA(e){if(e instanceof Lc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Zd.create(PA(n))}return new Lc({...e._def,shape:()=>t})}else return e instanceof th?new th({...e._def,type:PA(e.element)}):e instanceof Zd?Zd.create(PA(e.unwrap())):e instanceof Cm?Cm.create(PA(e.unwrap())):e instanceof Om?Om.create(e.items.map(t=>PA(t))):e}var Lc=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Yt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ce.object){let u=this._getOrReturnCtx(t);return Ae(u,{code:ye.invalid_type,expected:Ce.object,received:u.parsedType}),ht}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof wp&&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 Xd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof wp){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&&(Ae(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 Xd(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=>Es.mergeObjectSync(n,u)):Es.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Qe.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:Qe.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:wt.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 PA(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 Zd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return Gft(Yt.objectKeys(this.shape))}};Lc.create=(e,t)=>new Lc({shape:()=>e,unknownKeys:"strip",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});Lc.strictCreate=(e,t)=>new Lc({shape:()=>e,unknownKeys:"strict",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});Lc.lazycreate=(e,t)=>new Lc({shape:e,unknownKeys:"strip",catchall:wp.create(),typeName:wt.ZodObject,...Bt(t)});var rw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new zc(a.ctx.common.issues));return Ae(r,{code:ye.invalid_union,unionErrors:s}),ht}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 zc(c));return Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};rw.create=(e,t)=>new rw({options:e,typeName:wt.ZodUnion,...Bt(t)});var Q1=e=>e instanceof iw?Q1(e.schema):e instanceof Qd?Q1(e.innerType()):e instanceof ow?[e.value]:e instanceof sw?e.options:e instanceof aw?Yt.objectValues(e.enum):e instanceof cw?Q1(e._def.innerType):e instanceof ew?[void 0]:e instanceof tw?[null]:e instanceof Zd?[void 0,...Q1(e.unwrap())]:e instanceof Cm?[null,...Q1(e.unwrap())]:e instanceof $k||e instanceof dw?Q1(e.unwrap()):e instanceof uw?Q1(e._def.innerType):[],kY=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ae(r,{code:ye.invalid_type,expected:Ce.object,received:r.parsedType}),ht;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}):(Ae(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ht)}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=Q1(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:wt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function K8e(e,t){let r=Im(e),n=Im(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.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=K8e(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Ce.array&&n===Ce.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=K8e(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Ce.date&&n===Ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nw=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(CY(o)||CY(s))return ht;let a=K8e(o.value,s.value);return a.valid?((RY(o)||RY(s))&&r.dirty(),{status:r.value,value:a.data}):(Ae(n,{code:ye.invalid_intersection_types}),ht)};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}))}};nw.create=(e,t,r)=>new nw({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Om=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ae(n,{code:ye.invalid_type,expected:Ce.array,received:n.parsedType}),ht;if(n.data.length<this._def.items.length)return Ae(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ht;!this._def.rest&&n.data.length>this._def.items.length&&(Ae(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 Xd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Es.mergeArray(r,s)):Es.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Om.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Om({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var BY=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.object)return Ae(n,{code:ye.invalid_type,expected:Ce.object,received:n.parsedType}),ht;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Xd(n,a,n.path,a)),value:s._parse(new Xd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Es.mergeObjectAsync(r,i):Es.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:l2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},CA=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.map)return Ae(n,{code:ye.invalid_type,expected:Ce.map,received:n.parsedType}),ht;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Xd(n,a,n.path,[u,"key"])),value:o._parse(new Xd(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 ht;(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 ht;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};CA.create=(e,t,r)=>new CA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var RA=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ae(n,{code:ye.invalid_type,expected:Ce.set,received:n.parsedType}),ht;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ae(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&&(Ae(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 ht;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 Xd(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:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Qe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};RA.create=(e,t)=>new RA({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var NY=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ae(r,{code:ye.invalid_type,expected:Ce.function,received:r.parsedType}),ht;function n(a,c){return Fk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,SA(),X1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Fk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,SA(),X1].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 f2){let a=this;return oa(async function(...c){let u=new zc([]),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 oa(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new zc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new zc([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:Om.create(t).rest(eh.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||Om.create([]).rest(eh.create()),returns:r||eh.create(),typeName:wt.ZodFunction,...Bt(n)})}},iw=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};iw.create=(e,t)=>new iw({getter:e,typeName:wt.ZodLazy,...Bt(t)});var ow=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ae(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),ht}return{status:"valid",value:t.data}}get value(){return this._def.value}};ow.create=(e,t)=>new ow({value:e,typeName:wt.ZodLiteral,...Bt(t)});function Gft(e,t){return new sw({values:e,typeName:wt.ZodEnum,...Bt(t)})}var sw=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),ht}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 Ae(r,{received:r.data,code:ye.invalid_enum_value,options:n}),ht}return oa(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})}};sw.create=Gft;var aw=class extends qt{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Yt.objectValues(r);return Ae(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return oa(t.data)}get enum(){return this._def.values}};aw.create=(e,t)=>new aw({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var f2=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ae(r,{code:ye.invalid_type,expected:Ce.promise,received:r.parsedType}),ht;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return oa(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};f2.create=(e,t)=>new f2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Qd=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.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=>{Ae(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 ht;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ht:c.status==="dirty"?Jv(c.value):r.value==="dirty"?Jv(c.value):c});{if(r.value==="aborted")return ht;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ht:a.status==="dirty"?Jv(a.value):r.value==="dirty"?Jv(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"?ht:(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"?ht:(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(!d2(s))return ht;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=>d2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Yt.assertNever(i)}};Qd.create=(e,t,r)=>new Qd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Qd.createWithPreprocess=(e,t,r)=>new Qd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Zd=class extends qt{_parse(t){return this._getType(t)===Ce.undefined?oa(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Zd.create=(e,t)=>new Zd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Cm=class extends qt{_parse(t){return this._getType(t)===Ce.null?oa(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Cm.create=(e,t)=>new Cm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var cw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};cw.create=(e,t)=>new cw({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var uw=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return TA(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new zc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new zc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};uw.create=(e,t)=>new uw({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var kA=class extends qt{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.nan,received:n.parsedType}),ht}return{status:"valid",value:t.data}}};kA.create=e=>new kA({typeName:wt.ZodNaN,...Bt(e)});var U3r=Symbol("zod_brand"),$k=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Vk=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ht:o.status==="dirty"?(r.dirty(),Jv(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"?ht: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:wt.ZodPipeline})}},dw=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(d2(i)&&(i.value=Object.freeze(i.value)),i);return TA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};dw.create=(e,t)=>new dw({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function $ft(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Jft(e,t={},r){return e?p2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=$ft(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=$ft(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):p2.create()}var q3r={object:Lc.lazycreate},wt;(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"})(wt||(wt={}));var M3r=(e,t={message:`Input not instance of ${e.name}`})=>Jft(r=>r instanceof e,t),z=l2.create,Ir=Yv.create,D3r=kA.create,z3r=Zv.create,el=Xv.create,L3r=Qv.create,H3r=IA.create,F3r=ew.create,BA=tw.create,tl=p2.create,$3r=eh.create,V3r=wp.create,K3r=OA.create,ue=th.create,fe=Lc.create,W3r=Lc.strictCreate,NA=rw.create,G3r=kY.create,J3r=nw.create,Y3r=Om.create,Zt=BY.create,Z3r=CA.create,X3r=RA.create,Q3r=NY.create,e9r=iw.create,t9r=ow.create,rl=sw.create,r9r=aw.create,n9r=f2.create,i9r=Qd.create,o9r=Zd.create,s9r=Cm.create,a9r=Qd.createWithPreprocess,c9r=Vk.create,u9r=()=>z().optional(),d9r=()=>Ir().optional(),l9r=()=>el().optional(),qu={string:(e=>l2.create({...e,coerce:!0})),number:(e=>Yv.create({...e,coerce:!0})),boolean:(e=>Xv.create({...e,coerce:!0})),bigint:(e=>Zv.create({...e,coerce:!0})),date:(e=>Qv.create({...e,coerce:!0}))};var p9r=ht;var m9r=rl(["enc","sig"]),h9r=rl(["markdown","plain"]),y9r=rl(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),g9r=rl(["error","info","warning"]),qA=rl(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),b9r=rl(["completed","failed","pending"]),_9r=rl(["digital","pickup","shipping"]),v9r=rl(["fulfilled","partial","processing","removed"]),w9r=rl(["across","each"]),W8e=rl(["pickup","shipping"]),E9r=fe({config:Zt(z(),tl()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),x9r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:m9r.optional(),x:z().optional(),y:z().optional()}),A9r=fe({config:Zt(z(),tl()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),S9r=fe({endpoint:z()}),T9r=fe({schema:z()}),Yft=fe({endpoint:z(),schema:z()}),P9r=Yft,I9r=Yft,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),lo=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()}),G8e=lo,Zft=fe({id:z()}),O9r=Zft,C9r=Zft,Kk=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()}),jY=fe({type:z()}),Gi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),J8e=Gi,Xft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),UY=fe({amount:Ir(),display_text:z().optional(),type:z()}),m2=fe({title:z().optional(),type:z(),url:z()}),rh=fe({code:z().optional(),content:z(),content_type:h9r.optional(),path:z().optional(),severity:y9r.optional(),type:g9r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Y8e=rh,MA=fe({id:z(),label:z().optional(),permalink_url:z()}),R9r=fe({amount:Ir(),display_text:z()}),k9r=fe({config:Zt(z(),tl()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Z8e=fe({id:z(),quantity:Ir()}),B9r=Z8e,N9r=Z8e,j9r=Z8e,U9r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),q9r=fe({billing_address:Kk.optional(),credential:jY.optional(),display:Zt(z(),tl()).optional(),handler_id:z(),id:z(),type:z()}),M9r=fe({checkout_mandate:z()}),D9r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),z9r=fe({analytics:el().optional(),marketing:el().optional(),preferences:el().optional(),sale_of_data:el().optional()});var L9r=z9r;var Qft=fe({codes:ue(z()).optional()}),H9r=Qft,F9r=fe({amount:Ir(),path:z()}),$9r=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:Kk.optional(),name:z().optional()}),V9r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:qu.date().optional(),id:z(),latest_fulfillment_time:qu.date().optional(),title:z(),totals:ue(UY)}),K9r=fe({description:z().optional(),fulfillable_on:NA([BA(),z()]).optional(),line_item_ids:ue(z()),type:W8e}),W9r=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:Kk.optional(),name:z().optional()}),G9r=fe({max:Ir().optional(),min:Ir().optional()}),Wk=fe({taxonomy:z().optional(),value:z()}),Gk=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),jA=fe({amount:Ir(),currency:z()}),Jk=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),J9r=fe({id:z().optional(),label:z()}),Yk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),emt=fe({available:el().optional(),status:z().optional()}),Y9r=emt,tmt=fe({type:z(),value:z()}),Z9r=tmt,X9r=fe({id:z(),match:z().optional()}),X8e=fe({id:z().optional(),label:z(),name:z()}),rmt=X8e,nmt=fe({links:ue(m2).optional(),name:z().optional()}),Q9r=nmt,imt=fe({unit:z(),value:Ir()});var eEr=imt,tEr=fe({cursor:z().optional(),limit:Ir().optional()}),rEr=fe({cursor:z().optional(),has_next_page:el(),total_count:Ir().optional()}),nEr=fe({handlers:ue(E9r).optional()}),iEr=fe({a2a:S9r.optional(),embedded:T9r.optional(),mcp:P9r.optional(),rest:I9r.optional(),spec:z(),version:z()}),DA=fe({item:O9r,quantity:Ir()}),oEr=fe({billing_address:Kk.optional(),credential:jY.optional(),display:Zt(z(),tl()).optional(),handler_id:z(),id:z(),type:z(),selected:el().optional()}),Zk=fe({id:z().optional(),item:C9r,parent_id:z().optional(),quantity:Ir()}),qY=fe({instruments:ue(oEr).optional()}),sEr=qY,Xk=qY,zA=qY,MY=qY,lw=fe({id:z(),item:Xft,parent_id:z().optional(),quantity:Ir(),totals:ue(UY)}),h2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(R9r).optional()}),Ep=fe({capabilities:Zt(z(),ue(k9r)),version:z()}),aEr=fe({description:z().optional(),id:z(),line_items:ue(B9r).optional(),occurred_at:qu.date(),status:b9r,totals:ue(UY).optional(),type:z()}),cEr=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(N9r),occurred_at:qu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),uEr=fe({description:z().optional(),destination:Kk,fulfillable_on:z().optional(),id:z(),line_items:ue(j9r),method_type:_9r}),dEr=fe({id:z(),item:Xft,parent_id:z().optional(),quantity:U9r,status:v9r,totals:ue(UY)}),c4n=fe({payment_data:q9r}),u4n=fe({ap2:M9r.optional()}),d4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,ap2:D9r.optional()}),Q8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:L9r.optional()}),lEr=Q8e,pEr=Q8e,omt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional(),discounts:H9r.optional()}),fEr=fe({allocations:ue(F9r).optional(),amount:Ir(),automatic:el().optional(),code:z().optional(),eligibility:z().optional(),method:w9r.optional(),priority:Ir().optional(),provisional:el().optional(),title:z()}),smt=fe({id:z(),line_item_ids:ue(z()),options:ue(V9r).optional(),selected_option_id:NA([BA(),z()]).optional()}),mEr=fe({destinations:ue(W9r).optional(),groups:ue(smt).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:NA([BA(),z()]).optional(),type:W8e}),l4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),signals:Gi.optional()}),p4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),id:z(),line_items:ue(Zk),signals:Gi.optional()}),f4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2).optional(),messages:ue(rh).optional(),signals:Gi.optional(),totals:ue(h2),ucp:Ep}),hEr=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional()}),amt=hEr,m4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,cart_id:z().optional()}),e3e=fe({categories:ue(z()).optional(),price:G9r.optional()}),UA=fe({max:jA,min:jA}),t3e=fe({name:z(),values:ue(J9r)}),cmt=fe({amount:Ir(),currency:z(),measure:imt,reference:eEr}),yEr=cmt,h4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(rmt).optional(),signals:J8e.optional()}),y4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),pagination:tEr.optional(),query:z().optional(),signals:J8e.optional()}),gEr=fe({capabilities:ue(A9r),services:Zt(z(),iEr),version:z()}),g4n=fe({attribution:Zt(z(),z()).optional(),payment:sEr,signals:Gi.optional()}),umt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep}),bEr=fe({events:ue(cEr).optional(),expectations:ue(uEr).optional()}),dmt=fe({attribution:Zt(z(),z()).optional(),buyer:Q8e.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional()}),lmt=fe({attribution:Zt(z(),z()).optional(),buyer:pEr.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional()}),pmt=fe({attribution:Zt(z(),z()).optional(),buyer:lEr.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep}),fmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),discounts:Qft.optional()}),_Er=fe({applied:ue(fEr).optional(),codes:ue(z()).optional()}),vEr=fe({destinations:ue($9r).optional(),groups:ue(smt).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:NA([BA(),z()]).optional(),type:W8e}),wEr=fe({available_methods:ue(K9r).optional(),methods:ue(mEr).optional()}),mmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),cart_id:z().optional()}),b4n=fe({attribution:Zt(z(),z()).optional(),context:G8e.optional(),filters:e3e.optional(),ids:ue(z()),signals:J8e.optional()}),EEr=fe({availability:emt.optional(),barcodes:ue(tmt).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price:jA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(X8e).optional(),price:jA,rating:Yk.optional(),seller:nmt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:cmt.optional(),url:z().optional(),inputs:ue(X9r)}),hmt=fe({availability:Y9r.optional(),barcodes:ue(Z9r).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price:jA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(X8e).optional(),price:jA,rating:Yk.optional(),seller:Q9r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:yEr.optional(),url:z().optional()}),xEr=fe({categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(t3e).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(hmt)}),_4n=fe({payment:nEr.optional(),signing_keys:ue(x9r).optional(),ucp:gEr}),ymt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional()}),AEr=fe({adjustments:ue(aEr).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:bEr,id:z(),label:z().optional(),line_items:ue(dEr),messages:ue(rh).optional(),permalink_url:z(),totals:ue(h2),ucp:Ep}),gmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,discounts:_Er.optional()}),bmt=fe({methods:ue(vEr).optional()}),_mt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(Zk),payment:MY.optional(),signals:Gi.optional(),fulfillment:bmt.optional()}),vmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),continue_url:z().optional(),currency:z(),expires_at:qu.date().optional(),id:z(),line_items:ue(lw),links:ue(m2),messages:ue(rh).optional(),order:MA.optional(),payment:zA.optional(),signals:Gi.optional(),status:qA,totals:ue(h2),ucp:Ep,fulfillment:wEr.optional()}),SEr=fe({categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),options:ue(t3e).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(EEr)}),TEr=fe({options:ue(t3e).optional(),selected:ue(rmt).optional(),categories:ue(Wk).optional(),description:Gk,handle:z().optional(),id:z(),list_price_range:UA.optional(),media:ue(Jk).optional(),metadata:Zt(z(),tl()).optional(),price_range:UA,rating:Yk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(hmt)}),v4n=fe({messages:ue(Y8e).optional(),pagination:rEr.optional(),products:ue(xEr),ucp:Ep}),wmt=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:lo.optional(),line_items:ue(DA),payment:Xk.optional(),signals:Gi.optional(),fulfillment:bmt.optional()}),w4n=fe({messages:ue(Y8e).optional(),products:ue(SEr),ucp:Ep}),E4n=fe({messages:ue(Y8e).optional(),product:TEr,ucp:Ep});var T4n=jY.extend({token:jr.string().optional()}),PEr=jr.object({webhook_url:jr.string().url().optional()}),Emt=umt.extend(vmt.pick({fulfillment:!0}).shape).extend(gmt.pick({discounts:!0}).shape).extend(pmt.pick({buyer:!0}).shape).extend({platform:PEr.optional()}),xmt=ymt.extend(wmt.pick({fulfillment:!0}).shape).extend(fmt.pick({discounts:!0}).shape).extend(dmt.pick({buyer:!0}).shape).extend(mmt.pick({cart_id:!0}).shape),Amt=amt.extend(_mt.pick({fulfillment:!0}).shape).extend(omt.pick({discounts:!0}).shape).extend(lmt.pick({buyer:!0}).shape);Hc();async function DY(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 zY(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 IEr=3e4,Smt=2*1024*1024,xp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Tmt(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 Pmt(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"?xmt:Amt).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function OEr(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 Imt(e,t,r,n){try{e[t](r,n)}catch{}}function CEr(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 LY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Tmt(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Tmt(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??IEr,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Pmt(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:Pmt(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=zY(this.timeoutMs,this.signal),o=(0,Omt.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 DY(u,Smt,"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 xp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Smt)throw new xp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new xp("UCP MCP response is not valid JSON",void 0,u.status)}if(!OEr(l))throw new xp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new xp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new xp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new xp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new xp("UCP MCP response is missing result.structuredContent");if(!Emt.safeParse(CEr(p.structuredContent)).success)throw new xp("UCP checkout response failed schema validation");return Imt(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Imt(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 Rmt=require("node:crypto");Hc();var FY="2026-04-08",REr="dev.ucp.shopping",kEr="dev.ucp.shopping.checkout",BEr=1024*1024,NEr=1e4,jEr="https://ucp.dev",Qk=jr.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"),UEr=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Qk,schema:Qk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Qk.optional()}).passthrough(),qEr=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Qk,schema:Qk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),MEr=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(UEr)),capabilities:jr.record(jr.array(qEr)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function DEr(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 HY(e,t){if(new URL(e).origin!==jEr)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Cmt(e,t,r,n){try{e[t](r,n)}catch{}}async function zEr(e,t={}){let r=DEr(e,"UCP business URL"),n=zY(t.timeoutMs??NEr,t.signal),i=t.logger??Be,o=(0,Rmt.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 DY(c,BEr,"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=MEr.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Cmt(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 Cmt(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 LEr(e){if(e.ucp.version!==FY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[kEr]?.find(i=>i.version===FY);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");HY(t.spec,"Checkout capability spec"),HY(t.schema,"Checkout capability schema");let r=e.ucp.services[REr]?.find(i=>i.version===FY&&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");HY(r.spec,"Shopping service spec"),HY(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 kmt(e,t={}){let r=await zEr(e,t);return{...r,endpoint:LEr(r.profile),version:FY}}var HEr="https://app.visacli.sh/.well-known/ucp";function FEr(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 $Er(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 r3e(e,t=new Set){if(Array.isArray(e))for(let r of e)r3e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?$Er(n,t):r3e(n,t);return t}function VEr(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=r3e(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 KEr(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 WEr(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 Nmt(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??kmt)(e.business),i=await(t.getCheckout??(async(u,d)=>await new LY({endpoint:u.endpoint,platformProfileUrl:FEr(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??HEr)}).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=KEr(i),a=VEr(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Bmt.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:WEr(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>."}}gw();function GEr(){return Mu()}var ea=new dB(()=>zu.getSessionToken()),JEr="4.1.0-rc.37",o8n=["","","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(`
|
|
20780
20780
|
`);function YEr(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=GA(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(T3e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=WA();if(r.headless)return Be.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[GEr(),ol()].filter(s=>!!s).map(s=>i9e(t,s)).find(Boolean)??null;if(!i)return Be.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=vB(i);return o?((0,Umt.execFile)(o.cmd,o.args,s=>{s&&Be.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Be.info(`No browser command for platform "${VY.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function ZEr(){let e=!1,t;try{let n=qmt.join(VY.homedir(),".claude","settings.json");if($Y.existsSync(n)){let i=JSON.parse($Y.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=ult(o)}}catch{}let r=GJ();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function XEr(e){let t=await ea.getStatus(e);return t.hud=ZEr(),!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=JEr,t}async function QEr(e,t){return await ea.feedback(e.message,e.transaction_id,t)}async function exr(e){let t=await llt({api:ea,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 n3e=new Set(["auth.serverUrl"]);function eB(){return Object.keys(FA).filter(e=>!n3e.has(e)).sort()}function Mmt(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:eB()}}async function txr(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(n3e.has(e.key))return Be.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Mmt(e.key,"set");Be.info("config:set",{key:e.key});try{let t=A3e(e.key,e.value);return Be.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 km?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof km?`Unknown setting "${e.key}". MCP-settable keys: ${eB().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:eB()}}}async function rxr(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(n3e.has(e.key))return Be.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Mmt(e.key,"unset");Be.info("config:unset",{key:e.key});try{let t=S3e(e.key);return Be.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 km?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof km?`Unknown setting "${e.key}". MCP-settable keys: ${eB().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:eB()}}}async function nxr(e=ol(),t=!1){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};if(!t){let p=vk();if(p.kind==="claimed"){let f=p.credential,m;if(process.env.SUBWAY_MESH==="visa"&&f.name){let{registerOnVisaMeshIfEnabled:y}=await Promise.resolve().then(()=>(R8e(),mft));m=await y(f.name)}Be.info("agent:enroll_already_connected",{keyBound:f.keyBound,meshRegistered:m});let h=m===void 0?"":m?` Registered ${f.name??"this device"} on the .visa mesh.`:` Could not reach the .visa mesh \u2014 run \`visa register ${f.name??"<name>"}\` to join it.`;return{success:!0,alreadyConnected:!0,...f.name?{name:f.name}:{},keyBound:f.keyBound,...m!==void 0?{meshRegistered:m}:{},message:`This device is already connected${f.name?` as ${f.name}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).`+h+' Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.'}}}let{challenge:r,confirmCode:n,agentPkX:i,walletPkHex:o}=_k(),s=$A(e),a=`${s}?cli=${r}&cliPk=${i}${o?`&walletPk=${o}`:""}`;Be.info("agent:enroll_open",{url:s});let c=YEr(a),u="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint; already enrolled on the web? sign in \u2192 verify with your passkey \u2192 connect",d=`CONFIRMATION CODE: ${n} \u2014 the final screen will ask for it. Only enter it on a page YOU opened from this terminal; never share it or enter a code from a link someone sent you.`,l='When the final screen shows "Sent to your Visa CLI", call enroll_agent with {"action":"claim"} to store the enrollment credential on this device.';return c.opened?{success:!0,opened:!0,browserUrl:c.url,confirmCode:n,message:`Opened the Visa Verified Agent enrollment in your browser (${u}). ${d} ${l} Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:c.url??a,confirmCode:n,message:`Open this URL in a browser to enroll your agent (${u}): ${c.url??a} \u2014 ${d} ${l}`}}async function ixr(e=ol()){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};let t=await wk(e);switch(Be.info("agent:enroll_claim",{status:t.status}),t.status){case"claimed":return{success:!0,name:t.name,tokenId:t.tokenId,credentialPath:t.credentialPath,keyBound:t.keyBound,sessionSaved:t.sessionSaved,walletProvisioned:t.walletProvisioned,message:`Enrollment credential${t.name?` for ${t.name}`:""} stored at ${t.credentialPath} (token id ${t.tokenId}). The CLI purchase leg will read it from there.`+(t.keyBound?" The agent's key was generated on this terminal and its private half never left this device.":" Note: this terminal\u2019s agent key was not bound \u2014 normal when connecting an EXISTING agent from a returning sign-in (the agent keeps its original key); the credential works for purchases, but no agent key is held on this device.")+(t.sessionSaved?" This device is connected to your identity.":"")+(t.walletProvisioned?" Your x402 spending wallet is live on this device \u2014 fund the wallet address and you can pay (wallet_pay / visa pay).":"")};case"no_pending":return{success:!1,message:"No enrollment hand-off is in progress on this device \u2014 run enroll_agent first, finish the browser flow, then claim."};case"not_ready":return{success:!1,message:t.likelyExpired?"The hand-off window (15 minutes) has likely expired \u2014 run enroll_agent again, finish the browser flow, then claim.":'The enrollment credential is not ready yet \u2014 finish the browser flow through the final "minted" screen (it will say "Sent to your Visa CLI"), then claim again.'};case"confirm_mismatch":return{success:!1,confirmCode:t.confirmCode,message:`The confirmation code entered in the browser did not match this terminal, so the credential was refused. Your code is ${t.confirmCode} \u2014 re-enter it on the enrollment page ("Re-enter code"), then claim again. If YOU did not just complete the browser flow, someone else may have your enrollment link; run enroll_agent to start over with a fresh one.`};case"error":return{success:!1,message:t.message}}}async function jmt(){if(await zu.clearAll(),!!e9e())try{await t9e()}catch(e){Be.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function oxr(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Be.info("reset:attempt"),e.localOnly)return await jmt(),Be.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed. Use enroll_agent to connect this device again."};try{await ea.logout(void 0,t)}catch{}return await jmt(),Be.info("reset:success"),{success:!0,message:"Device reset. The server session, local credentials, and local keys have been removed. Use enroll_agent to connect this device again."}}async function sxr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>($v(),kk)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{CardRequiredError:r}=await Promise.resolve().then(()=>(QA(),G9e));return t instanceof r?{success:!1,card_required:!0,reason:t.reason,recovery_tool:"enroll_agent",error:t.message,message:`${t.message} Call enroll_agent, complete and claim V4 enrollment, then ask me to register again.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function axr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>($v(),kk));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function cxr(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(()=>($v(),kk)),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 uxr(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>($v(),kk)),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 Lo=class{static async subwayRegister(t){return sxr(t||{})}static async subwayFind(t){return axr(t||{})}static async subwaySend(t){return cxr(t||{})}static async subwayInbox(t){return uxr(t||{})}static async getStatus(t){return XEr(t)}static async feedback(t,r){return QEr(t,r)}static async configList(t){return exr(t||{})}static async configSet(t){return txr(t||{})}static async configUnset(t){return rxr(t||{})}static async reset(t,r){return oxr(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?nxr(void 0,t?.force===!0):n==="claim"?ixr():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens the enrollment flow) or "claim" (stores the credential after the browser flow finishes).`}}static async payMerchant(t={},r){return zft(t)}static async ucpCheckoutHandoff(t,r){return xm("ucp_checkout_handoff")&&(await fA(),xm("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."}:Nmt(t)}static async payMerchantStatus(t={},r){return Dft(t)}static async startCardMandate(t={},r){return Lft(t)}static async submitFeedback(t,r,n){Be.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await ea.submitFeedback(t,r,n);return Be.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Be.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Be.info("feedback:list",{limit:t||20});try{let n=await ea.getFeedback(t,r);return Be.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Be.error("feedback:error",{error:i}),n}}};function Dmt(e){return e==="pay_merchant"}Hc();var zmt="VISA_V4_WALLET_EXPERIMENT",dxr=null;function lxr(){return dxr??!0}var pxr=new Set(["1","true","on","yes"]),fxr=new Set(["0","false","off","no"]),Lmt=!1;function i3e(e,t){return Lmt||(Lmt=!0,Be.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function Fmt(){let e=(process.env[zmt]??"").trim().toLowerCase();if(pxr.has(e))return i3e(!0,"env-on");if(fxr.has(e))return i3e(!1,"env-off");e!==""&&Be.warn("wallet-experiment:unrecognized-env-value",{env:zmt,fallback:"bundled-runtime"});let t=lxr();return i3e(t,t?"bundled-runtime":"runtime-unavailable")}var Hmt=null;function $mt(){return Hmt??=$J(),Hmt}var mxr={user_context:{type:"string",description:"The exact verbatim request the user made that prompted this tool call. Always include the user's full original message."}};function hxr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...mxr},required:[...e.inputSchema.required||[],"user_context"]}}}function Vmt(){return Fmt()?$mt().WALLET_TOOL_DEFS.map(hxr):[]}function Kmt(e){return Fmt()?$mt().WALLET_TOOL_NAMES.includes(e):!1}async function Wmt(e,t,r={}){let i=await(await Promise.resolve().then(()=>Ze($J()))).dispatchWalletTool(e,t,{logger:Be,merchantDirectorySearch:r.merchantDirectorySearch});if(r.emitTelemetry&&(e==="wallet_pay"||e==="wallet_directory_pay")&&i.receipt)try{let o=yxr(e,t,i);o&&await r.emitTelemetry([o])}catch(o){Be.warn("wallet-experiment:telemetry-failed",{tool:e,error:o instanceof Error?o.message:String(o)})}return i}function yxr(e,t,r){if(e!=="wallet_pay"&&e!=="wallet_directory_pay")return null;let n=r.receipt&&typeof r.receipt=="object"&&!Array.isArray(r.receipt)?r.receipt:null;if(!n)return null;let i=typeof n.amountUsd=="string"?n.amountUsd:"",o=Number(i.replace(/[$,\s]/g,""));if(!Number.isFinite(o)||o<=0)return null;let s=r.directory&&typeof r.directory=="object"&&!Array.isArray(r.directory)?r.directory:null,a=s?.selection&&typeof s.selection=="object"&&!Array.isArray(s.selection)?s.selection:null,c=typeof t.url=="string"?t.url:typeof a?.url=="string"?a.url:"",u="Pay-per-use service";try{u=new URL(c).hostname.toLowerCase()}catch{}let d=typeof n.timestamp=="string"?n.timestamp:new Date().toISOString(),l=typeof n.network=="string"?n.network:null,p=typeof n.scheme=="string"?n.scheme:null,f=typeof n.txHash=="string"?n.txHash:null;return{timestamp:d,tool_name:e,user_prompt:"",tool_params:JSON.stringify({merchant_host:u,network:l,scheme:p}),result_success:!0,result_error:null,result_json:JSON.stringify({network:l,scheme:p}),payment_rail:"stablecoin",payment_amount:o,payment_currency:"USDC",merchant_name:u,transaction_id:null,tx_hash:f,protocol:"x402",http_status:null,duration_ms:0,source:"cli",endpoint:"/v4/wallet",resolved_model:null,session_budget_id:null}}Hc();var o3e=["pay_merchant"],gxr={pay_merchant:"merchant checkout"};function bxr(e){return gxr[e]||e}var Gmt={};function Jmt(e){let t=Gmt[e]??0;return Gmt[e]=t+1,t}function Ymt(e,t,r){return o3e.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${bxr(e)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:r}}:t%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:r}}:{}:{}}var WY=Ze(require("crypto")),GY=Ze(require("tty")),pw=Ze(require("fs")),a3e=Ze(require("os")),KY=Ze(require("path"));lZ();KA();var _xr=new Set(["connect","disconnect","connections"]);function vxr(e){return e!==void 0&&_xr.has(e)}function wxr(e){return/-rc\.|-beta\./.test(e)}function s3e(e){return WY.createHash("sha256").update(e.trim()).digest("hex")}function Zmt(e){return Bm==="SKIP"?!0:WY.timingSafeEqual(Buffer.from(s3e(e)),Buffer.from(Bm))}function Exr(){return KY.join(a3e.homedir(),".visa-mcp","agent-credential.json")}function xxr(){let e=process.env.VISA_V4_HOME||KY.join(a3e.homedir(),".visa-v4");return KY.join(e,"turnkey.json")}function Axr(){try{let e=pw.readFileSync(Exr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=pw.readFileSync(xxr(),"utf8"),t=JSON.parse(e);return typeof t?.organizationId=="string"&&t.organizationId.length>0&&typeof t?.walletId=="string"&&t.walletId.length>0&&typeof t?.address=="string"&&/^0x[0-9a-f]{40}$/i.test(t.address)}catch{return!1}}function Sxr(){try{let e=pw.openSync("/dev/tty","r+"),t=new GY.ReadStream(e),r=new GY.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{pw.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function Txr(e){return new Promise((t,r)=>{let n;try{n=Sxr()}catch(d){r(d);return}let{input:i,output:o,cleanupStreams:s}=n,a=()=>{i.off("data",u);try{i.setRawMode?.(!1)}catch{}s()};o.write(e),i.setRawMode?.(!0),i.resume(),i.setEncoding("utf8");let c="",u=d=>{d==="\r"||d===`
|
|
20781
20781
|
`?(o.write(`
|
|
20782
20782
|
`),a(),t(c)):d===""?(o.write(`
|