@visa/cli 4.1.0-rc.28 → 4.1.0-rc.29

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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";var Pmt=Object.create;var qk=Object.defineProperty;var Imt=Object.getOwnPropertyDescriptor;var Omt=Object.getOwnPropertyNames;var Cmt=Object.getPrototypeOf,Rmt=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}},Gi=(e,t)=>{for(var r in t)qk(e,r,{get:t[r],enumerable:!0})},N8e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Omt(t))!Rmt.call(e,i)&&i!==r&&qk(e,i,{get:()=>t[i],enumerable:!(n=Imt(t,i))||n.enumerable});return e};var Ze=(e,t,r)=>(r=e!=null?Pmt(Cmt(e)):{},N8e(t||!e||!e.__esModule?qk(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>N8e(qk({},"__esModule",{value:!0}),e);var Dk,L8e,H8e,PY,Q1,IY=P(()=>{"use strict";Dk=Ze(require("fs")),L8e=Ze(require("path")),H8e=Ze(require("os")),PY=L8e.join(H8e.homedir(),".visa-mcp"),Q1=class{static ensureConfigDir(){Dk.existsSync(PY)||Dk.mkdirSync(PY,{recursive:!0,mode:448})}static getConfigDir(){return PY}}});function jmt(){Ma.existsSync(CY)||Ma.mkdirSync(CY,{recursive:!0,mode:448})}function qmt(){if(!OY){if(jmt(),Ma.existsSync(IA)&&Ma.statSync(IA).size>Nmt){let t=IA+".1";Ma.existsSync(t)&&Ma.unlinkSync(t),Ma.renameSync(IA,t)}OY=Ma.createWriteStream(IA,{flags:"a"})}return OY}function Umt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function zk(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
- `;Umt(e)&&process.stderr.write(i),qmt().write(i)}var Ma,RY,F8e,CY,IA,Nmt,OY,Be,Dc=P(()=>{"use strict";Ma=Ze(require("fs")),RY=Ze(require("path")),F8e=Ze(require("os")),CY=RY.join(F8e.homedir(),".visa-mcp"),IA=RY.join(CY,"mcp-server.log"),Nmt=5*1024*1024,OY=null;Be={debug:(...e)=>zk("DEBUG",...e),info:(...e)=>zk("INFO",...e),warn:(...e)=>zk("WARN",...e),error:(...e)=>zk("ERROR",...e)}});var Lk=g((Lxr,Mmt)=>{Mmt.exports={name:"@visa/cli",version:"4.1.0-rc.28",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 $8e(e){let t=V8e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Hk(){return K8e.join(Q1.getConfigDir(),Dmt)}function W8e(e){if((0,BY.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Lmt(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 W8e(i)}function Hmt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,BY.isIP)(t);return r===4?W8e(t):r===6?t==="::1"||Lmt(t):!1}function kY(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:"&&Hmt(r.hostname)))throw new Error(`${t} ${zmt}`)}function Fk(){let e=Hk();if(!eh.existsSync(e))return{};try{let t=eh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Be.warn("settings:corrupt",{path:$8e(e),reason:"not_object"}),{}):r}catch(t){return Be.warn("settings:corrupt",{path:$8e(e),error:t?.message||String(t)}),{}}}function G8e(e){Q1.ensureConfigDir();let t=Hk(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
4
- `;eh.writeFileSync(r,n,{mode:384}),eh.renameSync(r,t)}function NY(e){let t=Fk()[e];return typeof t=="string"?t:void 0}function jY(e){let t=Fk()[e];return typeof t=="boolean"?t:void 0}function J8e(e,t){let r=OA[e];if(!r)throw new Im(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=Fk();return i[e]=n,G8e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Hk()}}function Y8e(e){let t=OA[e];if(!t)throw new Im(e);let r=Fk(),n=e in r;return n&&(delete r[e],G8e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Hk()}}function Vmt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Kmt(){try{let e=Lk();return Vmt(e.version)}catch{return!1}}function Wmt(e){return e.envVar!==void 0&&e.envVar!==""?(kY(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(kY(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?$mt:Fmt}function ju(){return Wmt({envVar:process.env.VISA_AUTH_URL,settingValue:NY("auth.serverUrl"),isPrerelease:Kmt()})}function Z8e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":jY("ui.suppressBrowser")??!1}var eh,BY,V8e,K8e,Dmt,zmt,OA,Im,Fmt,$mt,s4=P(()=>{"use strict";eh=Ze(require("fs")),BY=require("node:net"),V8e=Ze(require("os")),K8e=Ze(require("path"));IY();Dc();Dmt="settings.json",zmt="must use https unless it points at localhost/loopback for local development";OA={"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");kY(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Im=class extends Error{constructor(t){let r=Object.keys(OA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Fmt="https://auth.visacli.sh",$mt="https://auth-visa-code-preview.up.railway.app"});function qY(e=Qmt){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function X8e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rl(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return X8e(t||e0t)}function Kk(e){return`${X8e(e)}${t0t}`}var Qmt,e0t,t0t,UY=P(()=>{"use strict";Qmt="4.1.0-rc.28",e0t="https://app.visacli.sh",t0t="/agent/enroll"});var Om,MY=P(()=>{"use strict";Om="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function n3e(e){return`${e}-${t3e.randomBytes(24).toString("base64url")}`}function i3e(e=process.env){return e.NODE_ENV==="test"||e[r3e]==="true"}function th(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&i3e(e)}function Wk(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&i3e(e)}function DY(){return`Set ${r3e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function o3e(){return Q8e??=n3e("mock-session"),Q8e}function s3e(e=process.env){return e.NODE_ENV==="test"?Om:(e3e??=n3e("mock-rc"),e3e)}var t3e,r3e,Q8e,e3e,Gk=P(()=>{"use strict";t3e=Ze(require("crypto"));MY();r3e="VISA_ALLOW_INSECURE_MOCKS"});function n0t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
3
+ `;Umt(e)&&process.stderr.write(i),qmt().write(i)}var Ma,RY,F8e,CY,IA,Nmt,OY,Be,Dc=P(()=>{"use strict";Ma=Ze(require("fs")),RY=Ze(require("path")),F8e=Ze(require("os")),CY=RY.join(F8e.homedir(),".visa-mcp"),IA=RY.join(CY,"mcp-server.log"),Nmt=5*1024*1024,OY=null;Be={debug:(...e)=>zk("DEBUG",...e),info:(...e)=>zk("INFO",...e),warn:(...e)=>zk("WARN",...e),error:(...e)=>zk("ERROR",...e)}});var Lk=g((Lxr,Mmt)=>{Mmt.exports={name:"@visa/cli",version:"4.1.0-rc.29",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 $8e(e){let t=V8e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Hk(){return K8e.join(Q1.getConfigDir(),Dmt)}function W8e(e){if((0,BY.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Lmt(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 W8e(i)}function Hmt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,BY.isIP)(t);return r===4?W8e(t):r===6?t==="::1"||Lmt(t):!1}function kY(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:"&&Hmt(r.hostname)))throw new Error(`${t} ${zmt}`)}function Fk(){let e=Hk();if(!eh.existsSync(e))return{};try{let t=eh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Be.warn("settings:corrupt",{path:$8e(e),reason:"not_object"}),{}):r}catch(t){return Be.warn("settings:corrupt",{path:$8e(e),error:t?.message||String(t)}),{}}}function G8e(e){Q1.ensureConfigDir();let t=Hk(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
4
+ `;eh.writeFileSync(r,n,{mode:384}),eh.renameSync(r,t)}function NY(e){let t=Fk()[e];return typeof t=="string"?t:void 0}function jY(e){let t=Fk()[e];return typeof t=="boolean"?t:void 0}function J8e(e,t){let r=OA[e];if(!r)throw new Im(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=Fk();return i[e]=n,G8e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Hk()}}function Y8e(e){let t=OA[e];if(!t)throw new Im(e);let r=Fk(),n=e in r;return n&&(delete r[e],G8e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Hk()}}function Vmt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Kmt(){try{let e=Lk();return Vmt(e.version)}catch{return!1}}function Wmt(e){return e.envVar!==void 0&&e.envVar!==""?(kY(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(kY(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?$mt:Fmt}function ju(){return Wmt({envVar:process.env.VISA_AUTH_URL,settingValue:NY("auth.serverUrl"),isPrerelease:Kmt()})}function Z8e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":jY("ui.suppressBrowser")??!1}var eh,BY,V8e,K8e,Dmt,zmt,OA,Im,Fmt,$mt,s4=P(()=>{"use strict";eh=Ze(require("fs")),BY=require("node:net"),V8e=Ze(require("os")),K8e=Ze(require("path"));IY();Dc();Dmt="settings.json",zmt="must use https unless it points at localhost/loopback for local development";OA={"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");kY(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Im=class extends Error{constructor(t){let r=Object.keys(OA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Fmt="https://auth.visacli.sh",$mt="https://auth-visa-code-preview.up.railway.app"});function qY(e=Qmt){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function X8e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rl(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return X8e(t||e0t)}function Kk(e){return`${X8e(e)}${t0t}`}var Qmt,e0t,t0t,UY=P(()=>{"use strict";Qmt="4.1.0-rc.29",e0t="https://app.visacli.sh",t0t="/agent/enroll"});var Om,MY=P(()=>{"use strict";Om="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function n3e(e){return`${e}-${t3e.randomBytes(24).toString("base64url")}`}function i3e(e=process.env){return e.NODE_ENV==="test"||e[r3e]==="true"}function th(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&i3e(e)}function Wk(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&i3e(e)}function DY(){return`Set ${r3e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function o3e(){return Q8e??=n3e("mock-session"),Q8e}function s3e(e=process.env){return e.NODE_ENV==="test"?Om:(e3e??=n3e("mock-rc"),e3e)}var t3e,r3e,Q8e,e3e,Gk=P(()=>{"use strict";t3e=Ze(require("crypto"));MY();r3e="VISA_ALLOW_INSECURE_MOCKS"});function n0t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
5
5
  `)}function VY(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=n0t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function ih(){return process.platform!=="darwin"?Promise.resolve(!1):(a3e??=(async()=>{try{return await nl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return VY(e)}})(),a3e)}async function i0t(){if(!await ih())return null;try{let{stdout:e}=await nl("security",["find-generic-password","-s",qu,"-a",rh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(VY(e))throw new Yk("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 o0t(e){if(!await ih())return!1;try{try{await nl("security",["delete-generic-password","-s",qu,"-a",rh],{timeout:5e3})}catch{}return await nl("security",["add-generic-password","-s",qu,"-a",rh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function s0t(){if(await ih())try{await nl("security",["delete-generic-password","-s",qu,"-a",rh],{timeout:5e3})}catch{}}async function a0t(){if(!KY())return null;try{let{stdout:e}=await nl("secret-tool",["lookup","service",qu,"account",rh],{timeout:5e3});return e.trim()||null}catch{return null}}async function c0t(e){if(!KY())return!1;try{let t=(0,Zk.execFile)("secret-tool",["store","--label",`${qu} ${rh}`,"service",qu,"account",rh]);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"))},r0t))]),!0):!1}catch{return!1}}async function u0t(){if(KY())try{await nl("secret-tool",["clear","service",qu,"account",rh],{timeout:5e3})}catch{}}function KY(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function d0t(){if(!await ih())return null;try{let{stdout:e}=await nl("security",["find-generic-password","-s",qu,"-a",Jk,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function l0t(e){if(await ih())try{try{await nl("security",["delete-generic-password","-s",qu,"-a",Jk],{timeout:5e3})}catch{}await nl("security",["add-generic-password","-s",qu,"-a",Jk,"-w",e],{timeout:5e3})}catch{}}async function p0t(){if(await ih())try{await nl("security",["delete-generic-password","-s",qu,"-a",Jk],{timeout:5e3})}catch{}}function LY(){try{return nh.readFileSync(CA,"utf-8").trim()||null}catch(e){if(VY(e))throw new Yk(`Unable to read Visa CLI credentials from ${CA}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function u3e(e){nh.mkdirSync($Y,{recursive:!0,mode:448}),nh.writeFileSync(CA,e,{mode:384}),process.platform==="win32"&&f0t(CA)}function HY(){try{nh.unlinkSync(CA)}catch{}}function f0t(e){try{let t=Xk.userInfo().username;(0,Zk.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 zY(){switch(process.platform){case"darwin":return{get:i0t,store:o0t,delete:s0t};case"linux":return{get:a0t,store:c0t,delete:u0t};default:return{get:async()=>LY(),store:async e=>{try{return u3e(e),!0}catch{return!1}},delete:async()=>HY(),storesInSessionFile:!0}}}var Zk,c3e,nh,Xk,FY,nl,$Y,CA,qu,rh,Jk,r0t,Yk,a3e,Uu,RA=P(()=>{"use strict";Zk=require("child_process"),c3e=require("util"),nh=Ze(require("fs")),Xk=Ze(require("os")),FY=Ze(require("path"));Gk();nl=(0,c3e.promisify)(Zk.execFile),$Y=FY.join(Xk.homedir(),".visa-mcp"),CA=FY.join($Y,"session-token"),qu="visa-cli",rh="session-token",Jk="rc-access",r0t=5e3,Yk=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};a3e=null;Uu=class{static async getSessionToken(){if(th())return Promise.resolve(o3e());let t=zY(),r=await t.get();if(r)return r;let n=LY();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(th())return;let r=zY();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||HY();return}await r.delete()}if(u3e(t),LY()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${$Y} is writable.`))}static async getRcAccessToken(){return th()?s3e():d0t()}static async saveRcAccessToken(t){th()||await l0t(t)}static async deleteSessionToken(){if(th())return;await zY().delete(),HY()}static async clearAll(){await this.deleteSessionToken(),await p0t()}}});function kA(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 E0t(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 BA(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 O3e(e,t){let r=BA(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 C3e(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 rB(e,t=process.platform){let r=BA(e);return r?C3e(r,t):null}function P3e(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function nB(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=BA(e),s=t.spawn??((u,d,l)=>{(0,I3e.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 E0t(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=kA(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=C3e(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?P3e(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){P3e(r,l instanceof Error?l:new Error(String(l))),u()}})}var I3e,WY=P(()=>{"use strict";I3e=require("child_process")});function F0t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function n9e(e,t,r=""){let n=F0t(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 M3e(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 $0t(e,t){n9e(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 tZ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ZY(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function V0t(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 G0t(e,t=!1){return t?{h:Number(e&iB),l:Number(e>>D3e&iB)}:{h:Number(e>>D3e&iB)|0,l:Number(e&iB)|0}}function J0t(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}=G0t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function km(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function a1t(){return D0t.randomSecretKey()}function jA(e){return N0t(e)}function pB(){let e=a1t();return{secretKey:e,publicKey:jA(e)}}function o9e(e){if(e.length!==F3e)throw new Error(`Ed25519 seed must be ${F3e} bytes, got ${e.length}`);return{secretKey:e,publicKey:jA(e)}}function p4(e,t){return U0t(t,e)}function c1t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function u1t(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 rZ(e){return c1t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d1t(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return u1t(r)}function l1t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function f4(e){let t=jA(e);return{kty:"OKP",crv:"Ed25519",x:rZ(t),d:rZ(e)}}function ch(e){return{kty:"OKP",crv:"Ed25519",x:rZ(e)}}function qA(e){if(l1t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return d1t(e.d)}function c9e(){return UA.default.randomBytes(32).toString("base64url")}function u9e(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return pZ(e)}function f1t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function m1t(e){let t=f1t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function d9e(){return UA.default.randomBytes(32).toString("base64url")}function lZ(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("claim token must be 32 unpadded base64url bytes");return pZ(`visa-agent-pairing-claim-token:v1:${e}`)}function fB(e,t){lZ(t);let r=UA.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<p1t;i+=1)n+=dZ[r[i]&a9e];return m1t(n)}function l9e(e){return m9e("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 p9e(e){return m9e("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function f9e(e){return pZ(`visa-agent-pairing-artifacts:v1:${nZ(e)}`)}function pZ(e){return UA.default.createHash("sha256").update(e,"utf8").digest("base64url")}function m9e(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 g4r.encode(r)}function v4r(e,t,r,n,i,o,s){return _4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function w4r(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 V4r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Ylt(e,t,r=""){let n=V4r(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 plt(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 K4r(e,t){Ylt(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 xwe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ywe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function W4r(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 Y4r(e,t=!1){return t?{h:Number(e&kJ),l:Number(e>>flt&kJ)}:{h:Number(e>>flt&kJ)|0,l:Number(e&kJ)|0}}function Z4r(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}=Y4r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function K1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function uwr(){return L4r.randomSecretKey()}function Xlt(e){return D4r(e)}function dwr(){let e=uwr();return{secretKey:e,publicKey:Xlt(e)}}function lwr(e){if((0,Qb.existsSync)(e)){let r=(0,Qb.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:Xlt(n)}}let t=dwr();return(0,Qb.mkdirSync)((0,blt.dirname)(e),{recursive:!0}),(0,Qb.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function pwr(e){let{secretKey:t,publicKey:r}=lwr(e);return{privateKey:t,publicKey:r}}async function fwr(e,t,r,n,i,o,s,a){let c=v4r(t,r,n,i,o,s,a);return{signature:await m4r(e,c),signatureInput:b4r.subwayAgentMsgV1}}function glt(e){return y4r(e)}var Qb,blt,xvr,Evr,Avr,Svr,Tvr,_lt,UJ,jJ,Wdt,Gdt,uwe,dwe,Pvr,FJ,Ivr,bs,Ovr,Cvr,Rvr,W1,$J,Ewe,vlt,Awe,F1,Jdt,Swe,wlt,kvr,sA,Bvr,MJ,Sv,Tn,Ydt,Ve,xlt,Elt,Alt,Slt,lwe,gwe,dk,Rv,Ov,Tlt,Plt,wm,Nvr,Zdt,jvr,bwe,Twe,qvr,Ilt,Uvr,Mvr,Dvr,zvr,Lvr,Hvr,Pwe,Olt,DJ,Fvr,Clt,_we,$vr,Xdt,Qdt,Vvr,Blt,Nlt,Wb,ra,OJ,tlt,rlt,nlt,rA,nA,CJ,RJ,Xvr,Qvr,e4r,t4r,r4r,n4r,i4r,Gb,o4r,s4r,jlt,a4r,c4r,Jb,Yb,u4r,d4r,l4r,p4r,ilt,h4r,qlt,g4r,b4r,Ult,x4r,Mlt,zJ,qJ,olt,slt,fwe,mwe,E4r,aA,A4r,_s,S4r,T4r,P4r,e2,VJ,Iwe,Dlt,zlt,V1,alt,Llt,Hlt,I4r,Owe,O4r,LJ,Pv,Fn,clt,Ke,C4r,R4r,Flt,$lt,hwe,vwe,lk,cA,Cv,k4r,Vlt,Em,B4r,ult,N4r,j4r,q4r,U4r,Klt,M4r,Wlt,D4r,Glt,z4r,L4r,HJ,H4r,Jlt,wwe,F4r,dlt,llt,$4r,G4r,J4r,na,kJ,flt,mlt,hlt,iA,oA,BJ,NJ,X4r,Q4r,ewr,twr,rwr,nwr,Zlt,iwr,owr,Zb,Xb,swr,awr,cwr,ylt,mwr,hwr,Qlt,ept=P(()=>{"use strict";swe();swe();awe();Qb=require("fs"),blt=require("path");xvr=1e3,Evr=10,Avr=3e4,Svr=3e4,Tvr=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??xvr,this.maxReconnectAttempts=e.maxReconnectAttempts??Evr,this.pingInterval=e.pingInterval??Avr}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=vvr();if(!r){t(new ta('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 ta(`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 ta("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ta(`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 ta("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=wvr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Svr);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)}}},_lt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:UJ,n:jJ,Gx:Wdt,Gy:Gdt,a:uwe,d:dwe,h:Pvr}=_lt,FJ=32,Ivr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},bs=(e="")=>{let t=new Error(e);throw Ivr(t,bs),t},Ovr=e=>typeof e=="bigint",Cvr=e=>typeof e=="string",Rvr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,W1=(e,t,r="")=>{let n=Rvr(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e},$J=e=>new Uint8Array(e),Ewe=e=>Uint8Array.from(e),vlt=(e,t)=>e.toString(16).padStart(t,"0"),Awe=e=>Array.from(W1(e)).map(t=>vlt(t,2)).join(""),F1={_0:48,_9:57,A:65,F:70,a:97,f:102},Jdt=e=>{if(e>=F1._0&&e<=F1._9)return e-F1._0;if(e>=F1.A&&e<=F1.F)return e-(F1.A-10);if(e>=F1.a&&e<=F1.f)return e-(F1.a-10)},Swe=e=>{let t="hex invalid";if(!Cvr(e))return bs(t);let r=e.length,n=r/2;if(r%2)return bs(t);let i=$J(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Jdt(e.charCodeAt(s)),c=Jdt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return bs(t);i[o]=a*16+c}return i},wlt=()=>globalThis?.crypto,kvr=()=>wlt()?.subtle??bs("crypto.subtle must be defined, consider polyfill"),sA=(...e)=>{let t=0;for(let i of e)t+=W1(i).length;let r=$J(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Bvr=(e=FJ)=>wlt().getRandomValues($J(e)),MJ=BigInt,Sv=(e,t,r,n="bad number: out of range")=>{if(!Ovr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Tn=(e,t=UJ)=>{let r=e%t;return r>=0n?r:t+r},Ydt=(1n<<255n)-1n,Ve=e=>{e<0n&&bs("negative coordinate");let t=(e>>255n)*19n+(e&Ydt);return t=(t>>255n)*19n+(t&Ydt),t%UJ},xlt=e=>Tn(e,jJ),Elt=(e,t)=>{(e===0n||t<=0n)&&bs("no inverse n="+e+" mod="+t);let r=Tn(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?Tn(i,t):bs("no inverse")},Alt=e=>{let t=Olt[e];return typeof t!="function"&&bs("hashes."+e+" not set"),t},Slt=e=>W1(e,64,"digest"),lwe=e=>e instanceof dk?e:bs("Point expected"),gwe=2n**256n,dk=class Tv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=gwe;this.X=Sv(t,0n,o),this.Y=Sv(r,0n,o),this.Z=Sv(n,1n,o),this.T=Sv(i,0n,o),Object.freeze(this)}static CURVE(){return _lt}static fromAffine(t){return new Tv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=dwe,i=Ewe(W1(t,FJ)),o=t[31];i[31]=o&-129;let s=Plt(i);Sv(s,0n,r?gwe:UJ);let c=Ve(s*s),u=Tn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=jvr(u,d);l||bs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&bs("bad point: x==0, isLastByteOdd"),m!==f&&(p=Tn(-p)),new Tv(p,s,1n,Ve(p*s))}static fromHex(t,r){return Tv.fromBytes(Swe(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=uwe,r=dwe,n=this;if(n.is0())return bs("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=Tn(l+Ve(r*Ve(c*u)));if(f!==m)return bs("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?bs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=lwe(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(Ov)}negate(){return new Tv(Tn(-this.X),this.Y,this.Z,Tn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=uwe,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Tn(t+r),d=Tn(Ve(u*u)-o-s),l=Tn(c+s),p=Tn(l-a),f=Tn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new Tv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=lwe(t),d=uwe,l=dwe,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Tn(Ve(Tn(r+n)*Tn(s+a))-p-f),w=Tn(h-m),x=Tn(h+m),_=Tn(f-Ve(d*p)),v=Ve(y*w),E=Ve(x*_),A=Ve(y*_),S=Ve(w*x);return new Tv(v,E,S,A)}subtract(t){return this.add(lwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Sv(t,1n,jJ),!r&&this.is0()))return Ov;if(t===1n)return this;if(this.equals(Rv))return Vvr(t).p;let n=Ov,i=Rv;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(Ov))return{x:0n,y:1n};let i=Elt(n,UJ);Ve(n*i)!==1n&&bs("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=Tlt(r);return n[31]|=t&1n?128:0,n}toHex(){return Awe(this.toBytes())}clearCofactor(){return this.multiply(MJ(Pvr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(jJ/2n,!1).double();return jJ%2n&&(t=t.add(this)),t.is0()}},Rv=new dk(Wdt,Gdt,1n,Tn(Wdt*Gdt)),Ov=new dk(0n,1n,1n,0n);dk.BASE=Rv;dk.ZERO=Ov;Tlt=e=>Swe(vlt(Sv(e,0n,gwe),64)).reverse(),Plt=e=>MJ("0x"+Awe(Ewe(W1(e)).reverse())),wm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Nvr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(wm(r,2n)*r),i=Ve(wm(n,1n)*e),o=Ve(wm(i,5n)*i),s=Ve(wm(o,10n)*o),a=Ve(wm(s,20n)*s),c=Ve(wm(a,40n)*a),u=Ve(wm(c,80n)*c),d=Ve(wm(u,80n)*c),l=Ve(wm(d,10n)*o);return{pow_p_5_8:Ve(wm(l,2n)*e),b2:r}},Zdt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,jvr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Nvr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*Zdt),u=s===e,d=s===Tn(-e),l=s===Tn(-e*Zdt);return u&&(o=a),(d||l)&&(o=c),(Tn(o)&1n)===1n&&(o=Tn(-o)),{isValid:u||d,value:o}},bwe=e=>xlt(Plt(e)),Twe=(...e)=>Promise.resolve(Alt("sha512Async")(sA(...e))).then(Slt),qvr=(...e)=>Slt(Alt("sha512")(sA(...e))),Ilt=e=>{let t=Ewe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=bwe(r),o=Rv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Uvr=e=>Twe(W1(e,FJ)).then(Ilt),Mvr=e=>Ilt(qvr(W1(e,FJ))),Dvr=e=>Mvr(e).pointBytes,zvr=e=>Twe(e.hashable).then(e.finish),Lvr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=bwe(t),s=Rv.multiply(o).toBytes();return{hashable:sA(s,n,r),finish:u=>{let d=xlt(o+bwe(u)*i);return W1(sA(s,Tlt(d)),64)}}},Hvr=async(e,t)=>{let r=W1(e),n=await Uvr(t),i=await Twe(n.prefix,r);return zvr(Lvr(n,i,r))},Pwe=Object.freeze({bytesToHex:Awe,hexToBytes:Swe,concatBytes:sA,mod:Tn,invert:Elt,randomBytes:Bvr}),Olt={sha512Async:async e=>{let t=kvr(),r=sA(e);return $J(await t.digest("SHA-512",r.buffer))},sha512:void 0},DJ=8,Fvr=256,Clt=Math.ceil(Fvr/DJ)+1,_we=2**(DJ-1),$vr=()=>{let e=[],t=Rv,r=t;for(let n=0;n<Clt;n++){r=t,e.push(r);for(let i=1;i<_we;i++)r=r.add(t),e.push(r);t=r.double()}return e},Xdt=void 0,Qdt=(e,t)=>{let r=t.negate();return e?r:t},Vvr=e=>{let t=Xdt||(Xdt=$vr()),r=Ov,n=Rv,i=2**DJ,o=i,s=MJ(i-1),a=MJ(DJ);for(let c=0;c<Clt;c++){let u=Number(e&s);e>>=a,u>_we&&(u-=o,e+=1n);let d=c*_we,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(Qdt(f,t[l])):r=r.add(Qdt(m,t[p]))}return e!==0n&&bs("invalid wnaf"),{p:r,f:n}};Blt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Nlt=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=pwe(this.buffer)}update(e){elt(this),Rlt(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=pwe(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){elt(this),Wvr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,uk(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=pwe(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()}},Wb=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ra=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),OJ=BigInt(2**32-1),tlt=BigInt(32);rlt=(e,t,r)=>e>>>r,nlt=(e,t,r)=>e<<32-r|t>>>r,rA=(e,t,r)=>e>>>r|t<<32-r,nA=(e,t,r)=>e<<32-r|t>>>r,CJ=(e,t,r)=>e<<64-r|t>>>r-32,RJ=(e,t,r)=>e>>>r-32|t<<64-r;Xvr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Qvr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,e4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),t4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,r4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),n4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,i4r=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]),Gb=new Uint32Array(64),o4r=class extends Nlt{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)Gb[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Gb[d-15],p=Gb[d-2],f=xm(l,7)^xm(l,18)^l>>>3,m=xm(p,17)^xm(p,19)^p>>>10;Gb[d]=m+Gb[d-7]+f+Gb[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=xm(s,6)^xm(s,11)^xm(s,25),p=u+l+Gvr(s,a,c)+i4r[d]+Gb[d]|0,m=(xm(r,2)^xm(r,13)^xm(r,22))+Jvr(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(){uk(Gb)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),uk(this.buffer)}},s4r=class extends o4r{A=Wb[0]|0;B=Wb[1]|0;C=Wb[2]|0;D=Wb[3]|0;E=Wb[4]|0;F=Wb[5]|0;G=Wb[6]|0;H=Wb[7]|0;constructor(){super(32)}},jlt=Zvr(["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))),a4r=jlt[0],c4r=jlt[1],Jb=new Uint32Array(80),Yb=new Uint32Array(80),u4r=class extends Nlt{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 x=0;x<16;x++,t+=4)Jb[x]=e.getUint32(t),Yb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Jb[x-15]|0,v=Yb[x-15]|0,E=rA(_,v,1)^rA(_,v,8)^rlt(_,v,7),A=nA(_,v,1)^nA(_,v,8)^nlt(_,v,7),S=Jb[x-2]|0,C=Yb[x-2]|0,I=rA(S,C,19)^CJ(S,C,61)^rlt(S,C,6),R=nA(S,C,19)^RJ(S,C,61)^nlt(S,C,6),U=e4r(A,R,Yb[x-7],Yb[x-16]),j=t4r(U,E,I,Jb[x-7],Jb[x-16]);Jb[x]=j|0,Yb[x]=U|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 x=0;x<80;x++){let _=rA(d,l,14)^rA(d,l,18)^CJ(d,l,41),v=nA(d,l,14)^nA(d,l,18)^RJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=r4r(w,v,A,c4r[x],Yb[x]),C=n4r(S,y,_,E,a4r[x],Jb[x]),I=S|0,R=rA(r,n,28)^CJ(r,n,34)^CJ(r,n,39),U=nA(r,n,28)^RJ(r,n,34)^RJ(r,n,39),j=r&i^r&s^i&s,q=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}=$1(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=Xvr(I,U,q);r=Qvr(B,C,R,j),n=B|0}({h:r,l:n}=$1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=$1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=$1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=$1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=$1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=$1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=$1(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(){uk(Jb,Yb)}destroy(){this.destroyed=!0,uk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},d4r=class extends u4r{Ah=ra[0]|0;Al=ra[1]|0;Bh=ra[2]|0;Bl=ra[3]|0;Ch=ra[4]|0;Cl=ra[5]|0;Dh=ra[6]|0;Dl=ra[7]|0;Eh=ra[8]|0;El=ra[9]|0;Fh=ra[10]|0;Fl=ra[11]|0;Gh=ra[12]|0;Gl=ra[13]|0;Hh=ra[14]|0;Hl=ra[15]|0;constructor(){super(64)}},l4r=klt(()=>new s4r,Blt(1)),p4r=klt(()=>new d4r,Blt(3)),ilt=Olt;ilt.sha512||(ilt.sha512=e=>p4r(e));h4r=Pwe.bytesToHex,qlt=Pwe.hexToBytes;Pwe.concatBytes;g4r=new TextEncoder,b4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};qlt("302e020100300506032b657004220420");qlt("302a300506032b6570032100");Ult="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",x4r=Ult.length-1;if((Ult.length&x4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");Mlt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:zJ,n:qJ,Gx:olt,Gy:slt,a:fwe,d:mwe,h:E4r}=Mlt,aA=32,A4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw A4r(t,_s),t},S4r=e=>typeof e=="bigint",T4r=e=>typeof e=="string",P4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,e2=(e,t,r="")=>{let n=P4r(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},VJ=e=>new Uint8Array(e),Iwe=e=>Uint8Array.from(e),Dlt=(e,t)=>e.toString(16).padStart(t,"0"),zlt=e=>Array.from(e2(e)).map(t=>Dlt(t,2)).join(""),V1={_0:48,_9:57,A:65,F:70,a:97,f:102},alt=e=>{if(e>=V1._0&&e<=V1._9)return e-V1._0;if(e>=V1.A&&e<=V1.F)return e-(V1.A-10);if(e>=V1.a&&e<=V1.f)return e-(V1.a-10)},Llt=e=>{let t="hex invalid";if(!T4r(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=VJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=alt(e.charCodeAt(s)),c=alt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},Hlt=()=>globalThis?.crypto,I4r=()=>Hlt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),Owe=(...e)=>{let t=0;for(let i of e)t+=e2(i).length;let r=VJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},O4r=(e=aA)=>Hlt().getRandomValues(VJ(e)),LJ=BigInt,Pv=(e,t,r,n="bad number: out of range")=>{if(!S4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Fn=(e,t=zJ)=>{let r=e%t;return r>=0n?r:t+r},clt=(1n<<255n)-1n,Ke=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&clt);return t=(t>>255n)*19n+(t&clt),t%zJ},C4r=e=>Fn(e,qJ),R4r=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Fn(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?Fn(i,t):_s("no inverse")},Flt=e=>{let t=Glt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},$lt=e=>e2(e,64,"digest"),hwe=e=>e instanceof lk?e:_s("Point expected"),vwe=2n**256n,lk=class Iv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=vwe;this.X=Pv(t,0n,o),this.Y=Pv(r,0n,o),this.Z=Pv(n,1n,o),this.T=Pv(i,0n,o),Object.freeze(this)}static CURVE(){return Mlt}static fromAffine(t){return new Iv(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=mwe,i=Iwe(e2(t,aA)),o=t[31];i[31]=o&-129;let s=Vlt(i);Pv(s,0n,r?vwe:zJ);let c=Ke(s*s),u=Fn(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=N4r(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=Fn(-p)),new Iv(p,s,1n,Ke(p*s))}static fromHex(t,r){return Iv.fromBytes(Llt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=fwe,r=mwe,n=this;if(n.is0())return _s("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=Fn(l+Ke(r*Ke(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(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}=hwe(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(Cv)}negate(){return new Iv(Fn(-this.X),this.Y,this.Z,Fn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=fwe,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=Fn(t+r),d=Fn(Ke(u*u)-o-s),l=Fn(c+s),p=Fn(l-a),f=Fn(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Iv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=hwe(t),d=fwe,l=mwe,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=Fn(Ke(Fn(r+n)*Fn(s+a))-p-f),w=Fn(h-m),x=Fn(h+m),_=Fn(f-Ke(d*p)),v=Ke(y*w),E=Ke(x*_),A=Ke(y*_),S=Ke(w*x);return new Iv(v,E,S,A)}subtract(t){return this.add(hwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Pv(t,1n,qJ),!r&&this.is0()))return Cv;if(t===1n)return this;if(this.equals(cA))return $4r(t).p;let n=Cv,i=cA;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(Cv))return{x:0n,y:1n};let i=R4r(n,zJ);Ke(n*i)!==1n&&_s("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=k4r(r);return n[31]|=t&1n?128:0,n}toHex(){return zlt(this.toBytes())}clearCofactor(){return this.multiply(LJ(E4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(qJ/2n,!1).double();return qJ%2n&&(t=t.add(this)),t.is0()}},cA=new lk(olt,slt,1n,Fn(olt*slt)),Cv=new lk(0n,1n,1n,0n);lk.BASE=cA;lk.ZERO=Cv;k4r=e=>Llt(Dlt(Pv(e,0n,vwe),64)).reverse(),Vlt=e=>LJ("0x"+zlt(Iwe(e2(e)).reverse())),Em=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},B4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Em(r,2n)*r),i=Ke(Em(n,1n)*e),o=Ke(Em(i,5n)*i),s=Ke(Em(o,10n)*o),a=Ke(Em(s,20n)*s),c=Ke(Em(a,40n)*a),u=Ke(Em(c,80n)*c),d=Ke(Em(u,80n)*c),l=Ke(Em(d,10n)*o);return{pow_p_5_8:Ke(Em(l,2n)*e),b2:r}},ult=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,N4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=B4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*ult),u=s===e,d=s===Fn(-e),l=s===Fn(-e*ult);return u&&(o=a),(d||l)&&(o=c),(Fn(o)&1n)===1n&&(o=Fn(-o)),{isValid:u||d,value:o}},j4r=e=>C4r(Vlt(e)),q4r=(...e)=>Promise.resolve(Flt("sha512Async")(Owe(...e))).then($lt),U4r=(...e)=>$lt(Flt("sha512")(Owe(...e))),Klt=e=>{let t=Iwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=j4r(r),o=cA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},M4r=e=>q4r(e2(e,aA)).then(Klt),Wlt=e=>Klt(U4r(e2(e,aA))),D4r=e=>Wlt(e).pointBytes,Glt={sha512Async:async e=>{let t=I4r(),r=Owe(e);return VJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},z4r=e=>(e=e===void 0?O4r(aA):e,e2(e,aA)),L4r=Object.freeze({getExtendedPublicKeyAsync:M4r,getExtendedPublicKey:Wlt,randomSecretKey:z4r}),HJ=8,H4r=256,Jlt=Math.ceil(H4r/HJ)+1,wwe=2**(HJ-1),F4r=()=>{let e=[],t=cA,r=t;for(let n=0;n<Jlt;n++){r=t,e.push(r);for(let i=1;i<wwe;i++)r=r.add(t),e.push(r);t=r.double()}return e},dlt=void 0,llt=(e,t)=>{let r=t.negate();return e?r:t},$4r=e=>{let t=dlt||(dlt=F4r()),r=Cv,n=cA,i=2**HJ,o=i,s=LJ(i-1),a=LJ(HJ);for(let c=0;c<Jlt;c++){let u=Number(e&s);e>>=a,u>wwe&&(u-=o,e+=1n);let d=c*wwe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(llt(f,t[l])):r=r.add(llt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};G4r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),J4r=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=ywe(this.buffer)}update(e){plt(this),Ylt(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=ywe(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){plt(this),K4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,xwe(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=ywe(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()}},na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),kJ=BigInt(2**32-1),flt=BigInt(32);mlt=(e,t,r)=>e>>>r,hlt=(e,t,r)=>e<<32-r|t>>>r,iA=(e,t,r)=>e>>>r|t<<32-r,oA=(e,t,r)=>e<<32-r|t>>>r,BJ=(e,t,r)=>e<<64-r|t>>>r-32,NJ=(e,t,r)=>e>>>r-32|t<<64-r;X4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Q4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,ewr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),twr=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,rwr=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),nwr=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Zlt=Z4r(["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))),iwr=Zlt[0],owr=Zlt[1],Zb=new Uint32Array(80),Xb=new Uint32Array(80),swr=class extends J4r{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 x=0;x<16;x++,t+=4)Zb[x]=e.getUint32(t),Xb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Zb[x-15]|0,v=Xb[x-15]|0,E=iA(_,v,1)^iA(_,v,8)^mlt(_,v,7),A=oA(_,v,1)^oA(_,v,8)^hlt(_,v,7),S=Zb[x-2]|0,C=Xb[x-2]|0,I=iA(S,C,19)^BJ(S,C,61)^mlt(S,C,6),R=oA(S,C,19)^NJ(S,C,61)^hlt(S,C,6),U=ewr(A,R,Xb[x-7],Xb[x-16]),j=twr(U,E,I,Zb[x-7],Zb[x-16]);Zb[x]=j|0,Xb[x]=U|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 x=0;x<80;x++){let _=iA(d,l,14)^iA(d,l,18)^BJ(d,l,41),v=oA(d,l,14)^oA(d,l,18)^NJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=rwr(w,v,A,owr[x],Xb[x]),C=nwr(S,y,_,E,iwr[x],Zb[x]),I=S|0,R=iA(r,n,28)^BJ(r,n,34)^BJ(r,n,39),U=oA(r,n,28)^NJ(r,n,34)^NJ(r,n,39),j=r&i^r&s^i&s,q=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}=K1(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=X4r(I,U,q);r=Q4r(B,C,R,j),n=B|0}({h:r,l:n}=K1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=K1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=K1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=K1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=K1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=K1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=K1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=K1(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(){xwe(Zb,Xb)}destroy(){this.destroyed=!0,xwe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},awr=class extends swr{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)}},cwr=W4r(()=>new awr,G4r(3)),ylt=Glt;ylt.sha512||(ylt.sha512=e=>cwr(e));mwr="ws://localhost:9001/ws",hwr=3e4,Qlt=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=ck(e.name),e.keyPath)try{this._keypair=pwr(e.keyPath)}catch{}this.options={name:this._name,url:e.url??mwr,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??hwr,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new Tvr({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=w4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:f4r(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=glt(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 ta(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ta("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ta("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ta("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ta("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=ck(e),o=cwe();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 ta(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=ck(e),o=cwe(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await fwr(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 ta(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=ck(e),o=n?.correlationId??cwe(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new ak(`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 ta(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=ck(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 ta(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new ak(`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=owe(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new IJ(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=glt(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 qwe={};Gi(qwe,{SUBWAY_PROTOCOL:()=>lpt,registerDirect:()=>Iwr,resolveDirect:()=>Owr});function kwe(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 Wd(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 Bwe(e,t){return e<<3|t}function pk(e,t,r){e.push(Bwe(t,2)),kwe(e,r.length);for(let n of r)e.push(n)}function ywr(e,t){let r=[];return pk(r,1,Rwe.encode(e)),t&&t.length>0&&pk(r,2,Rwe.encode(t)),Uint8Array.from(r)}function gwr(e,t,r){let n=[];return r!==0n&&(n.push(Bwe(1,0)),kwe(n,r)),pk(n,2,ywr(e,t)),Uint8Array.from(n)}function bwr(e){let t=[];return pk(t,1,Rwe.encode(e)),Uint8Array.from(t)}function _wr(e,t){let r=[];return t!==0n&&(r.push(Bwe(1,0)),kwe(r,t)),pk(r,3,bwr(e)),Uint8Array.from(r)}function vwr(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.error=upt.decode(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function wwr(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Wd(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]=Wd(e,t),u=c,d=u+Number(a);r.error=upt.decode(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function Nwe(e,t,r){if(r===0)return Wd(e,t)[1];if(r===2){let[n,i]=Wd(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 dpt(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.registerNameResponse=vwr(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=wwr(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function xwr(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function jwe(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function Ewr(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=jwe(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:dpt(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function Awr(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=jwe(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:dpt(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Cwe(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 Pwr(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>tpt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+jwe(Cwe(t).subarray(0,4)),n>tpt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Cwe(t).subarray(0,n)}return Cwe(t)}async function ppt(e){return(0,rpt.createLibp2p)({...e?{privateKey:await(0,spt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,npt.tcp)()],connectionEncrypters:[(0,ipt.noise)()],streamMuxers:[(0,opt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function fpt(e,t,r){let n=await e.dialProtocol((0,apt.multiaddr)(t),lpt,{signal:AbortSignal.timeout(Swr)});n.send(xwr(r));let i;return Promise.race([Pwr(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),Twr)})]).finally(()=>clearTimeout(i))}async function Iwr(e){let t=await ppt(e.seed);try{let r=await fpt(t,e.relayMultiaddr,gwr(e.name,e.binding,e.requestId??1n)),n=Ewr(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function Owr(e){let t=await ppt(e.seed);try{let r=await fpt(t,e.relayMultiaddr,_wr(e.name,e.requestId??1n)),n=Awr(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,cpt.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var rpt,npt,ipt,opt,spt,apt,cpt,Rwe,upt,lpt,Swr,Twr,tpt,Uwe=P(()=>{"use strict";awe();rpt=require("libp2p"),npt=require("@libp2p/tcp"),ipt=require("@chainsafe/libp2p-noise"),opt=require("@chainsafe/libp2p-yamux"),spt=require("@libp2p/crypto/keys"),apt=require("@multiformats/multiaddr"),cpt=require("uint8arrays/to-string"),Rwe=new TextEncoder,upt=new TextDecoder;lpt="/subway/p2p/1.0.0",Swr=15e3,Twr=15e3,tpt=1<<20});var mk={};Gi(mk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>hpt,MESH:()=>vs,RELAY_URL:()=>Fwe,connectOrThrow:()=>JJ,ensureMailbox:()=>Jwe,isSubwayEnabled:()=>$we,listRegistered:()=>Nwr,loadBindingFor:()=>Wwe,loadRegistry:()=>kv,makeClient:()=>GJ,maybeMintVisaBinding:()=>gpt,meshName:()=>gp,pairedVisaBinding:()=>bpt,readInbox:()=>qwr,registerName:()=>Gwe,resolveActingName:()=>Rwr,resolveMeshName:()=>kwr,seedSubwayKeyFromTapAgent:()=>ypt,sendMessage:()=>Bwr,sendVia:()=>Uwr,subwayKeyPath:()=>WJ,visaRelayMultiaddr:()=>Hwe});function Hwe(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??hpt}function gp(e){return e.includes(".")?e:`${e}.${vs}`}function $we(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 Kwe(){co.mkdirSync(Vwe,{recursive:!0,mode:448})}function Cwr(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function WJ(e){return uA.join(Vwe,`${Cwr(e)}.key`)}function kv(){if(!co.existsSync(Lwe))return{};try{return JSON.parse(co.readFileSync(Lwe,"utf8"))}catch{return{}}}function Dwe(e){Kwe(),co.writeFileSync(Lwe,JSON.stringify(e,null,2),{mode:384})}function zwe(){try{return fk.userInfo().username}catch{return"local"}}function ypt(e){if(co.existsSync(e)||!co.existsSync(Mwe))return null;let t=co.readdirSync(Mwe).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>uA.join(Mwe,n)).sort((n,i)=>co.statSync(i).mtimeMs-co.statSync(n).mtimeMs)[0];try{let n=JSON.parse(co.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=qA(n.private_key_jwk);return Kwe(),co.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function GJ(e,t={}){return new Qlt({name:gp(e),url:Fwe,keyPath:WJ(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Wwe(e){if(vs!=="visa")return;let t=kv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function JJ(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Fwe})`)),t))])}function Rwr(e){if(e)return e;let t=Object.keys(kv());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 gpt(e){if(vs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new f2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await fZ({authUrl:ju(),apiKey:t,seed:hB(WJ(e)),name:gp(e)})}catch(r){if(r instanceof f2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function bpt(e=Date.now()){let t=Ywe();if(!t?.binding_jwt)return null;let r=hk(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 Gwe(e){let t=WJ(e),r=ypt(t),n=gp(e);vs==="visa"&&!co.existsSync(t)&&(Kwe(),co.writeFileSync(t,(0,mpt.randomBytes)(32),{mode:384}));let i=vs==="visa"?bpt():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await gpt(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=vs==="visa"?Hwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(Uwe(),qwe)),d=await u({relayMultiaddr:a,seed:hB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=kv();return l[e]={relayName:n,mesh:vs,peerId:d.peerId,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(l),{relayName:n,mesh:vs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(vs==="visa"&&!process.env.SUBWAY_RELAY){let u=kv();return u[e]={relayName:n,mesh:vs,peerId:null,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(u),{relayName:n,mesh:vs,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=GJ(e,{autoReconnect:!1,binding:o});try{await JJ(c);let u=kv();return u[e]={relayName:n,mesh:vs,peerId:c.peerId,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(u),{relayName:n,mesh:vs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function kwr(e){let t=gp(e),r=vs==="visa"?Hwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Uwe(),qwe)),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 Bwr(e,t,r){let n=GJ(e,{autoReconnect:!1,binding:Wwe(e)});try{await JJ(n);let i=gp(t);return await n.sendSigned(i,"chat",r),{to:i,as:gp(e)}}finally{n.disconnect()}}function Nwr(){let e=kv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Jwe(e){let t=KJ.get(e);if(t)return{relayName:gp(e),peerId:t.client.peerId};let r=GJ(e,{autoReconnect:!0,binding:Wwe(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>jwr&&n.shift()}),KJ.set(e,{client:r,buffer:n}),await JJ(r),{relayName:gp(e),peerId:r.peerId}}async function qwr(e,t=20,r=!1){await Jwe(e);let n=KJ.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function Uwr(e,t,r){await Jwe(e);let n=KJ.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gp(e)}}var co,fk,uA,mpt,vs,hpt,Fwe,Vwe,Lwe,Mwe,KJ,jwr,Bv=P(()=>{"use strict";ept();p2();co=Ze(require("fs")),fk=Ze(require("os")),uA=Ze(require("path")),mpt=require("crypto");s4();MA();YJ();vs=process.env.SUBWAY_MESH??"relay",hpt="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Fwe=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Vwe=uA.join(fk.homedir(),".visa-cli","subway"),Lwe=uA.join(Vwe,"registry.json"),Mwe=uA.join(fk.homedir(),".visa-cli","agents");KJ=new Map,jwr=200});async function Mwr(e){if(process.env.SUBWAY_MESH==="visa")try{await Gwe(e)}catch(t){Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)})}}function Dwr(e=process.env.VISA_V4_HOME||dA.join(Zwe.homedir(),".visa-v4")){try{let t=qc.readFileSync(dA.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 Xwe(e,t,r=yk){return dA.join(r,`${e}.${t}.json`)}function vpt(e,t=yk){qc.mkdirSync(t,{recursive:!0,mode:448}),qc.writeFileSync(Xwe(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function gk(e,t,r=yk){qc.rmSync(Xwe(e,t,r),{force:!0})}function ZJ(e,t,r=yk){try{let n=JSON.parse(qc.readFileSync(Xwe(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function Qwe(e=yk){return qc.existsSync(e)?qc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(qc.readFileSync(dA.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 Nv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":_pt,...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 e8e(e={}){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=c9e(),n=Dwr(),{body:i}=await Nv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:u9e(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 vpt(o,e.pairingDir),o}async function XJ(e){let{pairing:t}=e,{body:r}=await Nv(`${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 t8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),{body:r}=await Nv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function wpt(e,t){return Buffer.from(p4(e,Buffer.from(t,"utf8"))).toString("base64url")}async function r8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await t8e({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=pB();i=m.secretKey,s=f4(i),o=ch(m.publicKey)}let a=m4(o),c=xJ(),u=d9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:_pt},l=wpt(i,l9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:lZ(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()};vpt(p,e.pairingDir);let{body:f}=await Nv(`${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!==fB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function QJ(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 Nv(`${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=wJ(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))||f9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=wpt(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),p9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await Nv(`${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}:{}}),n8e(h,e.agentDir),await Mwr(u),gk(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 xpt(e){let{pairing:t}=e,{body:r}=await Nv(`${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"&&gk(t.pairingId,"human",e.pairingDir),r}var qc,Zwe,dA,_pt,yk,Ept=P(()=>{"use strict";qc=Ze(require("node:fs")),Zwe=Ze(require("node:os")),dA=Ze(require("node:path"));p2();MA();Bv();s4();Dc();K4e();YJ();_pt="4.1.0-rc.28",yk=dA.join(Zwe.homedir(),".visa-cli","pairings")});var Cpt={};Gi(Cpt,{agentFilePath:()=>_k,agentFormatIsJson:()=>bk,attachAgentCommand:()=>Fwr,claimOptsFromFlags:()=>s8e,decodeBindingClaims:()=>hk,enrollClaimEnvelope:()=>Ipt,isAgentCommandEnabled:()=>Ppt,isAgentRecord:()=>vk,listAgentFiles:()=>eY,newestAgentRecord:()=>Ywe,readAgent:()=>a8e,resolveAgentByRef:()=>Opt,writeAgent:()=>n8e});function vk(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 Ppt(){return!0}function bk(e){return e==="json"}function Ipt(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 s8e(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 i8e(e){return`${e.opened?`\u2713 Enrollment link opened in your browser.
20678
+ ${e.nonce}`;return g4r.encode(r)}function v4r(e,t,r,n,i,o,s){return _4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function w4r(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 V4r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Ylt(e,t,r=""){let n=V4r(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 plt(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 K4r(e,t){Ylt(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 xwe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ywe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function W4r(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 Y4r(e,t=!1){return t?{h:Number(e&kJ),l:Number(e>>flt&kJ)}:{h:Number(e>>flt&kJ)|0,l:Number(e&kJ)|0}}function Z4r(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}=Y4r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function K1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function uwr(){return L4r.randomSecretKey()}function Xlt(e){return D4r(e)}function dwr(){let e=uwr();return{secretKey:e,publicKey:Xlt(e)}}function lwr(e){if((0,Qb.existsSync)(e)){let r=(0,Qb.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:Xlt(n)}}let t=dwr();return(0,Qb.mkdirSync)((0,blt.dirname)(e),{recursive:!0}),(0,Qb.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function pwr(e){let{secretKey:t,publicKey:r}=lwr(e);return{privateKey:t,publicKey:r}}async function fwr(e,t,r,n,i,o,s,a){let c=v4r(t,r,n,i,o,s,a);return{signature:await m4r(e,c),signatureInput:b4r.subwayAgentMsgV1}}function glt(e){return y4r(e)}var Qb,blt,xvr,Evr,Avr,Svr,Tvr,_lt,UJ,jJ,Wdt,Gdt,uwe,dwe,Pvr,FJ,Ivr,bs,Ovr,Cvr,Rvr,W1,$J,Ewe,vlt,Awe,F1,Jdt,Swe,wlt,kvr,sA,Bvr,MJ,Sv,Tn,Ydt,Ve,xlt,Elt,Alt,Slt,lwe,gwe,dk,Rv,Ov,Tlt,Plt,wm,Nvr,Zdt,jvr,bwe,Twe,qvr,Ilt,Uvr,Mvr,Dvr,zvr,Lvr,Hvr,Pwe,Olt,DJ,Fvr,Clt,_we,$vr,Xdt,Qdt,Vvr,Blt,Nlt,Wb,ra,OJ,tlt,rlt,nlt,rA,nA,CJ,RJ,Xvr,Qvr,e4r,t4r,r4r,n4r,i4r,Gb,o4r,s4r,jlt,a4r,c4r,Jb,Yb,u4r,d4r,l4r,p4r,ilt,h4r,qlt,g4r,b4r,Ult,x4r,Mlt,zJ,qJ,olt,slt,fwe,mwe,E4r,aA,A4r,_s,S4r,T4r,P4r,e2,VJ,Iwe,Dlt,zlt,V1,alt,Llt,Hlt,I4r,Owe,O4r,LJ,Pv,Fn,clt,Ke,C4r,R4r,Flt,$lt,hwe,vwe,lk,cA,Cv,k4r,Vlt,Em,B4r,ult,N4r,j4r,q4r,U4r,Klt,M4r,Wlt,D4r,Glt,z4r,L4r,HJ,H4r,Jlt,wwe,F4r,dlt,llt,$4r,G4r,J4r,na,kJ,flt,mlt,hlt,iA,oA,BJ,NJ,X4r,Q4r,ewr,twr,rwr,nwr,Zlt,iwr,owr,Zb,Xb,swr,awr,cwr,ylt,mwr,hwr,Qlt,ept=P(()=>{"use strict";swe();swe();awe();Qb=require("fs"),blt=require("path");xvr=1e3,Evr=10,Avr=3e4,Svr=3e4,Tvr=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??xvr,this.maxReconnectAttempts=e.maxReconnectAttempts??Evr,this.pingInterval=e.pingInterval??Avr}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=vvr();if(!r){t(new ta('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 ta(`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 ta("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ta(`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 ta("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=wvr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Svr);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)}}},_lt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:UJ,n:jJ,Gx:Wdt,Gy:Gdt,a:uwe,d:dwe,h:Pvr}=_lt,FJ=32,Ivr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},bs=(e="")=>{let t=new Error(e);throw Ivr(t,bs),t},Ovr=e=>typeof e=="bigint",Cvr=e=>typeof e=="string",Rvr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,W1=(e,t,r="")=>{let n=Rvr(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e},$J=e=>new Uint8Array(e),Ewe=e=>Uint8Array.from(e),vlt=(e,t)=>e.toString(16).padStart(t,"0"),Awe=e=>Array.from(W1(e)).map(t=>vlt(t,2)).join(""),F1={_0:48,_9:57,A:65,F:70,a:97,f:102},Jdt=e=>{if(e>=F1._0&&e<=F1._9)return e-F1._0;if(e>=F1.A&&e<=F1.F)return e-(F1.A-10);if(e>=F1.a&&e<=F1.f)return e-(F1.a-10)},Swe=e=>{let t="hex invalid";if(!Cvr(e))return bs(t);let r=e.length,n=r/2;if(r%2)return bs(t);let i=$J(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Jdt(e.charCodeAt(s)),c=Jdt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return bs(t);i[o]=a*16+c}return i},wlt=()=>globalThis?.crypto,kvr=()=>wlt()?.subtle??bs("crypto.subtle must be defined, consider polyfill"),sA=(...e)=>{let t=0;for(let i of e)t+=W1(i).length;let r=$J(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Bvr=(e=FJ)=>wlt().getRandomValues($J(e)),MJ=BigInt,Sv=(e,t,r,n="bad number: out of range")=>{if(!Ovr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Tn=(e,t=UJ)=>{let r=e%t;return r>=0n?r:t+r},Ydt=(1n<<255n)-1n,Ve=e=>{e<0n&&bs("negative coordinate");let t=(e>>255n)*19n+(e&Ydt);return t=(t>>255n)*19n+(t&Ydt),t%UJ},xlt=e=>Tn(e,jJ),Elt=(e,t)=>{(e===0n||t<=0n)&&bs("no inverse n="+e+" mod="+t);let r=Tn(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?Tn(i,t):bs("no inverse")},Alt=e=>{let t=Olt[e];return typeof t!="function"&&bs("hashes."+e+" not set"),t},Slt=e=>W1(e,64,"digest"),lwe=e=>e instanceof dk?e:bs("Point expected"),gwe=2n**256n,dk=class Tv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=gwe;this.X=Sv(t,0n,o),this.Y=Sv(r,0n,o),this.Z=Sv(n,1n,o),this.T=Sv(i,0n,o),Object.freeze(this)}static CURVE(){return _lt}static fromAffine(t){return new Tv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=dwe,i=Ewe(W1(t,FJ)),o=t[31];i[31]=o&-129;let s=Plt(i);Sv(s,0n,r?gwe:UJ);let c=Ve(s*s),u=Tn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=jvr(u,d);l||bs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&bs("bad point: x==0, isLastByteOdd"),m!==f&&(p=Tn(-p)),new Tv(p,s,1n,Ve(p*s))}static fromHex(t,r){return Tv.fromBytes(Swe(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=uwe,r=dwe,n=this;if(n.is0())return bs("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=Tn(l+Ve(r*Ve(c*u)));if(f!==m)return bs("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?bs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=lwe(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(Ov)}negate(){return new Tv(Tn(-this.X),this.Y,this.Z,Tn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=uwe,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Tn(t+r),d=Tn(Ve(u*u)-o-s),l=Tn(c+s),p=Tn(l-a),f=Tn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new Tv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=lwe(t),d=uwe,l=dwe,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Tn(Ve(Tn(r+n)*Tn(s+a))-p-f),w=Tn(h-m),x=Tn(h+m),_=Tn(f-Ve(d*p)),v=Ve(y*w),E=Ve(x*_),A=Ve(y*_),S=Ve(w*x);return new Tv(v,E,S,A)}subtract(t){return this.add(lwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Sv(t,1n,jJ),!r&&this.is0()))return Ov;if(t===1n)return this;if(this.equals(Rv))return Vvr(t).p;let n=Ov,i=Rv;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(Ov))return{x:0n,y:1n};let i=Elt(n,UJ);Ve(n*i)!==1n&&bs("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=Tlt(r);return n[31]|=t&1n?128:0,n}toHex(){return Awe(this.toBytes())}clearCofactor(){return this.multiply(MJ(Pvr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(jJ/2n,!1).double();return jJ%2n&&(t=t.add(this)),t.is0()}},Rv=new dk(Wdt,Gdt,1n,Tn(Wdt*Gdt)),Ov=new dk(0n,1n,1n,0n);dk.BASE=Rv;dk.ZERO=Ov;Tlt=e=>Swe(vlt(Sv(e,0n,gwe),64)).reverse(),Plt=e=>MJ("0x"+Awe(Ewe(W1(e)).reverse())),wm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Nvr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(wm(r,2n)*r),i=Ve(wm(n,1n)*e),o=Ve(wm(i,5n)*i),s=Ve(wm(o,10n)*o),a=Ve(wm(s,20n)*s),c=Ve(wm(a,40n)*a),u=Ve(wm(c,80n)*c),d=Ve(wm(u,80n)*c),l=Ve(wm(d,10n)*o);return{pow_p_5_8:Ve(wm(l,2n)*e),b2:r}},Zdt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,jvr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Nvr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*Zdt),u=s===e,d=s===Tn(-e),l=s===Tn(-e*Zdt);return u&&(o=a),(d||l)&&(o=c),(Tn(o)&1n)===1n&&(o=Tn(-o)),{isValid:u||d,value:o}},bwe=e=>xlt(Plt(e)),Twe=(...e)=>Promise.resolve(Alt("sha512Async")(sA(...e))).then(Slt),qvr=(...e)=>Slt(Alt("sha512")(sA(...e))),Ilt=e=>{let t=Ewe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=bwe(r),o=Rv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Uvr=e=>Twe(W1(e,FJ)).then(Ilt),Mvr=e=>Ilt(qvr(W1(e,FJ))),Dvr=e=>Mvr(e).pointBytes,zvr=e=>Twe(e.hashable).then(e.finish),Lvr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=bwe(t),s=Rv.multiply(o).toBytes();return{hashable:sA(s,n,r),finish:u=>{let d=xlt(o+bwe(u)*i);return W1(sA(s,Tlt(d)),64)}}},Hvr=async(e,t)=>{let r=W1(e),n=await Uvr(t),i=await Twe(n.prefix,r);return zvr(Lvr(n,i,r))},Pwe=Object.freeze({bytesToHex:Awe,hexToBytes:Swe,concatBytes:sA,mod:Tn,invert:Elt,randomBytes:Bvr}),Olt={sha512Async:async e=>{let t=kvr(),r=sA(e);return $J(await t.digest("SHA-512",r.buffer))},sha512:void 0},DJ=8,Fvr=256,Clt=Math.ceil(Fvr/DJ)+1,_we=2**(DJ-1),$vr=()=>{let e=[],t=Rv,r=t;for(let n=0;n<Clt;n++){r=t,e.push(r);for(let i=1;i<_we;i++)r=r.add(t),e.push(r);t=r.double()}return e},Xdt=void 0,Qdt=(e,t)=>{let r=t.negate();return e?r:t},Vvr=e=>{let t=Xdt||(Xdt=$vr()),r=Ov,n=Rv,i=2**DJ,o=i,s=MJ(i-1),a=MJ(DJ);for(let c=0;c<Clt;c++){let u=Number(e&s);e>>=a,u>_we&&(u-=o,e+=1n);let d=c*_we,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(Qdt(f,t[l])):r=r.add(Qdt(m,t[p]))}return e!==0n&&bs("invalid wnaf"),{p:r,f:n}};Blt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Nlt=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=pwe(this.buffer)}update(e){elt(this),Rlt(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=pwe(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){elt(this),Wvr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,uk(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=pwe(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()}},Wb=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ra=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),OJ=BigInt(2**32-1),tlt=BigInt(32);rlt=(e,t,r)=>e>>>r,nlt=(e,t,r)=>e<<32-r|t>>>r,rA=(e,t,r)=>e>>>r|t<<32-r,nA=(e,t,r)=>e<<32-r|t>>>r,CJ=(e,t,r)=>e<<64-r|t>>>r-32,RJ=(e,t,r)=>e>>>r-32|t<<64-r;Xvr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Qvr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,e4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),t4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,r4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),n4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,i4r=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]),Gb=new Uint32Array(64),o4r=class extends Nlt{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)Gb[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Gb[d-15],p=Gb[d-2],f=xm(l,7)^xm(l,18)^l>>>3,m=xm(p,17)^xm(p,19)^p>>>10;Gb[d]=m+Gb[d-7]+f+Gb[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=xm(s,6)^xm(s,11)^xm(s,25),p=u+l+Gvr(s,a,c)+i4r[d]+Gb[d]|0,m=(xm(r,2)^xm(r,13)^xm(r,22))+Jvr(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(){uk(Gb)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),uk(this.buffer)}},s4r=class extends o4r{A=Wb[0]|0;B=Wb[1]|0;C=Wb[2]|0;D=Wb[3]|0;E=Wb[4]|0;F=Wb[5]|0;G=Wb[6]|0;H=Wb[7]|0;constructor(){super(32)}},jlt=Zvr(["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))),a4r=jlt[0],c4r=jlt[1],Jb=new Uint32Array(80),Yb=new Uint32Array(80),u4r=class extends Nlt{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 x=0;x<16;x++,t+=4)Jb[x]=e.getUint32(t),Yb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Jb[x-15]|0,v=Yb[x-15]|0,E=rA(_,v,1)^rA(_,v,8)^rlt(_,v,7),A=nA(_,v,1)^nA(_,v,8)^nlt(_,v,7),S=Jb[x-2]|0,C=Yb[x-2]|0,I=rA(S,C,19)^CJ(S,C,61)^rlt(S,C,6),R=nA(S,C,19)^RJ(S,C,61)^nlt(S,C,6),U=e4r(A,R,Yb[x-7],Yb[x-16]),j=t4r(U,E,I,Jb[x-7],Jb[x-16]);Jb[x]=j|0,Yb[x]=U|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 x=0;x<80;x++){let _=rA(d,l,14)^rA(d,l,18)^CJ(d,l,41),v=nA(d,l,14)^nA(d,l,18)^RJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=r4r(w,v,A,c4r[x],Yb[x]),C=n4r(S,y,_,E,a4r[x],Jb[x]),I=S|0,R=rA(r,n,28)^CJ(r,n,34)^CJ(r,n,39),U=nA(r,n,28)^RJ(r,n,34)^RJ(r,n,39),j=r&i^r&s^i&s,q=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}=$1(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=Xvr(I,U,q);r=Qvr(B,C,R,j),n=B|0}({h:r,l:n}=$1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=$1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=$1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=$1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=$1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=$1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=$1(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(){uk(Jb,Yb)}destroy(){this.destroyed=!0,uk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},d4r=class extends u4r{Ah=ra[0]|0;Al=ra[1]|0;Bh=ra[2]|0;Bl=ra[3]|0;Ch=ra[4]|0;Cl=ra[5]|0;Dh=ra[6]|0;Dl=ra[7]|0;Eh=ra[8]|0;El=ra[9]|0;Fh=ra[10]|0;Fl=ra[11]|0;Gh=ra[12]|0;Gl=ra[13]|0;Hh=ra[14]|0;Hl=ra[15]|0;constructor(){super(64)}},l4r=klt(()=>new s4r,Blt(1)),p4r=klt(()=>new d4r,Blt(3)),ilt=Olt;ilt.sha512||(ilt.sha512=e=>p4r(e));h4r=Pwe.bytesToHex,qlt=Pwe.hexToBytes;Pwe.concatBytes;g4r=new TextEncoder,b4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};qlt("302e020100300506032b657004220420");qlt("302a300506032b6570032100");Ult="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",x4r=Ult.length-1;if((Ult.length&x4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");Mlt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:zJ,n:qJ,Gx:olt,Gy:slt,a:fwe,d:mwe,h:E4r}=Mlt,aA=32,A4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw A4r(t,_s),t},S4r=e=>typeof e=="bigint",T4r=e=>typeof e=="string",P4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,e2=(e,t,r="")=>{let n=P4r(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},VJ=e=>new Uint8Array(e),Iwe=e=>Uint8Array.from(e),Dlt=(e,t)=>e.toString(16).padStart(t,"0"),zlt=e=>Array.from(e2(e)).map(t=>Dlt(t,2)).join(""),V1={_0:48,_9:57,A:65,F:70,a:97,f:102},alt=e=>{if(e>=V1._0&&e<=V1._9)return e-V1._0;if(e>=V1.A&&e<=V1.F)return e-(V1.A-10);if(e>=V1.a&&e<=V1.f)return e-(V1.a-10)},Llt=e=>{let t="hex invalid";if(!T4r(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=VJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=alt(e.charCodeAt(s)),c=alt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},Hlt=()=>globalThis?.crypto,I4r=()=>Hlt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),Owe=(...e)=>{let t=0;for(let i of e)t+=e2(i).length;let r=VJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},O4r=(e=aA)=>Hlt().getRandomValues(VJ(e)),LJ=BigInt,Pv=(e,t,r,n="bad number: out of range")=>{if(!S4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Fn=(e,t=zJ)=>{let r=e%t;return r>=0n?r:t+r},clt=(1n<<255n)-1n,Ke=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&clt);return t=(t>>255n)*19n+(t&clt),t%zJ},C4r=e=>Fn(e,qJ),R4r=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Fn(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?Fn(i,t):_s("no inverse")},Flt=e=>{let t=Glt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},$lt=e=>e2(e,64,"digest"),hwe=e=>e instanceof lk?e:_s("Point expected"),vwe=2n**256n,lk=class Iv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=vwe;this.X=Pv(t,0n,o),this.Y=Pv(r,0n,o),this.Z=Pv(n,1n,o),this.T=Pv(i,0n,o),Object.freeze(this)}static CURVE(){return Mlt}static fromAffine(t){return new Iv(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=mwe,i=Iwe(e2(t,aA)),o=t[31];i[31]=o&-129;let s=Vlt(i);Pv(s,0n,r?vwe:zJ);let c=Ke(s*s),u=Fn(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=N4r(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=Fn(-p)),new Iv(p,s,1n,Ke(p*s))}static fromHex(t,r){return Iv.fromBytes(Llt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=fwe,r=mwe,n=this;if(n.is0())return _s("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=Fn(l+Ke(r*Ke(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(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}=hwe(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(Cv)}negate(){return new Iv(Fn(-this.X),this.Y,this.Z,Fn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=fwe,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=Fn(t+r),d=Fn(Ke(u*u)-o-s),l=Fn(c+s),p=Fn(l-a),f=Fn(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Iv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=hwe(t),d=fwe,l=mwe,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=Fn(Ke(Fn(r+n)*Fn(s+a))-p-f),w=Fn(h-m),x=Fn(h+m),_=Fn(f-Ke(d*p)),v=Ke(y*w),E=Ke(x*_),A=Ke(y*_),S=Ke(w*x);return new Iv(v,E,S,A)}subtract(t){return this.add(hwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Pv(t,1n,qJ),!r&&this.is0()))return Cv;if(t===1n)return this;if(this.equals(cA))return $4r(t).p;let n=Cv,i=cA;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(Cv))return{x:0n,y:1n};let i=R4r(n,zJ);Ke(n*i)!==1n&&_s("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=k4r(r);return n[31]|=t&1n?128:0,n}toHex(){return zlt(this.toBytes())}clearCofactor(){return this.multiply(LJ(E4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(qJ/2n,!1).double();return qJ%2n&&(t=t.add(this)),t.is0()}},cA=new lk(olt,slt,1n,Fn(olt*slt)),Cv=new lk(0n,1n,1n,0n);lk.BASE=cA;lk.ZERO=Cv;k4r=e=>Llt(Dlt(Pv(e,0n,vwe),64)).reverse(),Vlt=e=>LJ("0x"+zlt(Iwe(e2(e)).reverse())),Em=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},B4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Em(r,2n)*r),i=Ke(Em(n,1n)*e),o=Ke(Em(i,5n)*i),s=Ke(Em(o,10n)*o),a=Ke(Em(s,20n)*s),c=Ke(Em(a,40n)*a),u=Ke(Em(c,80n)*c),d=Ke(Em(u,80n)*c),l=Ke(Em(d,10n)*o);return{pow_p_5_8:Ke(Em(l,2n)*e),b2:r}},ult=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,N4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=B4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*ult),u=s===e,d=s===Fn(-e),l=s===Fn(-e*ult);return u&&(o=a),(d||l)&&(o=c),(Fn(o)&1n)===1n&&(o=Fn(-o)),{isValid:u||d,value:o}},j4r=e=>C4r(Vlt(e)),q4r=(...e)=>Promise.resolve(Flt("sha512Async")(Owe(...e))).then($lt),U4r=(...e)=>$lt(Flt("sha512")(Owe(...e))),Klt=e=>{let t=Iwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=j4r(r),o=cA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},M4r=e=>q4r(e2(e,aA)).then(Klt),Wlt=e=>Klt(U4r(e2(e,aA))),D4r=e=>Wlt(e).pointBytes,Glt={sha512Async:async e=>{let t=I4r(),r=Owe(e);return VJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},z4r=e=>(e=e===void 0?O4r(aA):e,e2(e,aA)),L4r=Object.freeze({getExtendedPublicKeyAsync:M4r,getExtendedPublicKey:Wlt,randomSecretKey:z4r}),HJ=8,H4r=256,Jlt=Math.ceil(H4r/HJ)+1,wwe=2**(HJ-1),F4r=()=>{let e=[],t=cA,r=t;for(let n=0;n<Jlt;n++){r=t,e.push(r);for(let i=1;i<wwe;i++)r=r.add(t),e.push(r);t=r.double()}return e},dlt=void 0,llt=(e,t)=>{let r=t.negate();return e?r:t},$4r=e=>{let t=dlt||(dlt=F4r()),r=Cv,n=cA,i=2**HJ,o=i,s=LJ(i-1),a=LJ(HJ);for(let c=0;c<Jlt;c++){let u=Number(e&s);e>>=a,u>wwe&&(u-=o,e+=1n);let d=c*wwe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(llt(f,t[l])):r=r.add(llt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};G4r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),J4r=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=ywe(this.buffer)}update(e){plt(this),Ylt(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=ywe(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){plt(this),K4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,xwe(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=ywe(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()}},na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),kJ=BigInt(2**32-1),flt=BigInt(32);mlt=(e,t,r)=>e>>>r,hlt=(e,t,r)=>e<<32-r|t>>>r,iA=(e,t,r)=>e>>>r|t<<32-r,oA=(e,t,r)=>e<<32-r|t>>>r,BJ=(e,t,r)=>e<<64-r|t>>>r-32,NJ=(e,t,r)=>e>>>r-32|t<<64-r;X4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Q4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,ewr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),twr=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,rwr=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),nwr=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Zlt=Z4r(["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))),iwr=Zlt[0],owr=Zlt[1],Zb=new Uint32Array(80),Xb=new Uint32Array(80),swr=class extends J4r{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 x=0;x<16;x++,t+=4)Zb[x]=e.getUint32(t),Xb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Zb[x-15]|0,v=Xb[x-15]|0,E=iA(_,v,1)^iA(_,v,8)^mlt(_,v,7),A=oA(_,v,1)^oA(_,v,8)^hlt(_,v,7),S=Zb[x-2]|0,C=Xb[x-2]|0,I=iA(S,C,19)^BJ(S,C,61)^mlt(S,C,6),R=oA(S,C,19)^NJ(S,C,61)^hlt(S,C,6),U=ewr(A,R,Xb[x-7],Xb[x-16]),j=twr(U,E,I,Zb[x-7],Zb[x-16]);Zb[x]=j|0,Xb[x]=U|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 x=0;x<80;x++){let _=iA(d,l,14)^iA(d,l,18)^BJ(d,l,41),v=oA(d,l,14)^oA(d,l,18)^NJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=rwr(w,v,A,owr[x],Xb[x]),C=nwr(S,y,_,E,iwr[x],Zb[x]),I=S|0,R=iA(r,n,28)^BJ(r,n,34)^BJ(r,n,39),U=oA(r,n,28)^NJ(r,n,34)^NJ(r,n,39),j=r&i^r&s^i&s,q=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}=K1(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=X4r(I,U,q);r=Q4r(B,C,R,j),n=B|0}({h:r,l:n}=K1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=K1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=K1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=K1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=K1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=K1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=K1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=K1(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(){xwe(Zb,Xb)}destroy(){this.destroyed=!0,xwe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},awr=class extends swr{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)}},cwr=W4r(()=>new awr,G4r(3)),ylt=Glt;ylt.sha512||(ylt.sha512=e=>cwr(e));mwr="ws://localhost:9001/ws",hwr=3e4,Qlt=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=ck(e.name),e.keyPath)try{this._keypair=pwr(e.keyPath)}catch{}this.options={name:this._name,url:e.url??mwr,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??hwr,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new Tvr({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=w4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:f4r(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=glt(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 ta(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ta("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ta("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ta("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ta("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=ck(e),o=cwe();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 ta(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=ck(e),o=cwe(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await fwr(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 ta(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=ck(e),o=n?.correlationId??cwe(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new ak(`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 ta(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=ck(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 ta(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new ak(`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=owe(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new IJ(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=glt(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 qwe={};Gi(qwe,{SUBWAY_PROTOCOL:()=>lpt,registerDirect:()=>Iwr,resolveDirect:()=>Owr});function kwe(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 Wd(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 Bwe(e,t){return e<<3|t}function pk(e,t,r){e.push(Bwe(t,2)),kwe(e,r.length);for(let n of r)e.push(n)}function ywr(e,t){let r=[];return pk(r,1,Rwe.encode(e)),t&&t.length>0&&pk(r,2,Rwe.encode(t)),Uint8Array.from(r)}function gwr(e,t,r){let n=[];return r!==0n&&(n.push(Bwe(1,0)),kwe(n,r)),pk(n,2,ywr(e,t)),Uint8Array.from(n)}function bwr(e){let t=[];return pk(t,1,Rwe.encode(e)),Uint8Array.from(t)}function _wr(e,t){let r=[];return t!==0n&&(r.push(Bwe(1,0)),kwe(r,t)),pk(r,3,bwr(e)),Uint8Array.from(r)}function vwr(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.error=upt.decode(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function wwr(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Wd(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]=Wd(e,t),u=c,d=u+Number(a);r.error=upt.decode(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function Nwe(e,t,r){if(r===0)return Wd(e,t)[1];if(r===2){let[n,i]=Wd(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 dpt(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.registerNameResponse=vwr(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=wwr(e.subarray(u,d)),t=d}else t=Nwe(e,t,s)}return r}function xwr(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function jwe(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function Ewr(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=jwe(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:dpt(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function Awr(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=jwe(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:dpt(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Cwe(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 Pwr(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>tpt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+jwe(Cwe(t).subarray(0,4)),n>tpt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Cwe(t).subarray(0,n)}return Cwe(t)}async function ppt(e){return(0,rpt.createLibp2p)({...e?{privateKey:await(0,spt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,npt.tcp)()],connectionEncrypters:[(0,ipt.noise)()],streamMuxers:[(0,opt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function fpt(e,t,r){let n=await e.dialProtocol((0,apt.multiaddr)(t),lpt,{signal:AbortSignal.timeout(Swr)});n.send(xwr(r));let i;return Promise.race([Pwr(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),Twr)})]).finally(()=>clearTimeout(i))}async function Iwr(e){let t=await ppt(e.seed);try{let r=await fpt(t,e.relayMultiaddr,gwr(e.name,e.binding,e.requestId??1n)),n=Ewr(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function Owr(e){let t=await ppt(e.seed);try{let r=await fpt(t,e.relayMultiaddr,_wr(e.name,e.requestId??1n)),n=Awr(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,cpt.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var rpt,npt,ipt,opt,spt,apt,cpt,Rwe,upt,lpt,Swr,Twr,tpt,Uwe=P(()=>{"use strict";awe();rpt=require("libp2p"),npt=require("@libp2p/tcp"),ipt=require("@chainsafe/libp2p-noise"),opt=require("@chainsafe/libp2p-yamux"),spt=require("@libp2p/crypto/keys"),apt=require("@multiformats/multiaddr"),cpt=require("uint8arrays/to-string"),Rwe=new TextEncoder,upt=new TextDecoder;lpt="/subway/p2p/1.0.0",Swr=15e3,Twr=15e3,tpt=1<<20});var mk={};Gi(mk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>hpt,MESH:()=>vs,RELAY_URL:()=>Fwe,connectOrThrow:()=>JJ,ensureMailbox:()=>Jwe,isSubwayEnabled:()=>$we,listRegistered:()=>Nwr,loadBindingFor:()=>Wwe,loadRegistry:()=>kv,makeClient:()=>GJ,maybeMintVisaBinding:()=>gpt,meshName:()=>gp,pairedVisaBinding:()=>bpt,readInbox:()=>qwr,registerName:()=>Gwe,resolveActingName:()=>Rwr,resolveMeshName:()=>kwr,seedSubwayKeyFromTapAgent:()=>ypt,sendMessage:()=>Bwr,sendVia:()=>Uwr,subwayKeyPath:()=>WJ,visaRelayMultiaddr:()=>Hwe});function Hwe(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??hpt}function gp(e){return e.includes(".")?e:`${e}.${vs}`}function $we(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 Kwe(){co.mkdirSync(Vwe,{recursive:!0,mode:448})}function Cwr(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function WJ(e){return uA.join(Vwe,`${Cwr(e)}.key`)}function kv(){if(!co.existsSync(Lwe))return{};try{return JSON.parse(co.readFileSync(Lwe,"utf8"))}catch{return{}}}function Dwe(e){Kwe(),co.writeFileSync(Lwe,JSON.stringify(e,null,2),{mode:384})}function zwe(){try{return fk.userInfo().username}catch{return"local"}}function ypt(e){if(co.existsSync(e)||!co.existsSync(Mwe))return null;let t=co.readdirSync(Mwe).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>uA.join(Mwe,n)).sort((n,i)=>co.statSync(i).mtimeMs-co.statSync(n).mtimeMs)[0];try{let n=JSON.parse(co.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=qA(n.private_key_jwk);return Kwe(),co.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function GJ(e,t={}){return new Qlt({name:gp(e),url:Fwe,keyPath:WJ(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Wwe(e){if(vs!=="visa")return;let t=kv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function JJ(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Fwe})`)),t))])}function Rwr(e){if(e)return e;let t=Object.keys(kv());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 gpt(e){if(vs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new f2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await fZ({authUrl:ju(),apiKey:t,seed:hB(WJ(e)),name:gp(e)})}catch(r){if(r instanceof f2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function bpt(e=Date.now()){let t=Ywe();if(!t?.binding_jwt)return null;let r=hk(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 Gwe(e){let t=WJ(e),r=ypt(t),n=gp(e);vs==="visa"&&!co.existsSync(t)&&(Kwe(),co.writeFileSync(t,(0,mpt.randomBytes)(32),{mode:384}));let i=vs==="visa"?bpt():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await gpt(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=vs==="visa"?Hwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(Uwe(),qwe)),d=await u({relayMultiaddr:a,seed:hB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=kv();return l[e]={relayName:n,mesh:vs,peerId:d.peerId,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(l),{relayName:n,mesh:vs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(vs==="visa"&&!process.env.SUBWAY_RELAY){let u=kv();return u[e]={relayName:n,mesh:vs,peerId:null,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(u),{relayName:n,mesh:vs,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=GJ(e,{autoReconnect:!1,binding:o});try{await JJ(c);let u=kv();return u[e]={relayName:n,mesh:vs,peerId:c.peerId,owner:zwe(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Dwe(u),{relayName:n,mesh:vs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function kwr(e){let t=gp(e),r=vs==="visa"?Hwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Uwe(),qwe)),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 Bwr(e,t,r){let n=GJ(e,{autoReconnect:!1,binding:Wwe(e)});try{await JJ(n);let i=gp(t);return await n.sendSigned(i,"chat",r),{to:i,as:gp(e)}}finally{n.disconnect()}}function Nwr(){let e=kv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Jwe(e){let t=KJ.get(e);if(t)return{relayName:gp(e),peerId:t.client.peerId};let r=GJ(e,{autoReconnect:!0,binding:Wwe(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>jwr&&n.shift()}),KJ.set(e,{client:r,buffer:n}),await JJ(r),{relayName:gp(e),peerId:r.peerId}}async function qwr(e,t=20,r=!1){await Jwe(e);let n=KJ.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function Uwr(e,t,r){await Jwe(e);let n=KJ.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gp(e)}}var co,fk,uA,mpt,vs,hpt,Fwe,Vwe,Lwe,Mwe,KJ,jwr,Bv=P(()=>{"use strict";ept();p2();co=Ze(require("fs")),fk=Ze(require("os")),uA=Ze(require("path")),mpt=require("crypto");s4();MA();YJ();vs=process.env.SUBWAY_MESH??"relay",hpt="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Fwe=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Vwe=uA.join(fk.homedir(),".visa-cli","subway"),Lwe=uA.join(Vwe,"registry.json"),Mwe=uA.join(fk.homedir(),".visa-cli","agents");KJ=new Map,jwr=200});async function Mwr(e){if(process.env.SUBWAY_MESH==="visa")try{await Gwe(e)}catch(t){Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)})}}function Dwr(e=process.env.VISA_V4_HOME||dA.join(Zwe.homedir(),".visa-v4")){try{let t=qc.readFileSync(dA.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 Xwe(e,t,r=yk){return dA.join(r,`${e}.${t}.json`)}function vpt(e,t=yk){qc.mkdirSync(t,{recursive:!0,mode:448}),qc.writeFileSync(Xwe(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function gk(e,t,r=yk){qc.rmSync(Xwe(e,t,r),{force:!0})}function ZJ(e,t,r=yk){try{let n=JSON.parse(qc.readFileSync(Xwe(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function Qwe(e=yk){return qc.existsSync(e)?qc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(qc.readFileSync(dA.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 Nv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":_pt,...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 e8e(e={}){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=c9e(),n=Dwr(),{body:i}=await Nv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:u9e(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 vpt(o,e.pairingDir),o}async function XJ(e){let{pairing:t}=e,{body:r}=await Nv(`${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 t8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),{body:r}=await Nv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function wpt(e,t){return Buffer.from(p4(e,Buffer.from(t,"utf8"))).toString("base64url")}async function r8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await t8e({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=pB();i=m.secretKey,s=f4(i),o=ch(m.publicKey)}let a=m4(o),c=xJ(),u=d9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:_pt},l=wpt(i,l9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:lZ(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()};vpt(p,e.pairingDir);let{body:f}=await Nv(`${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!==fB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function QJ(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 Nv(`${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=wJ(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))||f9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=wpt(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),p9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await Nv(`${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}:{}}),n8e(h,e.agentDir),await Mwr(u),gk(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 xpt(e){let{pairing:t}=e,{body:r}=await Nv(`${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"&&gk(t.pairingId,"human",e.pairingDir),r}var qc,Zwe,dA,_pt,yk,Ept=P(()=>{"use strict";qc=Ze(require("node:fs")),Zwe=Ze(require("node:os")),dA=Ze(require("node:path"));p2();MA();Bv();s4();Dc();K4e();YJ();_pt="4.1.0-rc.29",yk=dA.join(Zwe.homedir(),".visa-cli","pairings")});var Cpt={};Gi(Cpt,{agentFilePath:()=>_k,agentFormatIsJson:()=>bk,attachAgentCommand:()=>Fwr,claimOptsFromFlags:()=>s8e,decodeBindingClaims:()=>hk,enrollClaimEnvelope:()=>Ipt,isAgentCommandEnabled:()=>Ppt,isAgentRecord:()=>vk,listAgentFiles:()=>eY,newestAgentRecord:()=>Ywe,readAgent:()=>a8e,resolveAgentByRef:()=>Opt,writeAgent:()=>n8e});function vk(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 Ppt(){return!0}function bk(e){return e==="json"}function Ipt(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 s8e(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 i8e(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
  `}
@@ -20765,12 +20765,12 @@ Approve it in your browser \u2014 grant the new rail to your existing agent.
20765
20765
  `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(r=>{let n=a8e(r);if(!n){let o=_k(r);process.stderr.write(Do.existsSync(o)?`Invalid or unreadable agent record: ${r}
20766
20766
  `:`Agent not found: ${r}
20767
20767
  `),process.exit(1)}let i=n.binding_jwt?hk(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: ${_k(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
20768
- `))})}var Spt,Do,Tpt,jv,o8e,qv,YJ=P(()=>{"use strict";Spt=require("node:child_process"),Do=Ze(require("fs")),Tpt=Ze(require("os")),jv=Ze(require("path")),o8e=require("node:readline/promises");p2();WY();UY();G4e();Udt();zdt();Ept();qv=jv.join(Tpt.homedir(),".visa-cli","agents")});var d8e={};Gi(d8e,{CardDrawRefusedError:()=>Uv,cardDrawIntentHash:()=>Npt,decimalUsdToCents:()=>u8e,fetchCardDrawVerdict:()=>Zwr,loadCardMandateCapability:()=>Ywr,registerCardMandate:()=>Xwr});function Vwr(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,c8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function Kwr(e){let{secretKey:t,publicKey:r}=o9e(e),n=f4(t),i=ch(r);return{privateJwk:n,publicJwk:i,jkt:Vwr(i)}}async function kpt(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:$wr},o=`${Rpt(i)}.${Rpt(n)}`,s=qA(e.privateJwk),a=p4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Bpt(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(!Wwr.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:Gwr,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,c8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function Jwr(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 u8e(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 Npt(e,t){let r=u8e(e.amount);return r===null?null:Bpt({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Ywr(e={}){let t=e.record!==void 0?e.record:(YJ(),ie(Cpt)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=Jwr(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=Kwr(qA(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 jpt(e){return e.replace(/\/+$/,"")}async function Zwr(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=jpt(e.authBaseUrl),i=Npt(e.draw,e.drawId);if(i===null)throw new Uv(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 Uv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Uv(502,["challenge_malformed"]);let a=await kpt(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 Uv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function Xwr(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=jpt(e.authBaseUrl),i=u8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Bpt({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 kpt(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 c8e,$wr,Rpt,Wwr,Gwr,Uv,l8e=P(()=>{"use strict";c8e=require("node:crypto");p2();$wr="visa-agent-pop+jwt",Rpt=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");Wwr=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),Gwr=1;Uv=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 xY={};Gi(xY,{initSentry:()=>Sxr,isSentryConfigured:()=>Axr,reportFatal:()=>Txr});function Axr(){return!1}async function Sxr(){return null}async function Txr(e,t){process.exit(t?.exitCode??1)}var EY=P(()=>{});var hmt=require("@modelcontextprotocol/sdk/server/index.js"),ymt=require("@modelcontextprotocol/sdk/server/stdio.js"),Pm=require("@modelcontextprotocol/sdk/types.js");async function j8e(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 Uk=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var q8e={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 U8e(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&&q8e[r]?q8e[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 kmt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function D8e(e,t){let r=M8e(e),n=M8e(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:Bmt(r.pre,n.pre)>0}function M8e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(kmt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Bmt(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 Mk(){return!!(z8e(process.env.VISA_CLI_NO_UPDATE_CHECK)||z8e(process.env.CI)||process.env.NODE_ENV==="test")}function z8e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}s4();var $k="4.1.0-rc.28",Gmt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function Jmt(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 Ymt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function a4(e){return typeof e=="string"?e.trim():""}function Zmt(e){let t=e&&typeof e=="object"?e:{},r=a4(t.error)||a4(t.message);if(!r)return Ymt;let n=a4(t.error_code),i=[["surface",a4(t.disabled_surface)],["flag",a4(t.flag)],["correlation_id",a4(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 Xmt(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?Gmt.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(`
20768
+ `))})}var Spt,Do,Tpt,jv,o8e,qv,YJ=P(()=>{"use strict";Spt=require("node:child_process"),Do=Ze(require("fs")),Tpt=Ze(require("os")),jv=Ze(require("path")),o8e=require("node:readline/promises");p2();WY();UY();G4e();Udt();zdt();Ept();qv=jv.join(Tpt.homedir(),".visa-cli","agents")});var d8e={};Gi(d8e,{CardDrawRefusedError:()=>Uv,cardDrawIntentHash:()=>Npt,decimalUsdToCents:()=>u8e,fetchCardDrawVerdict:()=>Zwr,loadCardMandateCapability:()=>Ywr,registerCardMandate:()=>Xwr});function Vwr(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,c8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function Kwr(e){let{secretKey:t,publicKey:r}=o9e(e),n=f4(t),i=ch(r);return{privateJwk:n,publicJwk:i,jkt:Vwr(i)}}async function kpt(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:$wr},o=`${Rpt(i)}.${Rpt(n)}`,s=qA(e.privateJwk),a=p4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Bpt(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(!Wwr.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:Gwr,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,c8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function Jwr(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 u8e(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 Npt(e,t){let r=u8e(e.amount);return r===null?null:Bpt({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Ywr(e={}){let t=e.record!==void 0?e.record:(YJ(),ie(Cpt)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=Jwr(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=Kwr(qA(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 jpt(e){return e.replace(/\/+$/,"")}async function Zwr(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=jpt(e.authBaseUrl),i=Npt(e.draw,e.drawId);if(i===null)throw new Uv(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 Uv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Uv(502,["challenge_malformed"]);let a=await kpt(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 Uv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function Xwr(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=jpt(e.authBaseUrl),i=u8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Bpt({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 kpt(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 c8e,$wr,Rpt,Wwr,Gwr,Uv,l8e=P(()=>{"use strict";c8e=require("node:crypto");p2();$wr="visa-agent-pop+jwt",Rpt=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");Wwr=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),Gwr=1;Uv=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 xY={};Gi(xY,{initSentry:()=>Sxr,isSentryConfigured:()=>Axr,reportFatal:()=>Txr});function Axr(){return!1}async function Sxr(){return null}async function Txr(e,t){process.exit(t?.exitCode??1)}var EY=P(()=>{});var hmt=require("@modelcontextprotocol/sdk/server/index.js"),ymt=require("@modelcontextprotocol/sdk/server/stdio.js"),Pm=require("@modelcontextprotocol/sdk/types.js");async function j8e(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 Uk=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var q8e={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 U8e(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&&q8e[r]?q8e[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 kmt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function D8e(e,t){let r=M8e(e),n=M8e(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:Bmt(r.pre,n.pre)>0}function M8e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(kmt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Bmt(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 Mk(){return!!(z8e(process.env.VISA_CLI_NO_UPDATE_CHECK)||z8e(process.env.CI)||process.env.NODE_ENV==="test")}function z8e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}s4();var $k="4.1.0-rc.29",Gmt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function Jmt(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 Ymt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function a4(e){return typeof e=="string"?e.trim():""}function Zmt(e){let t=e&&typeof e=="object"?e:{},r=a4(t.error)||a4(t.message);if(!r)return Ymt;let n=a4(t.error_code),i=[["surface",a4(t.disabled_surface)],["flag",a4(t.flag)],["correlation_id",a4(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 Xmt(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?Gmt.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(`
20769
20769
  `)}var Vk=class{constructor(t){this.getSessionToken=t;this.baseUrl=ju()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Mk()){let n=t.headers.get("X-Latest-Version");n&&D8e(n,$k)&&(this.lastSignals.updateAvailable={currentVersion:$k,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return $k}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Uk(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(Zmt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(Xmt());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 j8e(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":$k,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(U8e(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),Jmt(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)}};UY();var g3e=require("child_process"),b3e=require("util"),_3e=Ze(require("crypto")),$r=Ze(require("fs")),v3e=Ze(require("os")),xs=Ze(require("path"));Dc();Gk();RA();var Qk=(0,b3e.promisify)(g3e.execFile);var m0t=()=>process.platform==="darwin",tB=()=>process.platform==="win32",oh=xs.join(v3e.homedir(),".visa-mcp","bin"),a2=xs.join(oh,"Visa CLI"),Cm=xs.join(oh,"visa-keychain-win.exe"),w3e=xs.join(__dirname,"..","native"),d3e="6",l3e=xs.join(oh,"visa-keychain.version"),p3e=xs.join(oh,"visa-keychain.sha256"),f3e="1",m3e=xs.join(oh,"visa-keychain-win.version"),h3e=xs.join(oh,"visa-keychain-win.sha256"),x3e=[xs.join(w3e,"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 eB(e){let t=$r.readFileSync(e);return _3e.createHash("sha256").update(t).digest("hex")}function h0t(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 y0t(){try{if($r.readFileSync(l3e,"utf-8").trim()===d3e&&$r.existsSync(a2)){let n=$r.readFileSync(p3e,"utf-8").trim();if(eB(a2)!==n)Be.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),$r.unlinkSync(a2);else return a2}}catch{}let e=xs.join(w3e,"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(oh,{recursive:!0,mode:448});try{await Qk("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",a2,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=eB(a2);return $r.writeFileSync(p3e,t,{mode:384}),$r.writeFileSync(l3e,d3e,{mode:384}),a2}function E3e(){for(let e of x3e)if($r.existsSync(e))return e;return null}async function A3e(){try{if($r.readFileSync(m3e,"utf-8").trim()===f3e&&$r.existsSync(Cm)){let n=$r.readFileSync(h3e,"utf-8").trim();if(eB(Cm)!==n)Be.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),$r.unlinkSync(Cm);else return Cm}}catch{}let e=E3e();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
20770
20770
  If building from source, run native/build-win.bat first.`);$r.mkdirSync(oh,{recursive:!0}),$r.copyFileSync(e,Cm);let t=eB(Cm);return $r.writeFileSync(h3e,t,{mode:384}),$r.writeFileSync(m3e,f3e,{mode:384}),Cm}async function g0t(){return tB()?A3e():y0t()}var b0t="visa-cli",_0t="attestation-key";async function v0t(e){let t=await g0t(),r;try{r=(await Qk(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 h0t(r)}var y3e=!1;function w0t(){if(!tB())return!1;try{return $r.existsSync(Cm)||E3e()!==null?!0:(y3e||(y3e=!0,Be.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Cm,searchedPrebuiltPaths:x3e})),!1)}catch{return!1}}function S3e(){return Wk()||m0t()?!0:tB()?w0t():!1}async function T3e(){if(tB()){try{let e=await A3e();await Qk(e,["delete-key"],{timeout:1e4})}catch{}return}if(await ih())try{await Qk("security",["delete-generic-password","-s",b0t,"-a",_0t],{timeout:5e3})}catch{}try{await v0t(["delete-key"])}catch{}}RA();Dc();WY();G4e();var $ft=require("child_process"),gY=Ze(require("fs")),bY=Ze(require("os")),Vft=Ze(require("path"));var bm=Ze(require("fs")),EJ=Ze(require("os")),yp=Ze(require("path"));var L5r="# >>> visa-cli shell hud v2 >>>",H5r="# <<< visa-cli shell hud v2 <<<";function F5r(e){let t=e??process.env.SHELL;if(!t)return null;let r=yp.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 $5r(e){let t=J5r();if(e==="zsh")return yp.join(t,".zshrc");if(e==="bash")return yp.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return yp.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function V5r(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 K5r(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${ydt(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${ydt(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!V5r(a))return i;let l=d>0?e[d-1]:"";return o===`
20771
20771
  `&&l!==`
20772
20772
  `?`
20773
- `:""})}function W5r(e){return K5r(e,L5r,H5r).trimEnd()}function G5r(e){return W5r(e)!==e.trimEnd()}function AJ(e=F5r()){if(!e)return!1;try{let t=$5r(e),r=bm.readFileSync(t,"utf-8");return G5r(r)}catch{return!1}}function ydt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J5r(){let e=EJ.homedir();if(!e||!yp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return yp.resolve(e)}var p5n=1440*60*1e3;var Y5r="# visa-cli-hud-v1";function gdt(e){return typeof e!="string"?!1:e.includes(Y5r)?!0:e.includes("visa-cli")&&e.includes("statusline")}s4();Gk();var bdt="4.1.0-rc.28";function J4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Z5r(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=jY(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function eA(e){return e==null?"\u2014":e?"yes":"no"}async function _dt(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=NY("auth.serverUrl"),s=ju(),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:eA(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=Z5r("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:eA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=Mk(),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:eA(!u),source:d}),n.push({key:"client.version",value:bdt,formatted:bdt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=th();n.push({key:"dev.mockKeychain",value:p,formatted:eA(p),source:J4e("VISA_MOCK_KEYCHAIN",!!l),hint:DY()});let f=process.env.VISA_MOCK_TOUCHID,m=Wk();n.push({key:"dev.mockTouchid",value:m,formatted:eA(m),source:J4e("VISA_MOCK_TOUCHID",!!f),hint:DY()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:eA(!!h),source:J4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var f8e=require("node:os"),wk=require("node:path"),xk=require("node:fs/promises"),Upt=require("node:fs"),Mpt=require("node:url"),Dpt=require("node:crypto");Dc();var X5r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Y4e(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!X5r.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var L1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function Z4e(e){let t;try{t=new URL(e)}catch{throw new L1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new L1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Dc();var Q5r={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},vdt=300*1e3,X4e={},Q4e=0,ik=null;function ewe(){return ik||(ik=(async()=>{try{let e=await Qs.getFeatureFlags();X4e=e&&e.flags||{},Q4e=Date.now()}catch(e){X4e={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{ik=null}})(),ik)}async function wdt(){await ewe()}function xdt(){Date.now()-Q4e<vdt||ewe()}async function tA(){Date.now()-Q4e<vdt||await ewe()}function _m(e){let t=Q5r[e];return t?X4e[t]!==!0:!1}var Edt=require("node:crypto"),ok=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},SJ=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 ok(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??Edt.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 zpt(e){return[(0,wk.join)(e,"checkout-engine","index.js"),(0,wk.join)(e,"..","checkout-engine","index.js")]}function Qwr(e,t=Upt.existsSync){return zpt(e).find(r=>t(r))??null}var tY=null,Lpt=async()=>{if(tY)return tY;let e=Qwr(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${zpt(__dirname).join(" and ")}).`);return tY=(await import((0,Mpt.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await e8r(),cardMandateRegister:await t8r()}),tY};async function e8r(){let e=await Promise.resolve().then(()=>(l8e(),d8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function t8r(){let e=await Promise.resolve().then(()=>(l8e(),d8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function m8e(){return _m("pay_merchant")?(await tA(),_m("pay_merchant")):!1}var Hpt=(0,wk.join)((0,f8e.homedir)(),".visa-mcp","agent-credential.json"),Fpt=(0,wk.join)((0,f8e.homedir)(),".visa-mcp","contact.json"),$pt=new SJ;function Ek(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var r8r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Vpt(e){return r8r.has(e)?e:null}async function rY(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?Ek(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:Vpt(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 qpt(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?Ek(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:Vpt(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 p8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new L1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Kpt(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=Ek(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 Wpt(e={},t={}){if(await(t.flagDisabled??m8e)())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??$pt).get(n);return o?Kpt(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 Gpt(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:qY()&&!process.env.VISA_VERIFY_WEB_URL?null:rl();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??m8e)())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??$pt,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=Z4e(e.url??"").toString(),c=p8e(e.amount)}catch(C){if(C instanceof L1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Hpt,l=t.contactPath??Fpt;try{await(0,xk.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,xk.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??Lpt,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=>Qs.emitTelemetry(C)),x=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:x,currency:u});let C;try{C=await h.review(y)}catch(I){throw await rY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await rY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${Y4e(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 E=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:E,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:E,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await rY({emitTelemetry:w,action:"pay",merchantHost:x,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 rY({emitTelemetry:w,action:"pay",merchantHost:x,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"?E:null});let U=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:E,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${U}`:`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,Dpt.createHash)("sha256").update(JSON.stringify([E,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:E,merchantHost:x,currency:u,submit:A});try{let I=await s.start({reviewId:E,fingerprint:C,run:async R=>{try{let U=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:E}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:E,success:U.success===!0}),U}catch(U){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:E,error:Ek(U instanceof Error?U.message:String(U))}),U}}});return Kpt(I,"authorize")}catch(I){if(I instanceof ok)return Be.warn("pay_merchant:approval_handoff_conflict",{reviewId:E}),{success:!1,action:"authorize",reviewId:E,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 Jpt(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:rl();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??m8e)())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:Z4e(e.url??"").toString(),c=p8e(e.ceiling??e.amount)}catch(A){if(A instanceof L1)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=p8e(e.perTransaction)}catch(A){if(A instanceof L1)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??Hpt,p=t.contactPath??Fpt;try{await(0,xk.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,xk.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??Lpt,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),x=t.emitTelemetry??(A=>Qs.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?Ek(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await qpt({emitTelemetry:x,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 E=v.registerFailed===!0;return E&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await qpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),E?{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 ${Y4e(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 Lft=require("node:crypto");var Uft=require("node:crypto");var jr={};Gi(jr,{BRAND:()=>I8r,DIRTY:()=>Mv,EMPTY_PATH:()=>s8r,INVALID:()=>ht,NEVER:()=>i3r,OK:()=>ia,ParseStatus:()=>ws,Schema:()=>Ut,ZodAny:()=>n2,ZodArray:()=>Z1,ZodBigInt:()=>zv,ZodBoolean:()=>Lv,ZodBranded:()=>Sk,ZodCatch:()=>Xv,ZodDate:()=>Hv,ZodDefault:()=>Zv,ZodDiscriminatedUnion:()=>oY,ZodEffects:()=>Yd,ZodEnum:()=>Jv,ZodError:()=>Uc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>aY,ZodIntersection:()=>Kv,ZodIssueCode:()=>ye,ZodLazy:()=>Wv,ZodLiteral:()=>Gv,ZodMap:()=>yA,ZodNaN:()=>bA,ZodNativeEnum:()=>Yv,ZodNever:()=>bp,ZodNull:()=>$v,ZodNullable:()=>Tm,ZodNumber:()=>Dv,ZodObject:()=>Mc,ZodOptional:()=>Gd,ZodParsedType:()=>Ce,ZodPipeline:()=>Tk,ZodPromise:()=>i2,ZodReadonly:()=>Qv,ZodRecord:()=>sY,ZodSchema:()=>Ut,ZodSet:()=>gA,ZodString:()=>r2,ZodSymbol:()=>mA,ZodTransformer:()=>Yd,ZodTuple:()=>Sm,ZodType:()=>Ut,ZodUndefined:()=>Fv,ZodUnion:()=>Vv,ZodUnknown:()=>Y1,ZodVoid:()=>hA,addIssueToContext:()=>Ae,any:()=>Xd,array:()=>ue,bigint:()=>k8r,boolean:()=>Zd,coerce:()=>Nu,custom:()=>nft,date:()=>B8r,datetimeRegex:()=>tft,defaultErrorMap:()=>G1,discriminatedUnion:()=>z8r,effect:()=>Y8r,enum:()=>Qd,function:()=>V8r,getErrorMap:()=>lA,getParsedType:()=>Am,instanceof:()=>C8r,intersection:()=>L8r,isAborted:()=>nY,isAsync:()=>pA,isDirty:()=>iY,isValid:()=>t2,late:()=>O8r,lazy:()=>K8r,literal:()=>W8r,makeIssue:()=>Ak,map:()=>F8r,nan:()=>R8r,nativeEnum:()=>G8r,never:()=>U8r,null:()=>_A,nullable:()=>X8r,number:()=>Ir,object:()=>fe,objectUtil:()=>h8e,oboolean:()=>n3r,onumber:()=>r3r,optional:()=>Z8r,ostring:()=>t3r,pipeline:()=>e3r,preprocess:()=>Q8r,promise:()=>J8r,quotelessJson:()=>n8r,record:()=>Yt,set:()=>$8r,setErrorMap:()=>o8r,strictObject:()=>D8r,string:()=>z,symbol:()=>N8r,transformer:()=>Y8r,tuple:()=>H8r,undefined:()=>j8r,union:()=>vA,unknown:()=>q8r,util:()=>Jt,void:()=>M8r});var Jt;(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})(Jt||(Jt={}));var h8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(h8e||(h8e={}));var Ce=Jt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Am=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=Jt.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"]),n8r=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Uc=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,Jt.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()}};Uc.create=e=>new Uc(e);var i8r=(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,Jt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Jt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Jt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Jt.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}"`:Jt.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,Jt.assertNever(e)}return{message:r}},G1=i8r;var Ypt=G1;function o8r(e){Ypt=e}function lA(){return Ypt}var Ak=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}},s8r=[];function Ae(e,t){let r=lA(),n=Ak({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===G1?void 0:G1].filter(i=>!!i)});e.common.issues.push(n)}var ws=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"}),Mv=e=>({status:"dirty",value:e}),ia=e=>({status:"valid",value:e}),nY=e=>e.status==="aborted",iY=e=>e.status==="dirty",t2=e=>e.status==="valid",pA=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 Jd=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}},Zpt=(e,t)=>{if(t2(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 Uc(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 Ut=class{get description(){return this._def.description}_getType(t){return Am(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Am(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ws,ctx:{common:t.parent.common,data:t.data,parsedType:Am(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(pA(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:Am(t)},i=this._parseSync({data:t,path:n.path,parent:n});return Zpt(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Am(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return t2(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=>t2(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:Am(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(pA(i)?i:Promise.resolve(i));return Zpt(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 Yd({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 Gd.create(this,this._def)}nullable(){return Tm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z1.create(this)}promise(){return i2.create(this,this._def)}or(t){return Vv.create([this,t],this._def)}and(t){return Kv.create(this,t,this._def)}transform(t){return new Yd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Zv({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new Sk({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Xv({...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 Tk.create(this,t)}readonly(){return Qv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},a8r=/^c[^\s-]{8,}$/i,c8r=/^[0-9a-z]+$/,u8r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d8r=/^[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,l8r=/^[a-z0-9_-]{21}$/i,p8r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,f8r=/^[-+]?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)?)??$/,m8r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h8r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y8e,y8r=/^(?:(?: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])$/,g8r=/^(?:(?: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])$/,b8r=/^(([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]))$/,_8r=/^(([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])$/,v8r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w8r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qpt="((\\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])))",x8r=new RegExp(`^${Qpt}$`);function eft(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 E8r(e){return new RegExp(`^${eft(e)}$`)}function tft(e){let t=`${Qpt}T${eft(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 A8r(e,t){return!!((t==="v4"||!t)&&y8r.test(e)||(t==="v6"||!t)&&b8r.test(e))}function S8r(e,t){if(!p8r.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 T8r(e,t){return!!((t==="v4"||!t)&&g8r.test(e)||(t==="v6"||!t)&&_8r.test(e))}var r2=class e extends Ut{_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 ws,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")m8r.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")y8e||(y8e=new RegExp(h8r,"u")),y8e.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")d8r.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")l8r.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")a8r.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")c8r.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")u8r.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"?tft(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"?x8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?E8r(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"?f8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?A8r(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"?S8r(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"?T8r(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"?v8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?w8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Jt.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}};r2.create=e=>new r2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function P8r(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 Dv=class e extends Ut{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 ws;for(let o of this._def.checks)o.kind==="int"?Jt.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"?P8r(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()):Jt.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"&&Jt.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)}};Dv.create=e=>new Dv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var zv=class e extends Ut{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 ws;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()):Jt.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 Lv=class extends Ut{_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 ia(t.data)}};Lv.create=e=>new Lv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Hv=class e extends Ut{_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 ws,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()):Jt.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}};Hv.create=e=>new Hv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var mA=class extends Ut{_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 ia(t.data)}};mA.create=e=>new mA({typeName:wt.ZodSymbol,...Bt(e)});var Fv=class extends Ut{_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 ia(t.data)}};Fv.create=e=>new Fv({typeName:wt.ZodUndefined,...Bt(e)});var $v=class extends Ut{_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 ia(t.data)}};$v.create=e=>new $v({typeName:wt.ZodNull,...Bt(e)});var n2=class extends Ut{constructor(){super(...arguments),this._any=!0}_parse(t){return ia(t.data)}};n2.create=e=>new n2({typeName:wt.ZodAny,...Bt(e)});var Y1=class extends Ut{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ia(t.data)}};Y1.create=e=>new Y1({typeName:wt.ZodUnknown,...Bt(e)});var bp=class extends Ut{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};bp.create=e=>new bp({typeName:wt.ZodNever,...Bt(e)});var hA=class extends Ut{_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 ia(t.data)}};hA.create=e=>new hA({typeName:wt.ZodVoid,...Bt(e)});var Z1=class e extends Ut{_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 Jd(r,s,r.path,a)))).then(s=>ws.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Jd(r,s,r.path,a)));return ws.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)}};Z1.create=(e,t)=>new Z1({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function fA(e){if(e instanceof Mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Gd.create(fA(n))}return new Mc({...e._def,shape:()=>t})}else return e instanceof Z1?new Z1({...e._def,type:fA(e.element)}):e instanceof Gd?Gd.create(fA(e.unwrap())):e instanceof Tm?Tm.create(fA(e.unwrap())):e instanceof Sm?Sm.create(e.items.map(t=>fA(t))):e}var Mc=class e extends Ut{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=Jt.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 bp&&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 Jd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof bp){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 Jd(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=>ws.mergeObjectSync(n,u)):ws.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 Jt.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 Jt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return fA(this)}partial(t){let r={};for(let n of Jt.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 Jt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Gd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return rft(Jt.objectKeys(this.shape))}};Mc.create=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.strictCreate=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strict",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.lazycreate=(e,t)=>new Mc({shape:e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});var Vv=class extends Ut{_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 Uc(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 Uc(c));return Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};Vv.create=(e,t)=>new Vv({options:e,typeName:wt.ZodUnion,...Bt(t)});var J1=e=>e instanceof Wv?J1(e.schema):e instanceof Yd?J1(e.innerType()):e instanceof Gv?[e.value]:e instanceof Jv?e.options:e instanceof Yv?Jt.objectValues(e.enum):e instanceof Zv?J1(e._def.innerType):e instanceof Fv?[void 0]:e instanceof $v?[null]:e instanceof Gd?[void 0,...J1(e.unwrap())]:e instanceof Tm?[null,...J1(e.unwrap())]:e instanceof Sk||e instanceof Qv?J1(e.unwrap()):e instanceof Xv?J1(e._def.innerType):[],oY=class e extends Ut{_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=J1(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 g8e(e,t){let r=Am(e),n=Am(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Jt.objectKeys(t),o=Jt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=g8e(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=g8e(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 Kv=class extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(nY(o)||nY(s))return ht;let a=g8e(o.value,s.value);return a.valid?((iY(o)||iY(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}))}};Kv.create=(e,t,r)=>new Kv({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Sm=class e extends Ut{_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 Jd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ws.mergeArray(r,s)):ws.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Sm.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Sm({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var sY=class e extends Ut{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 Jd(n,a,n.path,a)),value:s._parse(new Jd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ws.mergeObjectAsync(r,i):ws.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ut?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:r2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},yA=class extends Ut{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 Jd(n,a,n.path,[u,"key"])),value:o._parse(new Jd(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}}}};yA.create=(e,t,r)=>new yA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var gA=class e extends Ut{_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 Jd(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)}};gA.create=(e,t)=>new gA({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var aY=class e extends Ut{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 Ak({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lA(),G1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Ak({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lA(),G1].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 i2){let a=this;return ia(async function(...c){let u=new Uc([]),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 ia(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Uc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Uc([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:Sm.create(t).rest(Y1.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||Sm.create([]).rest(Y1.create()),returns:r||Y1.create(),typeName:wt.ZodFunction,...Bt(n)})}},Wv=class extends Ut{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})}};Wv.create=(e,t)=>new Wv({getter:e,typeName:wt.ZodLazy,...Bt(t)});var Gv=class extends Ut{_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}};Gv.create=(e,t)=>new Gv({value:e,typeName:wt.ZodLiteral,...Bt(t)});function rft(e,t){return new Jv({values:e,typeName:wt.ZodEnum,...Bt(t)})}var Jv=class e extends Ut{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Jt.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 ia(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})}};Jv.create=rft;var Yv=class extends Ut{_parse(t){let r=Jt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Jt.objectValues(r);return Ae(n,{expected:Jt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Jt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Jt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return ia(t.data)}get enum(){return this._def.values}};Yv.create=(e,t)=>new Yv({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var i2=class extends Ut{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 ia(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};i2.create=(e,t)=>new i2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Yd=class extends Ut{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"?Mv(c.value):r.value==="dirty"?Mv(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"?Mv(a.value):r.value==="dirty"?Mv(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(!t2(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=>t2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Jt.assertNever(i)}};Yd.create=(e,t,r)=>new Yd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Yd.createWithPreprocess=(e,t,r)=>new Yd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Gd=class extends Ut{_parse(t){return this._getType(t)===Ce.undefined?ia(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Gd.create=(e,t)=>new Gd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Tm=class extends Ut{_parse(t){return this._getType(t)===Ce.null?ia(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Tm.create=(e,t)=>new Tm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var Zv=class extends Ut{_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}};Zv.create=(e,t)=>new Zv({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var Xv=class extends Ut{_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 pA(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Uc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Uc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Xv.create=(e,t)=>new Xv({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var bA=class extends Ut{_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}}};bA.create=e=>new bA({typeName:wt.ZodNaN,...Bt(e)});var I8r=Symbol("zod_brand"),Sk=class extends Ut{_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}},Tk=class e extends Ut{_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(),Mv(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})}},Qv=class extends Ut{_parse(t){let r=this._def.innerType._parse(t),n=i=>(t2(i)&&(i.value=Object.freeze(i.value)),i);return pA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Qv.create=(e,t)=>new Qv({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function Xpt(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function nft(e,t={},r){return e?n2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=Xpt(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=Xpt(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):n2.create()}var O8r={object:Mc.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 C8r=(e,t={message:`Input not instance of ${e.name}`})=>nft(r=>r instanceof e,t),z=r2.create,Ir=Dv.create,R8r=bA.create,k8r=zv.create,Zd=Lv.create,B8r=Hv.create,N8r=mA.create,j8r=Fv.create,_A=$v.create,Xd=n2.create,q8r=Y1.create,U8r=bp.create,M8r=hA.create,ue=Z1.create,fe=Mc.create,D8r=Mc.strictCreate,vA=Vv.create,z8r=oY.create,L8r=Kv.create,H8r=Sm.create,Yt=sY.create,F8r=yA.create,$8r=gA.create,V8r=aY.create,K8r=Wv.create,W8r=Gv.create,Qd=Jv.create,G8r=Yv.create,J8r=i2.create,Y8r=Yd.create,Z8r=Gd.create,X8r=Tm.create,Q8r=Yd.createWithPreprocess,e3r=Tk.create,t3r=()=>z().optional(),r3r=()=>Ir().optional(),n3r=()=>Zd().optional(),Nu={string:(e=>r2.create({...e,coerce:!0})),number:(e=>Dv.create({...e,coerce:!0})),boolean:(e=>Lv.create({...e,coerce:!0})),bigint:(e=>zv.create({...e,coerce:!0})),date:(e=>Hv.create({...e,coerce:!0}))};var i3r=ht;var s3r=Qd(["enc","sig"]),a3r=Qd(["markdown","plain"]),c3r=Qd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),u3r=Qd(["error","info","warning"]),EA=Qd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),d3r=Qd(["completed","failed","pending"]),l3r=Qd(["digital","pickup","shipping"]),p3r=Qd(["fulfilled","partial","processing","removed"]),f3r=Qd(["across","each"]),b8e=Qd(["pickup","shipping"]),m3r=fe({config:Yt(z(),Xd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),h3r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:s3r.optional(),x:z().optional(),y:z().optional()}),y3r=fe({config:Yt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),g3r=fe({endpoint:z()}),b3r=fe({schema:z()}),ift=fe({endpoint:z(),schema:z()}),_3r=ift,v3r=ift,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),uo=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()}),_8e=uo,oft=fe({id:z()}),w3r=oft,x3r=oft,Pk=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()}),cY=fe({type:z()}),Ki=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),v8e=Ki,sft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),uY=fe({amount:Ir(),display_text:z().optional(),type:z()}),o2=fe({title:z().optional(),type:z(),url:z()}),X1=fe({code:z().optional(),content:z(),content_type:a3r.optional(),path:z().optional(),severity:c3r.optional(),type:u3r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),w8e=X1,AA=fe({id:z(),label:z().optional(),permalink_url:z()}),E3r=fe({amount:Ir(),display_text:z()}),A3r=fe({config:Yt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),x8e=fe({id:z(),quantity:Ir()}),S3r=x8e,T3r=x8e,P3r=x8e,I3r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),O3r=fe({billing_address:Pk.optional(),credential:cY.optional(),display:Yt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z()}),C3r=fe({checkout_mandate:z()}),R3r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),k3r=fe({analytics:Zd().optional(),marketing:Zd().optional(),preferences:Zd().optional(),sale_of_data:Zd().optional()});var B3r=k3r;var aft=fe({codes:ue(z()).optional()}),N3r=aft,j3r=fe({amount:Ir(),path:z()}),q3r=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:Pk.optional(),name:z().optional()}),U3r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:Nu.date().optional(),id:z(),latest_fulfillment_time:Nu.date().optional(),title:z(),totals:ue(uY)}),M3r=fe({description:z().optional(),fulfillable_on:vA([_A(),z()]).optional(),line_item_ids:ue(z()),type:b8e}),D3r=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:Pk.optional(),name:z().optional()}),z3r=fe({max:Ir().optional(),min:Ir().optional()}),Ik=fe({taxonomy:z().optional(),value:z()}),Ok=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),wA=fe({amount:Ir(),currency:z()}),Ck=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),L3r=fe({id:z().optional(),label:z()}),Rk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),cft=fe({available:Zd().optional(),status:z().optional()}),H3r=cft,uft=fe({type:z(),value:z()}),F3r=uft,$3r=fe({id:z(),match:z().optional()}),E8e=fe({id:z().optional(),label:z(),name:z()}),dft=E8e,lft=fe({links:ue(o2).optional(),name:z().optional()}),V3r=lft,pft=fe({unit:z(),value:Ir()});var K3r=pft,W3r=fe({cursor:z().optional(),limit:Ir().optional()}),G3r=fe({cursor:z().optional(),has_next_page:Zd(),total_count:Ir().optional()}),J3r=fe({handlers:ue(m3r).optional()}),Y3r=fe({a2a:g3r.optional(),embedded:b3r.optional(),mcp:_3r.optional(),rest:v3r.optional(),spec:z(),version:z()}),SA=fe({item:w3r,quantity:Ir()}),Z3r=fe({billing_address:Pk.optional(),credential:cY.optional(),display:Yt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z(),selected:Zd().optional()}),kk=fe({id:z().optional(),item:x3r,parent_id:z().optional(),quantity:Ir()}),dY=fe({instruments:ue(Z3r).optional()}),X3r=dY,Bk=dY,TA=dY,lY=dY,e4=fe({id:z(),item:sft,parent_id:z().optional(),quantity:Ir(),totals:ue(uY)}),s2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(E3r).optional()}),_p=fe({capabilities:Yt(z(),ue(A3r)),version:z()}),Q3r=fe({description:z().optional(),id:z(),line_items:ue(S3r).optional(),occurred_at:Nu.date(),status:d3r,totals:ue(uY).optional(),type:z()}),e9r=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(T3r),occurred_at:Nu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),t9r=fe({description:z().optional(),destination:Pk,fulfillable_on:z().optional(),id:z(),line_items:ue(P3r),method_type:l3r}),r9r=fe({id:z(),item:sft,parent_id:z().optional(),quantity:I3r,status:p3r,totals:ue(uY)}),e4n=fe({payment_data:O3r}),t4n=fe({ap2:C3r.optional()}),r4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,ap2:R3r.optional()}),A8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:B3r.optional()}),n9r=A8e,i9r=A8e,fft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional(),discounts:N3r.optional()}),o9r=fe({allocations:ue(j3r).optional(),amount:Ir(),automatic:Zd().optional(),code:z().optional(),eligibility:z().optional(),method:f3r.optional(),priority:Ir().optional(),provisional:Zd().optional(),title:z()}),mft=fe({id:z(),line_item_ids:ue(z()),options:ue(U3r).optional(),selected_option_id:vA([_A(),z()]).optional()}),s9r=fe({destinations:ue(D3r).optional(),groups:ue(mft).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:vA([_A(),z()]).optional(),type:b8e}),n4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),signals:Ki.optional()}),i4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),id:z(),line_items:ue(kk),signals:Ki.optional()}),o4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2).optional(),messages:ue(X1).optional(),signals:Ki.optional(),totals:ue(s2),ucp:_p}),a9r=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional()}),hft=a9r,s4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,cart_id:z().optional()}),S8e=fe({categories:ue(z()).optional(),price:z3r.optional()}),xA=fe({max:wA,min:wA}),T8e=fe({name:z(),values:ue(L3r)}),yft=fe({amount:Ir(),currency:z(),measure:pft,reference:K3r}),c9r=yft,a4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(dft).optional(),signals:v8e.optional()}),c4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),pagination:W3r.optional(),query:z().optional(),signals:v8e.optional()}),u9r=fe({capabilities:ue(y3r),services:Yt(z(),Y3r),version:z()}),u4n=fe({attribution:Yt(z(),z()).optional(),payment:X3r,signals:Ki.optional()}),gft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p}),d9r=fe({events:ue(e9r).optional(),expectations:ue(t9r).optional()}),bft=fe({attribution:Yt(z(),z()).optional(),buyer:A8e.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional()}),_ft=fe({attribution:Yt(z(),z()).optional(),buyer:i9r.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional()}),vft=fe({attribution:Yt(z(),z()).optional(),buyer:n9r.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p}),wft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),discounts:aft.optional()}),l9r=fe({applied:ue(o9r).optional(),codes:ue(z()).optional()}),p9r=fe({destinations:ue(q3r).optional(),groups:ue(mft).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:vA([_A(),z()]).optional(),type:b8e}),f9r=fe({available_methods:ue(M3r).optional(),methods:ue(s9r).optional()}),xft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),cart_id:z().optional()}),d4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),ids:ue(z()),signals:v8e.optional()}),m9r=fe({availability:cft.optional(),barcodes:ue(uft).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price:wA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(E8e).optional(),price:wA,rating:Rk.optional(),seller:lft.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:yft.optional(),url:z().optional(),inputs:ue($3r)}),Eft=fe({availability:H3r.optional(),barcodes:ue(F3r).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price:wA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(E8e).optional(),price:wA,rating:Rk.optional(),seller:V3r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:c9r.optional(),url:z().optional()}),h9r=fe({categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(T8e).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Eft)}),l4n=fe({payment:J3r.optional(),signing_keys:ue(h3r).optional(),ucp:u9r}),Aft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional()}),y9r=fe({adjustments:ue(Q3r).optional(),attribution:Yt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:d9r,id:z(),label:z().optional(),line_items:ue(r9r),messages:ue(X1).optional(),permalink_url:z(),totals:ue(s2),ucp:_p}),Sft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,discounts:l9r.optional()}),Tft=fe({methods:ue(p9r).optional()}),Pft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional(),fulfillment:Tft.optional()}),Ift=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,fulfillment:f9r.optional()}),g9r=fe({categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(T8e).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(m9r)}),b9r=fe({options:ue(T8e).optional(),selected:ue(dft).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Eft)}),p4n=fe({messages:ue(w8e).optional(),pagination:G3r.optional(),products:ue(h9r),ucp:_p}),Oft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),fulfillment:Tft.optional()}),f4n=fe({messages:ue(w8e).optional(),products:ue(g9r),ucp:_p}),m4n=fe({messages:ue(w8e).optional(),product:b9r,ucp:_p});var b4n=cY.extend({token:jr.string().optional()}),_9r=jr.object({webhook_url:jr.string().url().optional()}),Cft=gft.extend(Ift.pick({fulfillment:!0}).shape).extend(Sft.pick({discounts:!0}).shape).extend(vft.pick({buyer:!0}).shape).extend({platform:_9r.optional()}),Rft=Aft.extend(Oft.pick({fulfillment:!0}).shape).extend(wft.pick({discounts:!0}).shape).extend(bft.pick({buyer:!0}).shape).extend(xft.pick({cart_id:!0}).shape),kft=hft.extend(Pft.pick({fulfillment:!0}).shape).extend(fft.pick({discounts:!0}).shape).extend(_ft.pick({buyer:!0}).shape);Dc();async function pY(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 fY(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 v9r=3e4,Bft=2*1024*1024,vp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Nft(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 jft(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"?Rft:kft).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function w9r(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 qft(e,t,r,n){try{e[t](r,n)}catch{}}function x9r(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 mY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Nft(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Nft(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??v9r,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:jft(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:jft(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=fY(this.timeoutMs,this.signal),o=(0,Uft.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 pY(u,Bft,"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 vp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Bft)throw new vp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new vp("UCP MCP response is not valid JSON",void 0,u.status)}if(!w9r(l))throw new vp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new vp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new vp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new vp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new vp("UCP MCP response is missing result.structuredContent");if(!Cft.safeParse(x9r(p.structuredContent)).success)throw new vp("UCP checkout response failed schema validation");return qft(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw qft(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 Dft=require("node:crypto");Dc();var yY="2026-04-08",E9r="dev.ucp.shopping",A9r="dev.ucp.shopping.checkout",S9r=1024*1024,T9r=1e4,P9r="https://ucp.dev",Nk=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"),I9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Nk,schema:Nk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Nk.optional()}).passthrough(),O9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Nk,schema:Nk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),C9r=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(I9r)),capabilities:jr.record(jr.array(O9r)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function R9r(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!==P9r)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Mft(e,t,r,n){try{e[t](r,n)}catch{}}async function k9r(e,t={}){let r=R9r(e,"UCP business URL"),n=fY(t.timeoutMs??T9r,t.signal),i=t.logger??Be,o=(0,Dft.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 pY(c,S9r,"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=C9r.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Mft(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 Mft(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 B9r(e){if(e.ucp.version!==yY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[A9r]?.find(i=>i.version===yY);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[E9r]?.find(i=>i.version===yY&&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 zft(e,t={}){let r=await k9r(e,t);return{...r,endpoint:B9r(r.profile),version:yY}}var N9r="https://app.visacli.sh/.well-known/ucp";function j9r(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 q9r(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 P8e(e,t=new Set){if(Array.isArray(e))for(let r of e)P8e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?q9r(n,t):P8e(n,t);return t}function U9r(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=P8e(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 M9r(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 D9r(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 Hft(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??zft)(e.business),i=await(t.getCheckout??(async(u,d)=>await new mY({endpoint:u.endpoint,platformProfileUrl:j9r(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??N9r)}).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=M9r(i),a=U9r(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Lft.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:D9r(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>."}}s4();function z9r(){return ju()}var Qs=new Vk(()=>Uu.getSessionToken()),L9r="4.1.0-rc.28",Z4n=["","","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(`
20773
+ `:""})}function W5r(e){return K5r(e,L5r,H5r).trimEnd()}function G5r(e){return W5r(e)!==e.trimEnd()}function AJ(e=F5r()){if(!e)return!1;try{let t=$5r(e),r=bm.readFileSync(t,"utf-8");return G5r(r)}catch{return!1}}function ydt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J5r(){let e=EJ.homedir();if(!e||!yp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return yp.resolve(e)}var p5n=1440*60*1e3;var Y5r="# visa-cli-hud-v1";function gdt(e){return typeof e!="string"?!1:e.includes(Y5r)?!0:e.includes("visa-cli")&&e.includes("statusline")}s4();Gk();var bdt="4.1.0-rc.29";function J4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Z5r(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=jY(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function eA(e){return e==null?"\u2014":e?"yes":"no"}async function _dt(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=NY("auth.serverUrl"),s=ju(),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:eA(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=Z5r("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:eA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=Mk(),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:eA(!u),source:d}),n.push({key:"client.version",value:bdt,formatted:bdt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=th();n.push({key:"dev.mockKeychain",value:p,formatted:eA(p),source:J4e("VISA_MOCK_KEYCHAIN",!!l),hint:DY()});let f=process.env.VISA_MOCK_TOUCHID,m=Wk();n.push({key:"dev.mockTouchid",value:m,formatted:eA(m),source:J4e("VISA_MOCK_TOUCHID",!!f),hint:DY()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:eA(!!h),source:J4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var f8e=require("node:os"),wk=require("node:path"),xk=require("node:fs/promises"),Upt=require("node:fs"),Mpt=require("node:url"),Dpt=require("node:crypto");Dc();var X5r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Y4e(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!X5r.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var L1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function Z4e(e){let t;try{t=new URL(e)}catch{throw new L1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new L1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Dc();var Q5r={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},vdt=300*1e3,X4e={},Q4e=0,ik=null;function ewe(){return ik||(ik=(async()=>{try{let e=await Qs.getFeatureFlags();X4e=e&&e.flags||{},Q4e=Date.now()}catch(e){X4e={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{ik=null}})(),ik)}async function wdt(){await ewe()}function xdt(){Date.now()-Q4e<vdt||ewe()}async function tA(){Date.now()-Q4e<vdt||await ewe()}function _m(e){let t=Q5r[e];return t?X4e[t]!==!0:!1}var Edt=require("node:crypto"),ok=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},SJ=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 ok(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??Edt.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 zpt(e){return[(0,wk.join)(e,"checkout-engine","index.js"),(0,wk.join)(e,"..","checkout-engine","index.js")]}function Qwr(e,t=Upt.existsSync){return zpt(e).find(r=>t(r))??null}var tY=null,Lpt=async()=>{if(tY)return tY;let e=Qwr(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${zpt(__dirname).join(" and ")}).`);return tY=(await import((0,Mpt.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await e8r(),cardMandateRegister:await t8r()}),tY};async function e8r(){let e=await Promise.resolve().then(()=>(l8e(),d8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function t8r(){let e=await Promise.resolve().then(()=>(l8e(),d8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function m8e(){return _m("pay_merchant")?(await tA(),_m("pay_merchant")):!1}var Hpt=(0,wk.join)((0,f8e.homedir)(),".visa-mcp","agent-credential.json"),Fpt=(0,wk.join)((0,f8e.homedir)(),".visa-mcp","contact.json"),$pt=new SJ;function Ek(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var r8r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Vpt(e){return r8r.has(e)?e:null}async function rY(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?Ek(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:Vpt(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 qpt(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?Ek(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:Vpt(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 p8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new L1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Kpt(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=Ek(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 Wpt(e={},t={}){if(await(t.flagDisabled??m8e)())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??$pt).get(n);return o?Kpt(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 Gpt(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:qY()&&!process.env.VISA_VERIFY_WEB_URL?null:rl();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??m8e)())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??$pt,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=Z4e(e.url??"").toString(),c=p8e(e.amount)}catch(C){if(C instanceof L1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Hpt,l=t.contactPath??Fpt;try{await(0,xk.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,xk.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??Lpt,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=>Qs.emitTelemetry(C)),x=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:x,currency:u});let C;try{C=await h.review(y)}catch(I){throw await rY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await rY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${Y4e(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 E=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:E,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:E,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await rY({emitTelemetry:w,action:"pay",merchantHost:x,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 rY({emitTelemetry:w,action:"pay",merchantHost:x,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"?E:null});let U=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:E,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${U}`:`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,Dpt.createHash)("sha256").update(JSON.stringify([E,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:E,merchantHost:x,currency:u,submit:A});try{let I=await s.start({reviewId:E,fingerprint:C,run:async R=>{try{let U=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:E}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:E,success:U.success===!0}),U}catch(U){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:E,error:Ek(U instanceof Error?U.message:String(U))}),U}}});return Kpt(I,"authorize")}catch(I){if(I instanceof ok)return Be.warn("pay_merchant:approval_handoff_conflict",{reviewId:E}),{success:!1,action:"authorize",reviewId:E,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 Jpt(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:rl();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??m8e)())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:Z4e(e.url??"").toString(),c=p8e(e.ceiling??e.amount)}catch(A){if(A instanceof L1)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=p8e(e.perTransaction)}catch(A){if(A instanceof L1)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??Hpt,p=t.contactPath??Fpt;try{await(0,xk.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,xk.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??Lpt,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),x=t.emitTelemetry??(A=>Qs.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?Ek(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await qpt({emitTelemetry:x,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 E=v.registerFailed===!0;return E&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await qpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),E?{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 ${Y4e(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 Lft=require("node:crypto");var Uft=require("node:crypto");var jr={};Gi(jr,{BRAND:()=>I8r,DIRTY:()=>Mv,EMPTY_PATH:()=>s8r,INVALID:()=>ht,NEVER:()=>i3r,OK:()=>ia,ParseStatus:()=>ws,Schema:()=>Ut,ZodAny:()=>n2,ZodArray:()=>Z1,ZodBigInt:()=>zv,ZodBoolean:()=>Lv,ZodBranded:()=>Sk,ZodCatch:()=>Xv,ZodDate:()=>Hv,ZodDefault:()=>Zv,ZodDiscriminatedUnion:()=>oY,ZodEffects:()=>Yd,ZodEnum:()=>Jv,ZodError:()=>Uc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>aY,ZodIntersection:()=>Kv,ZodIssueCode:()=>ye,ZodLazy:()=>Wv,ZodLiteral:()=>Gv,ZodMap:()=>yA,ZodNaN:()=>bA,ZodNativeEnum:()=>Yv,ZodNever:()=>bp,ZodNull:()=>$v,ZodNullable:()=>Tm,ZodNumber:()=>Dv,ZodObject:()=>Mc,ZodOptional:()=>Gd,ZodParsedType:()=>Ce,ZodPipeline:()=>Tk,ZodPromise:()=>i2,ZodReadonly:()=>Qv,ZodRecord:()=>sY,ZodSchema:()=>Ut,ZodSet:()=>gA,ZodString:()=>r2,ZodSymbol:()=>mA,ZodTransformer:()=>Yd,ZodTuple:()=>Sm,ZodType:()=>Ut,ZodUndefined:()=>Fv,ZodUnion:()=>Vv,ZodUnknown:()=>Y1,ZodVoid:()=>hA,addIssueToContext:()=>Ae,any:()=>Xd,array:()=>ue,bigint:()=>k8r,boolean:()=>Zd,coerce:()=>Nu,custom:()=>nft,date:()=>B8r,datetimeRegex:()=>tft,defaultErrorMap:()=>G1,discriminatedUnion:()=>z8r,effect:()=>Y8r,enum:()=>Qd,function:()=>V8r,getErrorMap:()=>lA,getParsedType:()=>Am,instanceof:()=>C8r,intersection:()=>L8r,isAborted:()=>nY,isAsync:()=>pA,isDirty:()=>iY,isValid:()=>t2,late:()=>O8r,lazy:()=>K8r,literal:()=>W8r,makeIssue:()=>Ak,map:()=>F8r,nan:()=>R8r,nativeEnum:()=>G8r,never:()=>U8r,null:()=>_A,nullable:()=>X8r,number:()=>Ir,object:()=>fe,objectUtil:()=>h8e,oboolean:()=>n3r,onumber:()=>r3r,optional:()=>Z8r,ostring:()=>t3r,pipeline:()=>e3r,preprocess:()=>Q8r,promise:()=>J8r,quotelessJson:()=>n8r,record:()=>Yt,set:()=>$8r,setErrorMap:()=>o8r,strictObject:()=>D8r,string:()=>z,symbol:()=>N8r,transformer:()=>Y8r,tuple:()=>H8r,undefined:()=>j8r,union:()=>vA,unknown:()=>q8r,util:()=>Jt,void:()=>M8r});var Jt;(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})(Jt||(Jt={}));var h8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(h8e||(h8e={}));var Ce=Jt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Am=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=Jt.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"]),n8r=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Uc=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,Jt.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()}};Uc.create=e=>new Uc(e);var i8r=(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,Jt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Jt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Jt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Jt.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}"`:Jt.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,Jt.assertNever(e)}return{message:r}},G1=i8r;var Ypt=G1;function o8r(e){Ypt=e}function lA(){return Ypt}var Ak=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}},s8r=[];function Ae(e,t){let r=lA(),n=Ak({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===G1?void 0:G1].filter(i=>!!i)});e.common.issues.push(n)}var ws=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"}),Mv=e=>({status:"dirty",value:e}),ia=e=>({status:"valid",value:e}),nY=e=>e.status==="aborted",iY=e=>e.status==="dirty",t2=e=>e.status==="valid",pA=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 Jd=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}},Zpt=(e,t)=>{if(t2(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 Uc(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 Ut=class{get description(){return this._def.description}_getType(t){return Am(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Am(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ws,ctx:{common:t.parent.common,data:t.data,parsedType:Am(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(pA(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:Am(t)},i=this._parseSync({data:t,path:n.path,parent:n});return Zpt(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Am(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return t2(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=>t2(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:Am(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(pA(i)?i:Promise.resolve(i));return Zpt(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 Yd({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 Gd.create(this,this._def)}nullable(){return Tm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z1.create(this)}promise(){return i2.create(this,this._def)}or(t){return Vv.create([this,t],this._def)}and(t){return Kv.create(this,t,this._def)}transform(t){return new Yd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Zv({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new Sk({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Xv({...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 Tk.create(this,t)}readonly(){return Qv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},a8r=/^c[^\s-]{8,}$/i,c8r=/^[0-9a-z]+$/,u8r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d8r=/^[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,l8r=/^[a-z0-9_-]{21}$/i,p8r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,f8r=/^[-+]?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)?)??$/,m8r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h8r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y8e,y8r=/^(?:(?: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])$/,g8r=/^(?:(?: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])$/,b8r=/^(([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]))$/,_8r=/^(([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])$/,v8r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w8r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qpt="((\\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])))",x8r=new RegExp(`^${Qpt}$`);function eft(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 E8r(e){return new RegExp(`^${eft(e)}$`)}function tft(e){let t=`${Qpt}T${eft(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 A8r(e,t){return!!((t==="v4"||!t)&&y8r.test(e)||(t==="v6"||!t)&&b8r.test(e))}function S8r(e,t){if(!p8r.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 T8r(e,t){return!!((t==="v4"||!t)&&g8r.test(e)||(t==="v6"||!t)&&_8r.test(e))}var r2=class e extends Ut{_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 ws,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")m8r.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")y8e||(y8e=new RegExp(h8r,"u")),y8e.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")d8r.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")l8r.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")a8r.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")c8r.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")u8r.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"?tft(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"?x8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?E8r(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"?f8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?A8r(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"?S8r(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"?T8r(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"?v8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?w8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Jt.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}};r2.create=e=>new r2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function P8r(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 Dv=class e extends Ut{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 ws;for(let o of this._def.checks)o.kind==="int"?Jt.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"?P8r(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()):Jt.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"&&Jt.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)}};Dv.create=e=>new Dv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var zv=class e extends Ut{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 ws;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()):Jt.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 Lv=class extends Ut{_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 ia(t.data)}};Lv.create=e=>new Lv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Hv=class e extends Ut{_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 ws,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()):Jt.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}};Hv.create=e=>new Hv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var mA=class extends Ut{_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 ia(t.data)}};mA.create=e=>new mA({typeName:wt.ZodSymbol,...Bt(e)});var Fv=class extends Ut{_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 ia(t.data)}};Fv.create=e=>new Fv({typeName:wt.ZodUndefined,...Bt(e)});var $v=class extends Ut{_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 ia(t.data)}};$v.create=e=>new $v({typeName:wt.ZodNull,...Bt(e)});var n2=class extends Ut{constructor(){super(...arguments),this._any=!0}_parse(t){return ia(t.data)}};n2.create=e=>new n2({typeName:wt.ZodAny,...Bt(e)});var Y1=class extends Ut{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ia(t.data)}};Y1.create=e=>new Y1({typeName:wt.ZodUnknown,...Bt(e)});var bp=class extends Ut{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};bp.create=e=>new bp({typeName:wt.ZodNever,...Bt(e)});var hA=class extends Ut{_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 ia(t.data)}};hA.create=e=>new hA({typeName:wt.ZodVoid,...Bt(e)});var Z1=class e extends Ut{_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 Jd(r,s,r.path,a)))).then(s=>ws.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Jd(r,s,r.path,a)));return ws.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)}};Z1.create=(e,t)=>new Z1({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function fA(e){if(e instanceof Mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Gd.create(fA(n))}return new Mc({...e._def,shape:()=>t})}else return e instanceof Z1?new Z1({...e._def,type:fA(e.element)}):e instanceof Gd?Gd.create(fA(e.unwrap())):e instanceof Tm?Tm.create(fA(e.unwrap())):e instanceof Sm?Sm.create(e.items.map(t=>fA(t))):e}var Mc=class e extends Ut{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=Jt.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 bp&&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 Jd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof bp){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 Jd(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=>ws.mergeObjectSync(n,u)):ws.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 Jt.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 Jt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return fA(this)}partial(t){let r={};for(let n of Jt.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 Jt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Gd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return rft(Jt.objectKeys(this.shape))}};Mc.create=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.strictCreate=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strict",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.lazycreate=(e,t)=>new Mc({shape:e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});var Vv=class extends Ut{_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 Uc(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 Uc(c));return Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};Vv.create=(e,t)=>new Vv({options:e,typeName:wt.ZodUnion,...Bt(t)});var J1=e=>e instanceof Wv?J1(e.schema):e instanceof Yd?J1(e.innerType()):e instanceof Gv?[e.value]:e instanceof Jv?e.options:e instanceof Yv?Jt.objectValues(e.enum):e instanceof Zv?J1(e._def.innerType):e instanceof Fv?[void 0]:e instanceof $v?[null]:e instanceof Gd?[void 0,...J1(e.unwrap())]:e instanceof Tm?[null,...J1(e.unwrap())]:e instanceof Sk||e instanceof Qv?J1(e.unwrap()):e instanceof Xv?J1(e._def.innerType):[],oY=class e extends Ut{_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=J1(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 g8e(e,t){let r=Am(e),n=Am(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Jt.objectKeys(t),o=Jt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=g8e(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=g8e(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 Kv=class extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(nY(o)||nY(s))return ht;let a=g8e(o.value,s.value);return a.valid?((iY(o)||iY(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}))}};Kv.create=(e,t,r)=>new Kv({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Sm=class e extends Ut{_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 Jd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ws.mergeArray(r,s)):ws.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Sm.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Sm({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var sY=class e extends Ut{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 Jd(n,a,n.path,a)),value:s._parse(new Jd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ws.mergeObjectAsync(r,i):ws.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ut?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:r2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},yA=class extends Ut{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 Jd(n,a,n.path,[u,"key"])),value:o._parse(new Jd(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}}}};yA.create=(e,t,r)=>new yA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var gA=class e extends Ut{_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 Jd(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)}};gA.create=(e,t)=>new gA({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var aY=class e extends Ut{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 Ak({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lA(),G1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Ak({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lA(),G1].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 i2){let a=this;return ia(async function(...c){let u=new Uc([]),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 ia(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Uc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Uc([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:Sm.create(t).rest(Y1.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||Sm.create([]).rest(Y1.create()),returns:r||Y1.create(),typeName:wt.ZodFunction,...Bt(n)})}},Wv=class extends Ut{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})}};Wv.create=(e,t)=>new Wv({getter:e,typeName:wt.ZodLazy,...Bt(t)});var Gv=class extends Ut{_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}};Gv.create=(e,t)=>new Gv({value:e,typeName:wt.ZodLiteral,...Bt(t)});function rft(e,t){return new Jv({values:e,typeName:wt.ZodEnum,...Bt(t)})}var Jv=class e extends Ut{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Jt.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 ia(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})}};Jv.create=rft;var Yv=class extends Ut{_parse(t){let r=Jt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Jt.objectValues(r);return Ae(n,{expected:Jt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Jt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Jt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return ia(t.data)}get enum(){return this._def.values}};Yv.create=(e,t)=>new Yv({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var i2=class extends Ut{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 ia(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};i2.create=(e,t)=>new i2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Yd=class extends Ut{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"?Mv(c.value):r.value==="dirty"?Mv(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"?Mv(a.value):r.value==="dirty"?Mv(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(!t2(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=>t2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Jt.assertNever(i)}};Yd.create=(e,t,r)=>new Yd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Yd.createWithPreprocess=(e,t,r)=>new Yd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Gd=class extends Ut{_parse(t){return this._getType(t)===Ce.undefined?ia(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Gd.create=(e,t)=>new Gd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Tm=class extends Ut{_parse(t){return this._getType(t)===Ce.null?ia(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Tm.create=(e,t)=>new Tm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var Zv=class extends Ut{_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}};Zv.create=(e,t)=>new Zv({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var Xv=class extends Ut{_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 pA(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Uc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Uc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Xv.create=(e,t)=>new Xv({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var bA=class extends Ut{_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}}};bA.create=e=>new bA({typeName:wt.ZodNaN,...Bt(e)});var I8r=Symbol("zod_brand"),Sk=class extends Ut{_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}},Tk=class e extends Ut{_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(),Mv(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})}},Qv=class extends Ut{_parse(t){let r=this._def.innerType._parse(t),n=i=>(t2(i)&&(i.value=Object.freeze(i.value)),i);return pA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Qv.create=(e,t)=>new Qv({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function Xpt(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function nft(e,t={},r){return e?n2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=Xpt(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=Xpt(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):n2.create()}var O8r={object:Mc.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 C8r=(e,t={message:`Input not instance of ${e.name}`})=>nft(r=>r instanceof e,t),z=r2.create,Ir=Dv.create,R8r=bA.create,k8r=zv.create,Zd=Lv.create,B8r=Hv.create,N8r=mA.create,j8r=Fv.create,_A=$v.create,Xd=n2.create,q8r=Y1.create,U8r=bp.create,M8r=hA.create,ue=Z1.create,fe=Mc.create,D8r=Mc.strictCreate,vA=Vv.create,z8r=oY.create,L8r=Kv.create,H8r=Sm.create,Yt=sY.create,F8r=yA.create,$8r=gA.create,V8r=aY.create,K8r=Wv.create,W8r=Gv.create,Qd=Jv.create,G8r=Yv.create,J8r=i2.create,Y8r=Yd.create,Z8r=Gd.create,X8r=Tm.create,Q8r=Yd.createWithPreprocess,e3r=Tk.create,t3r=()=>z().optional(),r3r=()=>Ir().optional(),n3r=()=>Zd().optional(),Nu={string:(e=>r2.create({...e,coerce:!0})),number:(e=>Dv.create({...e,coerce:!0})),boolean:(e=>Lv.create({...e,coerce:!0})),bigint:(e=>zv.create({...e,coerce:!0})),date:(e=>Hv.create({...e,coerce:!0}))};var i3r=ht;var s3r=Qd(["enc","sig"]),a3r=Qd(["markdown","plain"]),c3r=Qd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),u3r=Qd(["error","info","warning"]),EA=Qd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),d3r=Qd(["completed","failed","pending"]),l3r=Qd(["digital","pickup","shipping"]),p3r=Qd(["fulfilled","partial","processing","removed"]),f3r=Qd(["across","each"]),b8e=Qd(["pickup","shipping"]),m3r=fe({config:Yt(z(),Xd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),h3r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:s3r.optional(),x:z().optional(),y:z().optional()}),y3r=fe({config:Yt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),g3r=fe({endpoint:z()}),b3r=fe({schema:z()}),ift=fe({endpoint:z(),schema:z()}),_3r=ift,v3r=ift,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),uo=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()}),_8e=uo,oft=fe({id:z()}),w3r=oft,x3r=oft,Pk=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()}),cY=fe({type:z()}),Ki=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),v8e=Ki,sft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),uY=fe({amount:Ir(),display_text:z().optional(),type:z()}),o2=fe({title:z().optional(),type:z(),url:z()}),X1=fe({code:z().optional(),content:z(),content_type:a3r.optional(),path:z().optional(),severity:c3r.optional(),type:u3r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),w8e=X1,AA=fe({id:z(),label:z().optional(),permalink_url:z()}),E3r=fe({amount:Ir(),display_text:z()}),A3r=fe({config:Yt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),x8e=fe({id:z(),quantity:Ir()}),S3r=x8e,T3r=x8e,P3r=x8e,I3r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),O3r=fe({billing_address:Pk.optional(),credential:cY.optional(),display:Yt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z()}),C3r=fe({checkout_mandate:z()}),R3r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),k3r=fe({analytics:Zd().optional(),marketing:Zd().optional(),preferences:Zd().optional(),sale_of_data:Zd().optional()});var B3r=k3r;var aft=fe({codes:ue(z()).optional()}),N3r=aft,j3r=fe({amount:Ir(),path:z()}),q3r=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:Pk.optional(),name:z().optional()}),U3r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:Nu.date().optional(),id:z(),latest_fulfillment_time:Nu.date().optional(),title:z(),totals:ue(uY)}),M3r=fe({description:z().optional(),fulfillable_on:vA([_A(),z()]).optional(),line_item_ids:ue(z()),type:b8e}),D3r=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:Pk.optional(),name:z().optional()}),z3r=fe({max:Ir().optional(),min:Ir().optional()}),Ik=fe({taxonomy:z().optional(),value:z()}),Ok=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),wA=fe({amount:Ir(),currency:z()}),Ck=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),L3r=fe({id:z().optional(),label:z()}),Rk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),cft=fe({available:Zd().optional(),status:z().optional()}),H3r=cft,uft=fe({type:z(),value:z()}),F3r=uft,$3r=fe({id:z(),match:z().optional()}),E8e=fe({id:z().optional(),label:z(),name:z()}),dft=E8e,lft=fe({links:ue(o2).optional(),name:z().optional()}),V3r=lft,pft=fe({unit:z(),value:Ir()});var K3r=pft,W3r=fe({cursor:z().optional(),limit:Ir().optional()}),G3r=fe({cursor:z().optional(),has_next_page:Zd(),total_count:Ir().optional()}),J3r=fe({handlers:ue(m3r).optional()}),Y3r=fe({a2a:g3r.optional(),embedded:b3r.optional(),mcp:_3r.optional(),rest:v3r.optional(),spec:z(),version:z()}),SA=fe({item:w3r,quantity:Ir()}),Z3r=fe({billing_address:Pk.optional(),credential:cY.optional(),display:Yt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z(),selected:Zd().optional()}),kk=fe({id:z().optional(),item:x3r,parent_id:z().optional(),quantity:Ir()}),dY=fe({instruments:ue(Z3r).optional()}),X3r=dY,Bk=dY,TA=dY,lY=dY,e4=fe({id:z(),item:sft,parent_id:z().optional(),quantity:Ir(),totals:ue(uY)}),s2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(E3r).optional()}),_p=fe({capabilities:Yt(z(),ue(A3r)),version:z()}),Q3r=fe({description:z().optional(),id:z(),line_items:ue(S3r).optional(),occurred_at:Nu.date(),status:d3r,totals:ue(uY).optional(),type:z()}),e9r=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(T3r),occurred_at:Nu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),t9r=fe({description:z().optional(),destination:Pk,fulfillable_on:z().optional(),id:z(),line_items:ue(P3r),method_type:l3r}),r9r=fe({id:z(),item:sft,parent_id:z().optional(),quantity:I3r,status:p3r,totals:ue(uY)}),e4n=fe({payment_data:O3r}),t4n=fe({ap2:C3r.optional()}),r4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,ap2:R3r.optional()}),A8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:B3r.optional()}),n9r=A8e,i9r=A8e,fft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional(),discounts:N3r.optional()}),o9r=fe({allocations:ue(j3r).optional(),amount:Ir(),automatic:Zd().optional(),code:z().optional(),eligibility:z().optional(),method:f3r.optional(),priority:Ir().optional(),provisional:Zd().optional(),title:z()}),mft=fe({id:z(),line_item_ids:ue(z()),options:ue(U3r).optional(),selected_option_id:vA([_A(),z()]).optional()}),s9r=fe({destinations:ue(D3r).optional(),groups:ue(mft).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:vA([_A(),z()]).optional(),type:b8e}),n4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),signals:Ki.optional()}),i4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),id:z(),line_items:ue(kk),signals:Ki.optional()}),o4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2).optional(),messages:ue(X1).optional(),signals:Ki.optional(),totals:ue(s2),ucp:_p}),a9r=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional()}),hft=a9r,s4n=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,cart_id:z().optional()}),S8e=fe({categories:ue(z()).optional(),price:z3r.optional()}),xA=fe({max:wA,min:wA}),T8e=fe({name:z(),values:ue(L3r)}),yft=fe({amount:Ir(),currency:z(),measure:pft,reference:K3r}),c9r=yft,a4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(dft).optional(),signals:v8e.optional()}),c4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),pagination:W3r.optional(),query:z().optional(),signals:v8e.optional()}),u9r=fe({capabilities:ue(y3r),services:Yt(z(),Y3r),version:z()}),u4n=fe({attribution:Yt(z(),z()).optional(),payment:X3r,signals:Ki.optional()}),gft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p}),d9r=fe({events:ue(e9r).optional(),expectations:ue(t9r).optional()}),bft=fe({attribution:Yt(z(),z()).optional(),buyer:A8e.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional()}),_ft=fe({attribution:Yt(z(),z()).optional(),buyer:i9r.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional()}),vft=fe({attribution:Yt(z(),z()).optional(),buyer:n9r.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p}),wft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),discounts:aft.optional()}),l9r=fe({applied:ue(o9r).optional(),codes:ue(z()).optional()}),p9r=fe({destinations:ue(q3r).optional(),groups:ue(mft).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:vA([_A(),z()]).optional(),type:b8e}),f9r=fe({available_methods:ue(M3r).optional(),methods:ue(s9r).optional()}),xft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),cart_id:z().optional()}),d4n=fe({attribution:Yt(z(),z()).optional(),context:_8e.optional(),filters:S8e.optional(),ids:ue(z()),signals:v8e.optional()}),m9r=fe({availability:cft.optional(),barcodes:ue(uft).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price:wA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(E8e).optional(),price:wA,rating:Rk.optional(),seller:lft.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:yft.optional(),url:z().optional(),inputs:ue($3r)}),Eft=fe({availability:H3r.optional(),barcodes:ue(F3r).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price:wA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(E8e).optional(),price:wA,rating:Rk.optional(),seller:V3r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:c9r.optional(),url:z().optional()}),h9r=fe({categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(T8e).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Eft)}),l4n=fe({payment:J3r.optional(),signing_keys:ue(h3r).optional(),ucp:u9r}),Aft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional()}),y9r=fe({adjustments:ue(Q3r).optional(),attribution:Yt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:d9r,id:z(),label:z().optional(),line_items:ue(r9r),messages:ue(X1).optional(),permalink_url:z(),totals:ue(s2),ucp:_p}),Sft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,discounts:l9r.optional()}),Tft=fe({methods:ue(p9r).optional()}),Pft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(kk),payment:lY.optional(),signals:Ki.optional(),fulfillment:Tft.optional()}),Ift=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(e4),links:ue(o2),messages:ue(X1).optional(),order:AA.optional(),payment:TA.optional(),signals:Ki.optional(),status:EA,totals:ue(s2),ucp:_p,fulfillment:f9r.optional()}),g9r=fe({categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),options:ue(T8e).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(m9r)}),b9r=fe({options:ue(T8e).optional(),selected:ue(dft).optional(),categories:ue(Ik).optional(),description:Ok,handle:z().optional(),id:z(),list_price_range:xA.optional(),media:ue(Ck).optional(),metadata:Yt(z(),Xd()).optional(),price_range:xA,rating:Rk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Eft)}),p4n=fe({messages:ue(w8e).optional(),pagination:G3r.optional(),products:ue(h9r),ucp:_p}),Oft=fe({attribution:Yt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(SA),payment:Bk.optional(),signals:Ki.optional(),fulfillment:Tft.optional()}),f4n=fe({messages:ue(w8e).optional(),products:ue(g9r),ucp:_p}),m4n=fe({messages:ue(w8e).optional(),product:b9r,ucp:_p});var b4n=cY.extend({token:jr.string().optional()}),_9r=jr.object({webhook_url:jr.string().url().optional()}),Cft=gft.extend(Ift.pick({fulfillment:!0}).shape).extend(Sft.pick({discounts:!0}).shape).extend(vft.pick({buyer:!0}).shape).extend({platform:_9r.optional()}),Rft=Aft.extend(Oft.pick({fulfillment:!0}).shape).extend(wft.pick({discounts:!0}).shape).extend(bft.pick({buyer:!0}).shape).extend(xft.pick({cart_id:!0}).shape),kft=hft.extend(Pft.pick({fulfillment:!0}).shape).extend(fft.pick({discounts:!0}).shape).extend(_ft.pick({buyer:!0}).shape);Dc();async function pY(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 fY(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 v9r=3e4,Bft=2*1024*1024,vp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function Nft(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 jft(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"?Rft:kft).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function w9r(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 qft(e,t,r,n){try{e[t](r,n)}catch{}}function x9r(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 mY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=Nft(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=Nft(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??v9r,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:jft(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:jft(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=fY(this.timeoutMs,this.signal),o=(0,Uft.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 pY(u,Bft,"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 vp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Bft)throw new vp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new vp("UCP MCP response is not valid JSON",void 0,u.status)}if(!w9r(l))throw new vp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new vp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new vp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new vp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new vp("UCP MCP response is missing result.structuredContent");if(!Cft.safeParse(x9r(p.structuredContent)).success)throw new vp("UCP checkout response failed schema validation");return qft(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw qft(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 Dft=require("node:crypto");Dc();var yY="2026-04-08",E9r="dev.ucp.shopping",A9r="dev.ucp.shopping.checkout",S9r=1024*1024,T9r=1e4,P9r="https://ucp.dev",Nk=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"),I9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Nk,schema:Nk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Nk.optional()}).passthrough(),O9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Nk,schema:Nk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),C9r=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(I9r)),capabilities:jr.record(jr.array(O9r)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function R9r(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!==P9r)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function Mft(e,t,r,n){try{e[t](r,n)}catch{}}async function k9r(e,t={}){let r=R9r(e,"UCP business URL"),n=fY(t.timeoutMs??T9r,t.signal),i=t.logger??Be,o=(0,Dft.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 pY(c,S9r,"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=C9r.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return Mft(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 Mft(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 B9r(e){if(e.ucp.version!==yY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[A9r]?.find(i=>i.version===yY);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[E9r]?.find(i=>i.version===yY&&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 zft(e,t={}){let r=await k9r(e,t);return{...r,endpoint:B9r(r.profile),version:yY}}var N9r="https://app.visacli.sh/.well-known/ucp";function j9r(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 q9r(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 P8e(e,t=new Set){if(Array.isArray(e))for(let r of e)P8e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?q9r(n,t):P8e(n,t);return t}function U9r(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=P8e(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 M9r(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 D9r(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 Hft(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??zft)(e.business),i=await(t.getCheckout??(async(u,d)=>await new mY({endpoint:u.endpoint,platformProfileUrl:j9r(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??N9r)}).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=M9r(i),a=U9r(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Lft.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:D9r(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>."}}s4();function z9r(){return ju()}var Qs=new Vk(()=>Uu.getSessionToken()),L9r="4.1.0-rc.29",Z4n=["","","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(`
20774
20774
  `);function H9r(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=BA(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Z8e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=kA();if(r.headless)return Be.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[z9r(),rl()].filter(s=>!!s).map(s=>O3e(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=rB(i);return o?((0,$ft.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 "${bY.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function F9r(){let e=!1,t;try{let n=Vft.join(bY.homedir(),".claude","settings.json");if(gY.existsSync(n)){let i=JSON.parse(gY.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=gdt(o)}}catch{}let r=AJ();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function $9r(e){let t=await Qs.getStatus(e);return t.hud=F9r(),!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=L9r,t}async function V9r(e,t){return await Qs.feedback(e.message,e.transaction_id,t)}async function K9r(e){let t=await _dt({api:Qs,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 I8e=new Set(["auth.serverUrl"]);function jk(){return Object.keys(OA).filter(e=>!I8e.has(e)).sort()}function Kft(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:jk()}}async function W9r(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(I8e.has(e.key))return Be.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Kft(e.key,"set");Be.info("config:set",{key:e.key});try{let t=J8e(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 Im?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Im?`Unknown setting "${e.key}". MCP-settable keys: ${jk().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:jk()}}}async function G9r(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(I8e.has(e.key))return Be.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Kft(e.key,"unset");Be.info("config:unset",{key:e.key});try{let t=Y8e(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 Im?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Im?`Unknown setting "${e.key}". MCP-settable keys: ${jk().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:jk()}}}async function J9r(e=rl()){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{challenge:t,confirmCode:r,agentPkX:n,walletPkHex:i}=rk(),o=Kk(e),s=`${o}?cli=${t}&cliPk=${n}${i?`&walletPk=${i}`:""}`;Be.info("agent:enroll_open",{url:o});let a=H9r(s),c="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",u=`CONFIRMATION CODE: ${r} \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.`,d='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 a.opened?{success:!0,opened:!0,browserUrl:a.url,confirmCode:r,message:`Opened the Visa Verified Agent enrollment in your browser (${c}). ${u} ${d} 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:a.url??s,confirmCode:r,message:`Open this URL in a browser to enroll your agent (${c}): ${a.url??s} \u2014 ${u} ${d}`}}async function Y9r(e=rl()){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 nk(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 Fft(){if(await Uu.clearAll(),!!S3e())try{await T3e()}catch(e){Be.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function Z9r(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 Fft(),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 Qs.logout(void 0,t)}catch{}return await Fft(),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 X9r(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(Bv(),mk)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{CardRequiredError:r}=await Promise.resolve().then(()=>(MA(),_9e));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 Q9r(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Bv(),mk));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function exr(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(()=>(Bv(),mk)),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 txr(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(Bv(),mk)),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 zo=class{static async subwayRegister(t){return X9r(t||{})}static async subwayFind(t){return Q9r(t||{})}static async subwaySend(t){return exr(t||{})}static async subwayInbox(t){return txr(t||{})}static async getStatus(t){return $9r(t)}static async feedback(t,r){return V9r(t,r)}static async configList(t){return K9r(t||{})}static async configSet(t){return W9r(t||{})}static async configUnset(t){return G9r(t||{})}static async reset(t,r){return Z9r(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?J9r():n==="claim"?Y9r():{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 Gpt(t)}static async ucpCheckoutHandoff(t,r){return _m("ucp_checkout_handoff")&&(await tA(),_m("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."}:Hft(t)}static async payMerchantStatus(t={},r){return Wpt(t)}static async startCardMandate(t={},r){return Jpt(t)}static async submitFeedback(t,r,n){Be.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await Qs.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 Qs.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 Wft(e){return e==="pay_merchant"}Dc();var Gft="VISA_V4_WALLET_EXPERIMENT",rxr=null;function nxr(){return rxr??!0}var ixr=new Set(["1","true","on","yes"]),oxr=new Set(["0","false","off","no"]),Jft=!1;function O8e(e,t){return Jft||(Jft=!0,Be.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function Zft(){let e=(process.env[Gft]??"").trim().toLowerCase();if(ixr.has(e))return O8e(!0,"env-on");if(oxr.has(e))return O8e(!1,"env-off");e!==""&&Be.warn("wallet-experiment:unrecognized-env-value",{env:Gft,fallback:"bundled-runtime"});let t=nxr();return O8e(t,t?"bundled-runtime":"runtime-unavailable")}var Yft=null;function Xft(){return Yft??=_J(),Yft}var sxr={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 axr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...sxr},required:[...e.inputSchema.required||[],"user_context"]}}}function Qft(){return Zft()?Xft().WALLET_TOOL_DEFS.map(axr):[]}function emt(e){return Zft()?Xft().WALLET_TOOL_NAMES.includes(e):!1}async function tmt(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=cxr(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 cxr(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}}Dc();var C8e=["pay_merchant"],uxr={pay_merchant:"merchant checkout"};function dxr(e){return uxr[e]||e}var rmt={};function nmt(e){let t=rmt[e]??0;return rmt[e]=t+1,t}function imt(e,t,r){return C8e.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${dxr(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 vY=Ze(require("crypto")),wY=Ze(require("tty")),t4=Ze(require("fs")),k8e=Ze(require("os")),_Y=Ze(require("path"));MY();RA();var lxr=new Set(["connect","disconnect","connections"]);function pxr(e){return e!==void 0&&lxr.has(e)}function fxr(e){return/-rc\.|-beta\./.test(e)}function R8e(e){return vY.createHash("sha256").update(e.trim()).digest("hex")}function omt(e){return Om==="SKIP"?!0:vY.timingSafeEqual(Buffer.from(R8e(e)),Buffer.from(Om))}function mxr(){return _Y.join(k8e.homedir(),".visa-mcp","agent-credential.json")}function hxr(){let e=process.env.VISA_V4_HOME||_Y.join(k8e.homedir(),".visa-v4");return _Y.join(e,"turnkey.json")}function yxr(){try{let e=t4.readFileSync(mxr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=t4.readFileSync(hxr(),"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 gxr(){try{let e=t4.openSync("/dev/tty","r+"),t=new wY.ReadStream(e),r=new wY.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{t4.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 bxr(e){return new Promise((t,r)=>{let n;try{n=gxr()}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===`
20775
20775
  `?(o.write(`
20776
20776
  `),a(),t(c)):d===""?(o.write(`