@visa/cli 4.1.0-rc.56 → 4.1.0-rc.57

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,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";var Kgt=Object.create;var lB=Object.defineProperty;var Wgt=Object.getOwnPropertyDescriptor;var Ggt=Object.getOwnPropertyNames;var Jgt=Object.getPrototypeOf,Ygt=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}},Ai=(e,t)=>{for(var r in t)lB(e,r,{get:t[r],enumerable:!0})},zAe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ggt(t))!Ygt.call(e,i)&&i!==r&&lB(e,i,{get:()=>t[i],enumerable:!(n=Wgt(t,i))||n.enumerable});return e};var Me=(e,t,r)=>(r=e!=null?Kgt(Jgt(e)):{},zAe(t||!e||!e.__esModule?lB(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>zAe(lB({},"__esModule",{value:!0}),e);async function HAe(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 FAe=P(()=>{"use strict"});var pB,VAe=P(()=>{"use strict";pB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}}});function KAe(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&&$Ae[r]?$Ae[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 $Ae,WAe=P(()=>{"use strict";$Ae={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 JAe(e,t){let r=GAe(e),n=GAe(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:Xgt(r.pre,n.pre)>0}function GAe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Zgt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Xgt(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){if(o>=r.length)return-1;if(o>=n.length)return 1;let s=r[o],a=n[o],c=/^\d+$/.test(s),u=/^\d+$/.test(a);if(c&&u){let d=Number(s)-Number(a);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(s<a)return-1;if(s>a)return 1}}return 0}var Zgt,YAe=P(()=>{"use strict";Zgt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function fB(){return!!(ZAe(process.env.VISA_CLI_NO_UPDATE_CHECK)||ZAe(process.env.CI)||process.env.NODE_ENV==="test")}function ZAe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var FX=P(()=>{"use strict"});var mB,XAe,QAe,VX,VS,e9e=P(()=>{"use strict";mB=Me(require("fs")),XAe=Me(require("path")),QAe=Me(require("os")),VX=XAe.join(QAe.homedir(),".visa-mcp"),VS=class{static ensureConfigDir(){mB.existsSync(VX)||mB.mkdirSync(VX,{recursive:!0,mode:448})}static getConfigDir(){return VX}}});function ebt(){Ya.existsSync(KX)||Ya.mkdirSync(KX,{recursive:!0,mode:448})}function tbt(){if(!$X){if(ebt(),Ya.existsSync($S)&&Ya.statSync($S).size>Qgt){let t=$S+".1";Ya.existsSync(t)&&Ya.unlinkSync(t),Ya.renameSync($S,t)}$X=Ya.createWriteStream($S,{flags:"a"})}return $X}function rbt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function hB(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
- `;rbt(e)&&process.stderr.write(i),tbt().write(i)}var Ya,WX,t9e,KX,$S,Qgt,$X,Ne,Sl=P(()=>{"use strict";Ya=Me(require("fs")),WX=Me(require("path")),t9e=Me(require("os")),KX=WX.join(t9e.homedir(),".visa-mcp"),$S=WX.join(KX,"mcp-server.log"),Qgt=5*1024*1024,$X=null;Ne={debug:(...e)=>hB("DEBUG",...e),info:(...e)=>hB("INFO",...e),warn:(...e)=>hB("WARN",...e),error:(...e)=>hB("ERROR",...e)}});var yB=g((pCr,nbt)=>{nbt.exports={name:"@visa/cli",version:"4.1.0-rc.56",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0","@ucp-js/sdk":"0.4.1",commander:"^12.1.0",zod:"^3.23.0"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1","playwright-core":"^1.48.2"},devDependencies:{"@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.65.0","@typescript-eslint/parser":"^8.65.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function r9e(e){let t=n9e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function gB(){return i9e.join(VS.getConfigDir(),ibt)}function o9e(e){if((0,JX.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function sbt(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 o9e(i)}function abt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,JX.isIP)(t);return r===4?o9e(t):r===6?t==="::1"||sbt(t):!1}function GX(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:"&&abt(r.hostname)))throw new Error(`${t} ${obt}`)}function bB(){let e=gB();if(!Dh.existsSync(e))return{};try{let t=Dh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Ne.warn("settings:corrupt",{path:r9e(e),reason:"not_object"}),{}):r}catch(t){return Ne.warn("settings:corrupt",{path:r9e(e),error:t?.message||String(t)}),{}}}function s9e(e){VS.ensureConfigDir();let t=gB(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
3
+ `;rbt(e)&&process.stderr.write(i),tbt().write(i)}var Ya,WX,t9e,KX,$S,Qgt,$X,Ne,Sl=P(()=>{"use strict";Ya=Me(require("fs")),WX=Me(require("path")),t9e=Me(require("os")),KX=WX.join(t9e.homedir(),".visa-mcp"),$S=WX.join(KX,"mcp-server.log"),Qgt=5*1024*1024,$X=null;Ne={debug:(...e)=>hB("DEBUG",...e),info:(...e)=>hB("INFO",...e),warn:(...e)=>hB("WARN",...e),error:(...e)=>hB("ERROR",...e)}});var yB=g((pCr,nbt)=>{nbt.exports={name:"@visa/cli",version:"4.1.0-rc.57",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0","@ucp-js/sdk":"0.4.1",commander:"^12.1.0",zod:"^3.23.0"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1","playwright-core":"^1.48.2"},devDependencies:{"@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.65.0","@typescript-eslint/parser":"^8.65.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function r9e(e){let t=n9e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function gB(){return i9e.join(VS.getConfigDir(),ibt)}function o9e(e){if((0,JX.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function sbt(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 o9e(i)}function abt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,JX.isIP)(t);return r===4?o9e(t):r===6?t==="::1"||sbt(t):!1}function GX(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:"&&abt(r.hostname)))throw new Error(`${t} ${obt}`)}function bB(){let e=gB();if(!Dh.existsSync(e))return{};try{let t=Dh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Ne.warn("settings:corrupt",{path:r9e(e),reason:"not_object"}),{}):r}catch(t){return Ne.warn("settings:corrupt",{path:r9e(e),error:t?.message||String(t)}),{}}}function s9e(e){VS.ensureConfigDir();let t=gB(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
4
4
  `;Dh.writeFileSync(r,n,{mode:384}),Dh.renameSync(r,t)}function YX(e){let t=bB()[e];return typeof t=="string"?t:void 0}function ZX(e){let t=bB()[e];return typeof t=="boolean"?t:void 0}function a9e(e,t){let r=KS[e];if(!r)throw new c0(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=bB();return i[e]=n,s9e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:gB()}}function c9e(e){let t=KS[e];if(!t)throw new c0(e);let r=bB(),n=e in r;return n&&(delete r[e],s9e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:gB()}}function dbt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function lbt(){try{let e=yB();return dbt(e.version)}catch{return!1}}function pbt(e){return e.envVar!==void 0&&e.envVar!==""?(GX(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(GX(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?ubt:cbt}function rd(){return pbt({envVar:process.env.VISA_AUTH_URL,settingValue:YX("auth.serverUrl"),isPrerelease:lbt()})}function u9e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":ZX("ui.suppressBrowser")??!1}var Dh,JX,n9e,i9e,ibt,obt,KS,c0,cbt,ubt,m4=P(()=>{"use strict";Dh=Me(require("fs")),JX=require("node:net"),n9e=Me(require("os")),i9e=Me(require("path"));e9e();Sl();ibt="settings.json",obt="must use https unless it points at localhost/loopback for local development";KS={"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");GX(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};c0=class extends Error{constructor(t){let r=Object.keys(KS).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};cbt="https://auth.visacli.sh",ubt="https://auth-visa-code-preview.up.railway.app"});function mbt(e,t){let r=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return r?new Error(r):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function h4(e){return typeof e=="string"?e.trim():""}function ybt(e){let t=e&&typeof e=="object"?e:{},r=h4(t.error)||h4(t.message);if(!r)return hbt;let n=h4(t.error_code),i=[["surface",h4(t.disabled_surface)],["flag",h4(t.flag)],["correlation_id",h4(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 gbt(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?fbt.test(n)?(r.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."),r.push("Use the Visa Key with X-Api-Key on the /v2/harness/* surface.")):(r.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>)."),r.push("Create a new Visa Key with: visa-cli keys create <app-name>")):r.push("Ask your agent to call `enroll_agent` to connect this device."),t===!1&&r.push("Complete enrollment in a normal terminal, then restart the MCP client."),r.join(`
5
- `)}var _B,fbt,hbt,y4,XX=P(()=>{"use strict";FAe();VAe();WAe();YAe();FX();m4();_B="4.1.0-rc.56",fbt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;hbt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";y4=class{constructor(t){this.getSessionToken=t;this.baseUrl=rd()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!fB()){let n=t.headers.get("X-Latest-Version");n&&JAe(n,_B)&&(this.lastSignals.updateAvailable={currentVersion:_B,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return _B}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new pB(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(ybt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(gbt());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 HAe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":_B,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(KAe(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),mbt(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}}});function QX(e=d9e){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function l9e(e=d9e){return/-(?:rc|alpha|beta)\./i.test(e)}function eQ(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Lh(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?eQ(t):l9e()?_bt:bbt}function p9e(e){return`${eQ(e)}${vbt}`}function wbt(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||l9e()}function tQ(e,t=process.env){if(!e||!wbt(t))return e;try{let r=new URL(Lh(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function f9e(e,t=fetch){let r=`${eQ(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var d9e,bbt,_bt,vbt,vB=P(()=>{"use strict";d9e="4.1.0-rc.56",bbt="https://app.visacli.sh",_bt="https://web-visa-code-preview.up.railway.app",vbt="/agent/enroll"});var u0,rQ=P(()=>{"use strict";u0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function b9e(e){return`${e}-${y9e.randomBytes(24).toString("base64url")}`}function _9e(e=process.env){return e.NODE_ENV==="test"||e[g9e]==="true"}function zh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&_9e(e)}function wB(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&_9e(e)}function nQ(){return`Set ${g9e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function v9e(){return m9e??=b9e("mock-session"),m9e}function w9e(e=process.env){return e.NODE_ENV==="test"?u0:(h9e??=b9e("mock-rc"),h9e)}var y9e,g9e,m9e,h9e,EB=P(()=>{"use strict";y9e=Me(require("crypto"));rQ();g9e="VISA_ALLOW_INSECURE_MOCKS"});function Abt(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
5
+ `)}var _B,fbt,hbt,y4,XX=P(()=>{"use strict";FAe();VAe();WAe();YAe();FX();m4();_B="4.1.0-rc.57",fbt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;hbt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";y4=class{constructor(t){this.getSessionToken=t;this.baseUrl=rd()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!fB()){let n=t.headers.get("X-Latest-Version");n&&JAe(n,_B)&&(this.lastSignals.updateAvailable={currentVersion:_B,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return _B}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new pB(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(ybt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(gbt());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 HAe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":_B,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(KAe(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),mbt(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}}});function QX(e=d9e){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function l9e(e=d9e){return/-(?:rc|alpha|beta)\./i.test(e)}function eQ(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Lh(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?eQ(t):l9e()?_bt:bbt}function p9e(e){return`${eQ(e)}${vbt}`}function wbt(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||l9e()}function tQ(e,t=process.env){if(!e||!wbt(t))return e;try{let r=new URL(Lh(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function f9e(e,t=fetch){let r=`${eQ(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var d9e,bbt,_bt,vbt,vB=P(()=>{"use strict";d9e="4.1.0-rc.57",bbt="https://app.visacli.sh",_bt="https://web-visa-code-preview.up.railway.app",vbt="/agent/enroll"});var u0,rQ=P(()=>{"use strict";u0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function b9e(e){return`${e}-${y9e.randomBytes(24).toString("base64url")}`}function _9e(e=process.env){return e.NODE_ENV==="test"||e[g9e]==="true"}function zh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&_9e(e)}function wB(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&_9e(e)}function nQ(){return`Set ${g9e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function v9e(){return m9e??=b9e("mock-session"),m9e}function w9e(e=process.env){return e.NODE_ENV==="test"?u0:(h9e??=b9e("mock-rc"),h9e)}var y9e,g9e,m9e,h9e,EB=P(()=>{"use strict";y9e=Me(require("crypto"));rQ();g9e="VISA_ALLOW_INSECURE_MOCKS"});function Abt(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
6
6
  `)}function uQ(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=Abt(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function Vh(){return process.platform!=="darwin"?Promise.resolve(!1):(E9e??=(async()=>{try{return await Tl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return uQ(e)}})(),E9e)}async function xbt(){if(!await Vh())return null;try{let{stdout:e}=await Tl("security",["find-generic-password","-s",nd,"-a",Hh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(uQ(e))throw new xB("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 Sbt(e){if(!await Vh())return!1;try{try{await Tl("security",["delete-generic-password","-s",nd,"-a",Hh],{timeout:5e3})}catch{}return await Tl("security",["add-generic-password","-s",nd,"-a",Hh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Tbt(){if(await Vh())try{await Tl("security",["delete-generic-password","-s",nd,"-a",Hh],{timeout:5e3})}catch{}}async function Ibt(){if(!dQ())return null;try{let{stdout:e}=await Tl("secret-tool",["lookup","service",nd,"account",Hh],{timeout:5e3});return e.trim()||null}catch{return null}}async function Pbt(e){if(!dQ())return!1;try{let t=(0,SB.execFile)("secret-tool",["store","--label",`${nd} ${Hh}`,"service",nd,"account",Hh]);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"))},Ebt))]),!0):!1}catch{return!1}}async function Obt(){if(dQ())try{await Tl("secret-tool",["clear","service",nd,"account",Hh],{timeout:5e3})}catch{}}function dQ(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Cbt(){if(!await Vh())return null;try{let{stdout:e}=await Tl("security",["find-generic-password","-s",nd,"-a",AB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function kbt(e){if(await Vh())try{try{await Tl("security",["delete-generic-password","-s",nd,"-a",AB],{timeout:5e3})}catch{}await Tl("security",["add-generic-password","-s",nd,"-a",AB,"-w",e],{timeout:5e3})}catch{}}async function Rbt(){if(await Vh())try{await Tl("security",["delete-generic-password","-s",nd,"-a",AB],{timeout:5e3})}catch{}}function oQ(){try{return Fh.readFileSync(WS,"utf-8").trim()||null}catch(e){if(uQ(e))throw new xB(`Unable to read Visa CLI credentials from ${WS}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function x9e(e){Fh.mkdirSync(cQ,{recursive:!0,mode:448}),Fh.writeFileSync(WS,e,{mode:384}),process.platform==="win32"&&Nbt(WS)}function sQ(){try{Fh.unlinkSync(WS)}catch{}}function Nbt(e){try{let t=TB.userInfo().username;(0,SB.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 iQ(){switch(process.platform){case"darwin":return{get:xbt,store:Sbt,delete:Tbt};case"linux":return{get:Ibt,store:Pbt,delete:Obt};default:return{get:async()=>oQ(),store:async e=>{try{return x9e(e),!0}catch{return!1}},delete:async()=>sQ(),storesInSessionFile:!0}}}var SB,A9e,Fh,TB,aQ,Tl,cQ,WS,nd,Hh,AB,Ebt,xB,E9e,Za,g4=P(()=>{"use strict";SB=require("child_process"),A9e=require("util"),Fh=Me(require("fs")),TB=Me(require("os")),aQ=Me(require("path"));EB();Tl=(0,A9e.promisify)(SB.execFile),cQ=aQ.join(TB.homedir(),".visa-mcp"),WS=aQ.join(cQ,"session-token"),nd="visa-cli",Hh="session-token",AB="rc-access",Ebt=5e3,xB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};E9e=null;Za=class{static async getSessionToken(){if(zh())return Promise.resolve(v9e());let t=iQ(),r=await t.get();if(r)return r;let n=oQ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(zh())return;let r=iQ();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||sQ();return}await r.delete()}if(x9e(t),oQ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${cQ} is writable.`))}static async getRcAccessToken(){return zh()?w9e():Cbt()}static async saveRcAccessToken(t){zh()||await kbt(t)}static async deleteSessionToken(){if(zh())return;await iQ().delete(),sQ()}static async clearAll(){await this.deleteSessionToken(),await Rbt()}}});function GS(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 Fbt(e){let r=e.length+4;return[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(r)}\u2518`].join(`
7
7
  `)}function JS(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 V9e(e,t){let r=JS(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 $9e(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 K9e(e,t=process.platform){let r=JS(e);return r?$9e(r,t):null}function H9e(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function YS(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=JS(e),s=t.spawn??((u,d,l)=>{(0,F9e.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 Fbt(o??e).split(`
8
8
  `))r(` ${u}`);if(r(""),!o){r(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),r(" Open the URL above manually to continue."),r("");return}let a=GS(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=$9e(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?H9e(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){H9e(r,l instanceof Error?l:new Error(String(l))),u()}})}var F9e,lQ=P(()=>{"use strict";F9e=require("child_process")});function u2t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Txe(e,t,r=""){let n=u2t(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 exe(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 d2t(e,t){Txe(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 AQ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function hQ(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function l2t(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 m2t(e,t=!1){return t?{h:Number(e&CB),l:Number(e>>txe&CB)}:{h:Number(e>>txe&CB)|0,l:Number(e&CB)|0}}function h2t(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}=m2t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function p0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function I2t(){return o2t.randomSecretKey()}function p_(e){return e2t(e)}function Pxe(){let e=I2t();return{secretKey:e,publicKey:p_(e)}}function Oxe(e){if(e.length!==oxe)throw new Error(`Ed25519 seed must be ${oxe} bytes, got ${e.length}`);return{secretKey:e,publicKey:p_(e)}}function A4(e,t){return n2t(t,e)}function P2t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function O2t(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 DB(e){return P2t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function kxe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return O2t(r)}function C2t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function f_(e){let t=p_(e);return{kty:"OKP",crv:"Ed25519",x:DB(t),d:DB(e)}}function Yh(e){return{kty:"OKP",crv:"Ed25519",x:DB(e)}}function x4(e){if(C2t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return kxe(e.d)}function axe(e,t){return e<t?-1:e>t?1:0}function gQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sr(e){if(typeof e!="string"||!N2t.test(e))return!1;try{let t=kxe(e);return t.byteLength===32&&DB(t)===e}catch{return!1}}function bQ(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function L2t(e,t){if(typeof t!="string"||!R2t.test(t))throw new Error(`${e} must be a UUID`)}function ZS(e,t){return L2t(e,t),t.toLowerCase()}function cxe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=j2t.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function NB(e,t,r=!1){if(typeof t!="string"||!B2t.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>M2t)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function z2t(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>U2t)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function uxe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Rxe.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>q2t)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function H2t(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(Rxe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function _Q(e,t){return typeof e=="string"&&t.includes(e)}function F2t(e){if(!gQ(e))throw new Error("agent authority grant must be an object");if(bQ("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==v4)throw new Error("grant.v must be 2");let t=ZS("grantId",e.grantId),r=ZS("agentId",e.agentId),n=z2t("version",e.version),i=ZS("budgetEpochId",e.budgetEpochId);if(!_Q(e.budgetEpochMode,k2t))throw new Error("budgetEpochMode must be new or continue");if(!_Q(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==yQ)throw new Error(`valuationPolicy must be '${yQ}'`);let o=NB("totalMicros",e.totalMicros),s=NB("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!gQ(l))throw new Error("grant scope must be an object");if(bQ("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!_Q(l.scope,Gh))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:NB("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:NB("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=H2t("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>sxe)throw new Error(`payeeConstraints must contain between 1 and ${sxe} entries`);if(c=e.payeeConstraints.map(p=>{if(!gQ(p))throw new Error("payee constraint must be an object");if(bQ("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:uxe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=uxe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!D2t.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=cxe("effectiveAt",e.effectiveAt),d=cxe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&ZS("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:v4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:yQ,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>axe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>axe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:ZS("supersedesGrantId",e.supersedesGrantId)}:{}}}function Uxe(e,t){return e<t?-1:e>t?1:0}function id(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Il(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function X2t(e){if(typeof e!="string")throw new Error("displayName must be a string");if(HB.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>K2t)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function Q2t(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(HB.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!$2t.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function BB(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(HB.test(t)||jxe.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function e_t(e){if(!id(e))throw new Error("runtime context v2 must be an object");Il("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=BB("runtime",e.runtime,G2t),r=BB("contextLabel",e.contextLabel,J2t),n=e.cliVersion===void 0?void 0:BB("cliVersion",e.cliVersion,Y2t),i=e.platform===void 0?void 0:BB("platform",e.platform,Z2t);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function RQ(e){if(typeof e!="string"||!Bxe.test(e))throw new Error("pairingId must be a server-generated pairing id")}function FB(e){if(e!==Rt)throw new Error("protocolVersion must be 2")}function Jh(e,t){if(typeof t!="string"||!W2t.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function wo(e,t){if(!Sr(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function Mxe(e){if(typeof e!="string"||!t_t.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function r_t(e){if(typeof e!="string"||!LB.includes(e))throw new Error(`capability must be one of ${LB.join(", ")}`)}function n_t(e){if(typeof e!="string"||!Gh.includes(e))throw new Error(`rail must be one of ${Gh.join(", ")}`)}function pxe(e,t){if(typeof t!="string"||t.length===0||t.length>lxe||HB.test(t)||jxe.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>lxe)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function qxe(){return QS.default.randomBytes(32).toString("base64url")}function Dxe(e){if(!Sr(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return tT(e)}function i_t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function o_t(e){let t=i_t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function VB(){return QS.default.randomBytes(32).toString("base64url")}function f0(e){if(!Sr(e))throw new Error("claim token must be 32 unpadded base64url bytes");return tT(`visa-agent-pairing-claim-token:v1:${e}`)}function $B(e,t){f0(t);let r=QS.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<V2t;i+=1)n+=kQ[r[i]&Nxe];return o_t(n)}function Lxe(e){if(!id(e))throw new Error("pairing terms v2 must be an object");if(Il("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==v4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!Bxe.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!dxe.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!Sr(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!dxe.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=X2t(e.displayName),i=e.dotVisaAddress===void 0?void 0:Q2t(e.dotVisaAddress);if(e.authority===null){if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:v4})}if(!id(e.authority))throw new Error("pairing authority must be an object or null");if(Il("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>Gh.length)throw new Error(`pairing authority scopes must contain between 1 and ${Gh.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!id(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(Il("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!Gh.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Sr(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=F2t({v:v4,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:v4})}function s_t(e){return tT(`visa-agent-pairing-terms:v2:${Lxe(e)}`)}function NQ(e){if(!id(e))throw new Error("pairing claim v2 must be an object");Il("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),FB(e.protocolVersion),RQ(e.pairingId),Jh("agentId",e.agentId),wo("serverNonce",e.serverNonce),wo("claimTokenHash",e.claimTokenHash),wo("identityKeyJkt",e.identityKeyJkt);let t=e_t(e.runtime);return KB("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function zxe(e){if(!id(e))throw new Error("pairing activation v2 must be an object");return Il("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),FB(e.protocolVersion),RQ(e.pairingId),Jh("agentId",e.agentId),Jh("ownerPublicId",e.ownerPublicId),wo("claimTokenHash",e.claimTokenHash),wo("identityKeyJkt",e.identityKeyJkt),wo("ceremonyHash",e.ceremonyHash),wo("deliveryArtifactHash",e.deliveryArtifactHash),KB("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function Hxe(e){if(!id(e))throw new Error("capability attach claim v2 must be an object");return Il("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),FB(e.protocolVersion),Mxe(e.attachId),Jh("agentId",e.agentId),r_t(e.capability),wo("serverNonce",e.serverNonce),wo("claimTokenHash",e.claimTokenHash),wo("identityKeyJkt",e.identityKeyJkt),KB("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function BQ(e){if(!id(e))throw new Error("capability attach activation v2 must be an object");return Il("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),FB(e.protocolVersion),Mxe(e.attachId),Jh("agentId",e.agentId),Jh("ownerPublicId",e.ownerPublicId),wo("identityKeyJkt",e.identityKeyJkt),wo("claimTokenHash",e.claimTokenHash),wo("grantHash",e.grantHash),wo("ceremonyHash",e.ceremonyHash),wo("deliveryArtifactHash",e.deliveryArtifactHash),n_t(e.rail),KB("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function eT(e){if(!id(e))throw new Error("pairing delivery artifact v2 must be an object");if(Il("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==Rt)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(RQ(e.pairingId),Jh("agentId",e.agentId),Jh("ownerPublicId",e.ownerPublicId),wo("ceremonyHash",e.ceremonyHash),!id(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Il("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),wo("identityKey.jkt",e.identityKey.jkt),!id(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Il("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");wo("identityKey.publicJwk.x",t.x);let r=tT(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!id(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let n=Lxe(e.terms);if(s_t(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=pxe("issuer",e.issuer),o=pxe("activationAudience",e.activationAudience);return xQ({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(n),v:Rt})}function Fxe(e){return tT(`visa-agent-pairing-delivery-artifact:v2:${eT(e)}`)}function tT(e){return QS.default.createHash("sha256").update(e,"utf8").digest("base64url")}function KB(e,t){return`${e}
@@ -33,7 +33,7 @@ ${e.nonce}`;return i6t.encode(r)}function a6t(e,t,r,n,i,o,s){return s6t({message
33
33
  `)?a:a+`
34
34
  `}function Pvt(e){for(let t of e.split(`
35
35
  `)){if(t.trim()===""||gj(t)>0)continue;let r=t.trim();if(!(r.startsWith("#")||r==="---"||r==="..."||r.startsWith("- "))&&!/^[^\s:#][^:]*:(\s|$)/.test(r))return!1}return!0}function mee(e,t){return e?e.command===t.command&&Array.isArray(e.args)&&e.args.length===t.args.length&&t.args.every((r,n)=>e.args[n]===r):!1}function ITe(e,t,r=hee()){let n=e.configFormat??"json";try{let i=od.existsSync(t),o=i?od.readFileSync(t,"utf-8"):"",s;if(n==="toml"){if(mee(Evt(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=Avt(o,"visa-cli",r)}else if(n==="yaml"){if(i&&!Pvt(o))return{status:"error",configPath:t,error:`existing config at ${t} does not look like editable YAML \u2014 fix or remove it, then re-run`};if(mee(Svt(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=Ivt(o,"visa-cli",r)}else{let a={};if(i){try{a=JSON.parse(o)}catch{return{status:"error",configPath:t,error:`existing config at ${t} is not valid JSON \u2014 fix or remove it, then re-run`}}if(!a||typeof a!="object"||Array.isArray(a))return{status:"error",configPath:t,error:`existing config at ${t} is not a JSON object \u2014 fix or remove it, then re-run`}}if(mee(wvt(a,e.configKey)?.["visa-cli"],r))return{status:"already-mounted",configPath:t};vvt(a,e.configKey)["visa-cli"]=e.buildEntry?e.buildEntry(r):r,s=JSON.stringify(a,null,2)+`
36
- `}return od.mkdirSync(Vt.dirname(t),{recursive:!0}),od.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}var od,Vt,_Te,jn,hvt,_vt,xTe,PTe=P(()=>{"use strict";od=Me(require("fs")),Vt=Me(require("path")),_Te=Me(require("os")),jn=_Te.homedir(),hvt=["Claude_","Anthropic.ClaudeDesktop_"];_vt=[{id:"claude",displayName:"Claude Code",globalConfigPath:Vt.join(jn,".claude.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:gvt(),configKey:"mcpServers",detectPaths:bvt(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Vt.join(jn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Vt.join(jn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Vt.join(jn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:fee({win32:Vt.join(fT(),"Roo","mcp_settings.json"),posix:Vt.join(jn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Vt.join(jn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Vt.join(jn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Vt.join(jn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:fee({win32:Vt.join(fT(),"Zed","settings.json"),posix:Vt.join(jn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:fee({win32:[Vt.join(fT(),"Zed")],posix:[Vt.join(jn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Vt.join(jn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Vt.join(jn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Vt.join(jn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Vt.join(jn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Vt.join(jn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Vt.join(jn,".hermes")],postInstallHint:"Restart Hermes to connect."}];xTe="mcp_servers"});function yee(e,t={}){let r=t.home??bj.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return Zn.join(r,".openclaw","skills");case"hermes":return Zn.join(r,".hermes","skills");case"claude-code":case"claude":return Zn.join(r,".claude","skills");case"default":case"agentskills":return Zn.join(n,".agents","skills");default:return null}}function Ovt(e={}){let t=e.home??bj.homedir(),r=[["openclaw",Zn.join(t,".openclaw")],["hermes",Zn.join(t,".hermes")],["claude-code",Zn.join(t,".claude")]];for(let[n,i]of r)if(qs.existsSync(i))return{runtime:n,base:yee(n,e)};return{runtime:"default",base:yee("default",e)}}function OTe(e){let t=[Zn.join(e,"skills",v0),Zn.join(e,"..","skills",v0),Zn.join(e,"..","..","visa-cli-openclaw","skills",v0),Zn.join(e,"..","..","..","visa-cli-openclaw","skills",v0)];for(let r of t)if(qs.existsSync(Zn.join(r,"SKILL.md")))return r;return null}function Cvt(e){let{bundledDir:t,base:r,force:n}=e;if(!qs.existsSync(Zn.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=Zn.join(r,v0),o=qs.existsSync(i)&&qs.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return qs.mkdirSync(r,{recursive:!0}),o&&qs.rmSync(i,{recursive:!0,force:!0}),qs.cpSync(t,i,{recursive:!0}),{installedDir:i,files:kvt(i),overwrote:o}}function kvt(e){let t=[],r=(n,i)=>{for(let o of qs.readdirSync(n,{withFileTypes:!0})){let s=i?Zn.join(i,o.name):o.name;o.isDirectory()?r(Zn.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function CTe(e){return qs.readFileSync(Zn.join(e,"SKILL.md"),"utf8")}function Nvt(e){let{runtime:t}=e;if(!Rvt.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=wTe(t),n=e.home?Zn.join(e.home,Zn.relative(bj.homedir(),r.globalConfigPath)):r.globalConfigPath,i=ITe(r,n,hee());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function kTe(e){let t,r;if(e.dir)t=Zn.resolve(e.dir),r="custom";else if(e.runtime){let o=yee(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=Ovt(e);t=o.base,r=o.runtime}let n=Cvt({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:Nvt({runtime:r,home:e.home});return{skill:v0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var qs,bj,Zn,v0,Rvt,RTe=P(()=>{"use strict";qs=Me(require("fs")),bj=Me(require("os")),Zn=Me(require("path"));PTe();v0="pair-visa-agent";Rvt=["openclaw","hermes"]});function Bvt(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function BTe(e,t=NTe.spawn){try{let{cmd:r,args:n}=Bvt(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var NTe,jTe=P(()=>{"use strict";NTe=require("node:child_process")});function DTe(e=process.env){return e[Uvt]==="true"}function Fvt(e){return typeof e=="string"&&LB.includes(e)}function S_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wj(e){return typeof e=="string"&&Mvt.test(e)}function _ee(e){return typeof e=="string"&&qvt.test(e)}function _j(e){return typeof e=="string"&&Dvt.test(e)}function Ej(e){return typeof e=="string"&&Gh.includes(e)}function zTe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=zvt&&!Hvt.test(e)}function Kvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function Wvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function HTe(e){if(e.length===0||e.length>Lvt)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&Wvt(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Gvt(e){if(typeof e!="string")return!1;try{return HTe(e)===e}catch{return!1}}function FTe(e){return S_(e)&&e.protocolVersion===Rt&&wj(e.attachId)&&_ee(e.agentId)&&Gvt(e.authUrl)&&Fvt(e.capability)&&Ej(e.rail)&&LTe[e.capability]===e.rail&&e.currency==="USD"&&_j(e.aggregateCeilingMicros)&&_j(e.perTransactionMicros)&&zTe(e.instrumentLabel)&&Sr(e.serverNonce)&&Sr(e.identityKeyJkt)&&Sr(e.claimToken)&&Kvt(e.createdAt)}function vee(e,t=mT){if(!wj(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return bee.join(t,`${e}.json`)}function Jvt(e){sy.mkdirSync(e,{recursive:!0,mode:448});let t=sy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");sy.chmodSync(e,448),Xa(e)}function Yvt(e,t=mT){if(!FTe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Jvt(t),_0(vee(e.attachId,t),JSON.stringify(e,null,2))}function wee(e,t=mT){if(!wj(e))return null;let r=x_(vee(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!FTe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function UTe(e,t=mT){wee(e,t)&&Xa(t)&&sy.rmSync(vee(e,t),{force:!0})}function vj(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function gee(e,t){return t?t.aborted?Promise.reject(vj(t)):new Promise((r,n)=>{let i=()=>n(vj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function Eee(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${MTe}ms`)),MTe);s.unref?.();try{if(i.signal.aborted)throw vj(i.signal);let a=await gee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":jvt,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await gee(a.json(),i.signal)}catch{if(i.signal.aborted)throw vj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=S_(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function VTe(e,t){return Buffer.from(A4(e,Buffer.from(t,"utf8"))).toString("base64url")}function $Te(e,t,r){let n=hT(e,r);if(!n||!tf(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||Yp(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function KTe(e){let t=e.attachDir??mT,r=e.capability,n=hT(e.agentId,e.agentDir);if(!n||!tf(n))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let i=HTe(e.authUrl??n.auth_url??rd());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let o=await e.createCall(e.agentId,{protocolVersion:Rt,capability:r,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!S_(o)||o.protocolVersion!==Rt||!wj(o.attachId)||o.agentId!==e.agentId||o.state!=="attach_initiated"||o.capability!==r||!Ej(o.rail)||o.rail!==LTe[r]||o.currency!=="USD"||!_j(o.aggregateCeilingMicros)||!_j(o.perTransactionMicros)||!zTe(o.instrumentLabel??null)||!Sr(o.serverNonce))throw new Error("capability-attach server returned an invalid create response");let s={protocolVersion:Rt,attachId:o.attachId,agentId:e.agentId,authUrl:i,capability:r,rail:o.rail,currency:"USD",aggregateCeilingMicros:o.aggregateCeilingMicros,perTransactionMicros:o.perTransactionMicros,instrumentLabel:o.instrumentLabel??null,serverNonce:o.serverNonce,identityKeyJkt:n.identity_key.jkt,claimToken:VB(),createdAt:new Date().toISOString()};return Yvt(s,t),s}function Zvt(e,t,r){let n=VTe(r,Hxe({protocolVersion:Rt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:f0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:Rt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function WTe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=$Te(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await Eee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Zvt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!S_(i)||i.protocolVersion!==Rt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function Xvt(e,t){if(!S_(e)||e.protocolVersion!==Rt||e.attachId!==t.attachId||e.agentId!==t.agentId||!Ej(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==f0(t.claimToken)||!_ee(e.ownerPublicId)||!Sr(e.grantHash)||!Sr(e.ceremonyHash)||!Sr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:Rt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:f0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return BQ(r),r}async function Qvt(e,t,r,n){let{status:i,body:o}=await Eee(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!S_(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!Vvt.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),$vt.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=Xvt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function e5t(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await Qvt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&UTe(t.attachId,e.attachDir),a}if(!n)return null;let i=$Te(t.agentId,t.identityKeyJkt,e.agentDir),o=VTe(i.seed,BQ(n)),{body:s}=await Eee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:Rt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!S_(s)||s.protocolVersion!==Rt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!Ej(s.rail)||s.rail!==t.rail||!_ee(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return UTe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function Aee(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await e5t({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await gee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var sy,qTe,bee,jvt,mT,Uvt,Mvt,qvt,Dvt,Lvt,zvt,Hvt,LTe,Vvt,$vt,MTe,GTe=P(()=>{"use strict";sy=Me(require("node:fs")),qTe=Me(require("node:os")),bee=Me(require("node:path"));m_();m4();nT();lT();ay();jvt="4.1.0-rc.56",mT=bee.join(qTe.homedir(),".visa-cli","capability-attach"),Uvt="VISA_V4_CAPABILITY_ATTACH_ENABLED";Mvt=/^ca_[A-Za-z0-9_-]{24}$/,qvt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Dvt=/^(0|[1-9][0-9]{0,17})$/,Lvt=2048,zvt=255,Hvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,LTe={card:"card:vic",wallet:"wallet:x402"};Vvt=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),$vt=new Set(["failed","expired"]);MTe=3e4});var d7e={};Ai(d7e,{agentFilePath:()=>j4,agentFormatIsJson:()=>T_,attachAgentCommand:()=>h5t,attachPollOptsFromFlags:()=>Pee,claimOptsFromFlags:()=>B4,decodeBindingClaims:()=>U4,enrollClaimEnvelope:()=>a7e,formatUsdMicros:()=>gT,isAgentCommandEnabled:()=>s7e,isAgentRecord:()=>Cee,isAgentRecordV2:()=>tf,isStoredAgentRecord:()=>kee,listAgentFiles:()=>Tj,listLegacyAgentRecords:()=>Oj,loginClaimEnvelope:()=>c7e,loginClaimOptsFromFlags:()=>u7e,newestAgentRecord:()=>Pj,newestAgentRecordV2:()=>rf,parseUsdToCents:()=>Iee,readAgent:()=>hT,renderGrantActivated:()=>Oee,writeAgent:()=>Ree});function Cee(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 r5t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function n5t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function i5t(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&n5t(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function o5t(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!t5t.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function s5t(e,t){try{let r=f_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function JTe(e){if(e.length===0||e.length>Tee)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function YTe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function a5t(e){let t=JTe(e.activation_credentials.binding_jwt),r=JTe(e.activation_credentials.registration_jwt);return!t||!r||!YTe(t)||!YTe(r)?!1:t.v===Rt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function o7e(e){return typeof e=="string"&&(See.test(e)||Sr(e))}function yT(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function tf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!yT(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==Rt||typeof t.agent_id!="string"||!See.test(t.agent_id)||typeof t.owner_public_id!="string"||!See.test(t.owner_public_id)||!o5t(t.display_name)||!t.identity_key||!yT(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!yT(t.identity_key.public_jwk??{},["kty","crv","x"])||!yT(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Sr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Sr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Sr(t.identity_key.private_jwk.x)||!Sr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!s5t(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!yT(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>Tee||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>Tee||!t.delivery_artifact||!i5t(t.auth_url)||!r5t(t.created_at)||!a5t(t))return!1;try{let r=JSON.parse(eT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function kee(e){return tf(e)||Cee(e)}function s7e(){return!0}function T_(e){return e==="json"}function a7e(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function c7e(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function B4(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 Iee(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function gT(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Pee(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=B4({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function Oee(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${gT(e.aggregateCeilingMicros)} ceiling.
36
+ `}return od.mkdirSync(Vt.dirname(t),{recursive:!0}),od.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}var od,Vt,_Te,jn,hvt,_vt,xTe,PTe=P(()=>{"use strict";od=Me(require("fs")),Vt=Me(require("path")),_Te=Me(require("os")),jn=_Te.homedir(),hvt=["Claude_","Anthropic.ClaudeDesktop_"];_vt=[{id:"claude",displayName:"Claude Code",globalConfigPath:Vt.join(jn,".claude.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:gvt(),configKey:"mcpServers",detectPaths:bvt(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Vt.join(jn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Vt.join(jn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Vt.join(jn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Vt.join(jn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:fee({win32:Vt.join(fT(),"Roo","mcp_settings.json"),posix:Vt.join(jn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Vt.join(jn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Vt.join(jn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Vt.join(jn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:fee({win32:Vt.join(fT(),"Zed","settings.json"),posix:Vt.join(jn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:fee({win32:[Vt.join(fT(),"Zed")],posix:[Vt.join(jn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Vt.join(jn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Vt.join(jn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Vt.join(jn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Vt.join(jn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Vt.join(jn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Vt.join(jn,".hermes")],postInstallHint:"Restart Hermes to connect."}];xTe="mcp_servers"});function yee(e,t={}){let r=t.home??bj.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return Zn.join(r,".openclaw","skills");case"hermes":return Zn.join(r,".hermes","skills");case"claude-code":case"claude":return Zn.join(r,".claude","skills");case"default":case"agentskills":return Zn.join(n,".agents","skills");default:return null}}function Ovt(e={}){let t=e.home??bj.homedir(),r=[["openclaw",Zn.join(t,".openclaw")],["hermes",Zn.join(t,".hermes")],["claude-code",Zn.join(t,".claude")]];for(let[n,i]of r)if(qs.existsSync(i))return{runtime:n,base:yee(n,e)};return{runtime:"default",base:yee("default",e)}}function OTe(e){let t=[Zn.join(e,"skills",v0),Zn.join(e,"..","skills",v0),Zn.join(e,"..","..","visa-cli-openclaw","skills",v0),Zn.join(e,"..","..","..","visa-cli-openclaw","skills",v0)];for(let r of t)if(qs.existsSync(Zn.join(r,"SKILL.md")))return r;return null}function Cvt(e){let{bundledDir:t,base:r,force:n}=e;if(!qs.existsSync(Zn.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=Zn.join(r,v0),o=qs.existsSync(i)&&qs.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return qs.mkdirSync(r,{recursive:!0}),o&&qs.rmSync(i,{recursive:!0,force:!0}),qs.cpSync(t,i,{recursive:!0}),{installedDir:i,files:kvt(i),overwrote:o}}function kvt(e){let t=[],r=(n,i)=>{for(let o of qs.readdirSync(n,{withFileTypes:!0})){let s=i?Zn.join(i,o.name):o.name;o.isDirectory()?r(Zn.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function CTe(e){return qs.readFileSync(Zn.join(e,"SKILL.md"),"utf8")}function Nvt(e){let{runtime:t}=e;if(!Rvt.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=wTe(t),n=e.home?Zn.join(e.home,Zn.relative(bj.homedir(),r.globalConfigPath)):r.globalConfigPath,i=ITe(r,n,hee());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function kTe(e){let t,r;if(e.dir)t=Zn.resolve(e.dir),r="custom";else if(e.runtime){let o=yee(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=Ovt(e);t=o.base,r=o.runtime}let n=Cvt({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:Nvt({runtime:r,home:e.home});return{skill:v0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var qs,bj,Zn,v0,Rvt,RTe=P(()=>{"use strict";qs=Me(require("fs")),bj=Me(require("os")),Zn=Me(require("path"));PTe();v0="pair-visa-agent";Rvt=["openclaw","hermes"]});function Bvt(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function BTe(e,t=NTe.spawn){try{let{cmd:r,args:n}=Bvt(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var NTe,jTe=P(()=>{"use strict";NTe=require("node:child_process")});function DTe(e=process.env){return e[Uvt]==="true"}function Fvt(e){return typeof e=="string"&&LB.includes(e)}function S_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wj(e){return typeof e=="string"&&Mvt.test(e)}function _ee(e){return typeof e=="string"&&qvt.test(e)}function _j(e){return typeof e=="string"&&Dvt.test(e)}function Ej(e){return typeof e=="string"&&Gh.includes(e)}function zTe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=zvt&&!Hvt.test(e)}function Kvt(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function Wvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function HTe(e){if(e.length===0||e.length>Lvt)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&Wvt(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function Gvt(e){if(typeof e!="string")return!1;try{return HTe(e)===e}catch{return!1}}function FTe(e){return S_(e)&&e.protocolVersion===Rt&&wj(e.attachId)&&_ee(e.agentId)&&Gvt(e.authUrl)&&Fvt(e.capability)&&Ej(e.rail)&&LTe[e.capability]===e.rail&&e.currency==="USD"&&_j(e.aggregateCeilingMicros)&&_j(e.perTransactionMicros)&&zTe(e.instrumentLabel)&&Sr(e.serverNonce)&&Sr(e.identityKeyJkt)&&Sr(e.claimToken)&&Kvt(e.createdAt)}function vee(e,t=mT){if(!wj(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return bee.join(t,`${e}.json`)}function Jvt(e){sy.mkdirSync(e,{recursive:!0,mode:448});let t=sy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");sy.chmodSync(e,448),Xa(e)}function Yvt(e,t=mT){if(!FTe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");Jvt(t),_0(vee(e.attachId,t),JSON.stringify(e,null,2))}function wee(e,t=mT){if(!wj(e))return null;let r=x_(vee(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!FTe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function UTe(e,t=mT){wee(e,t)&&Xa(t)&&sy.rmSync(vee(e,t),{force:!0})}function vj(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function gee(e,t){return t?t.aborted?Promise.reject(vj(t)):new Promise((r,n)=>{let i=()=>n(vj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function Eee(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${MTe}ms`)),MTe);s.unref?.();try{if(i.signal.aborted)throw vj(i.signal);let a=await gee(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":jvt,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await gee(a.json(),i.signal)}catch{if(i.signal.aborted)throw vj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=S_(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function VTe(e,t){return Buffer.from(A4(e,Buffer.from(t,"utf8"))).toString("base64url")}function $Te(e,t,r){let n=hT(e,r);if(!n||!tf(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||Yp(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function KTe(e){let t=e.attachDir??mT,r=e.capability,n=hT(e.agentId,e.agentDir);if(!n||!tf(n))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let i=HTe(e.authUrl??n.auth_url??rd());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let o=await e.createCall(e.agentId,{protocolVersion:Rt,capability:r,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!S_(o)||o.protocolVersion!==Rt||!wj(o.attachId)||o.agentId!==e.agentId||o.state!=="attach_initiated"||o.capability!==r||!Ej(o.rail)||o.rail!==LTe[r]||o.currency!=="USD"||!_j(o.aggregateCeilingMicros)||!_j(o.perTransactionMicros)||!zTe(o.instrumentLabel??null)||!Sr(o.serverNonce))throw new Error("capability-attach server returned an invalid create response");let s={protocolVersion:Rt,attachId:o.attachId,agentId:e.agentId,authUrl:i,capability:r,rail:o.rail,currency:"USD",aggregateCeilingMicros:o.aggregateCeilingMicros,perTransactionMicros:o.perTransactionMicros,instrumentLabel:o.instrumentLabel??null,serverNonce:o.serverNonce,identityKeyJkt:n.identity_key.jkt,claimToken:VB(),createdAt:new Date().toISOString()};return Yvt(s,t),s}function Zvt(e,t,r){let n=VTe(r,Hxe({protocolVersion:Rt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:f0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:Rt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function WTe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=$Te(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await Eee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Zvt(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!S_(i)||i.protocolVersion!==Rt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function Xvt(e,t){if(!S_(e)||e.protocolVersion!==Rt||e.attachId!==t.attachId||e.agentId!==t.agentId||!Ej(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==f0(t.claimToken)||!_ee(e.ownerPublicId)||!Sr(e.grantHash)||!Sr(e.ceremonyHash)||!Sr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:Rt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:f0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return BQ(r),r}async function Qvt(e,t,r,n){let{status:i,body:o}=await Eee(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!S_(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!Vvt.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),$vt.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=Xvt(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function e5t(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await Qvt(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&UTe(t.attachId,e.attachDir),a}if(!n)return null;let i=$Te(t.agentId,t.identityKeyJkt,e.agentDir),o=VTe(i.seed,BQ(n)),{body:s}=await Eee(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:Rt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!S_(s)||s.protocolVersion!==Rt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!Ej(s.rail)||s.rail!==t.rail||!_ee(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return UTe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function Aee(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await e5t({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await gee(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var sy,qTe,bee,jvt,mT,Uvt,Mvt,qvt,Dvt,Lvt,zvt,Hvt,LTe,Vvt,$vt,MTe,GTe=P(()=>{"use strict";sy=Me(require("node:fs")),qTe=Me(require("node:os")),bee=Me(require("node:path"));m_();m4();nT();lT();ay();jvt="4.1.0-rc.57",mT=bee.join(qTe.homedir(),".visa-cli","capability-attach"),Uvt="VISA_V4_CAPABILITY_ATTACH_ENABLED";Mvt=/^ca_[A-Za-z0-9_-]{24}$/,qvt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Dvt=/^(0|[1-9][0-9]{0,17})$/,Lvt=2048,zvt=255,Hvt=/[\p{Cc}\p{Cf}\u2028\u2029]/u,LTe={card:"card:vic",wallet:"wallet:x402"};Vvt=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),$vt=new Set(["failed","expired"]);MTe=3e4});var d7e={};Ai(d7e,{agentFilePath:()=>j4,agentFormatIsJson:()=>T_,attachAgentCommand:()=>h5t,attachPollOptsFromFlags:()=>Pee,claimOptsFromFlags:()=>B4,decodeBindingClaims:()=>U4,enrollClaimEnvelope:()=>a7e,formatUsdMicros:()=>gT,isAgentCommandEnabled:()=>s7e,isAgentRecord:()=>Cee,isAgentRecordV2:()=>tf,isStoredAgentRecord:()=>kee,listAgentFiles:()=>Tj,listLegacyAgentRecords:()=>Oj,loginClaimEnvelope:()=>c7e,loginClaimOptsFromFlags:()=>u7e,newestAgentRecord:()=>Pj,newestAgentRecordV2:()=>rf,parseUsdToCents:()=>Iee,readAgent:()=>hT,renderGrantActivated:()=>Oee,writeAgent:()=>Ree});function Cee(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 r5t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function n5t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function i5t(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&n5t(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function o5t(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!t5t.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function s5t(e,t){try{let r=f_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function JTe(e){if(e.length===0||e.length>Tee)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function YTe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function a5t(e){let t=JTe(e.activation_credentials.binding_jwt),r=JTe(e.activation_credentials.registration_jwt);return!t||!r||!YTe(t)||!YTe(r)?!1:t.v===Rt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function o7e(e){return typeof e=="string"&&(See.test(e)||Sr(e))}function yT(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function tf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!yT(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==Rt||typeof t.agent_id!="string"||!See.test(t.agent_id)||typeof t.owner_public_id!="string"||!See.test(t.owner_public_id)||!o5t(t.display_name)||!t.identity_key||!yT(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!yT(t.identity_key.public_jwk??{},["kty","crv","x"])||!yT(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Sr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Sr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Sr(t.identity_key.private_jwk.x)||!Sr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!s5t(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!yT(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>Tee||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>Tee||!t.delivery_artifact||!i5t(t.auth_url)||!r5t(t.created_at)||!a5t(t))return!1;try{let r=JSON.parse(eT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function kee(e){return tf(e)||Cee(e)}function s7e(){return!0}function T_(e){return e==="json"}function a7e(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function c7e(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function B4(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 Iee(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function gT(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Pee(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=B4({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function Oee(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${gT(e.aggregateCeilingMicros)} ceiling.
37
37
  Rail: ${e.rail}
38
38
  Per transaction: ${gT(e.perTransactionMicros)}
39
39
  Grant: ${e.grantId} (v${e.grantVersion})
@@ -111,7 +111,7 @@ ${e.nonce}`;return i6t.encode(r)}function a6t(e,t,r,n,i,o,s){return s6t({message
111
111
  `:` Could not reach the .visa mesh \u2014 run \`visa register ${e??"<name>"}\` to join it.
112
112
  `}function r7e(e,t){let{json:r,exitCode:n}=a7e(e);if(t)process.stdout.write(JSON.stringify(r)+`
113
113
  `);else{let{text:i,toStderr:o}=u5t(e);(o?process.stderr:process.stdout).write(i)}n!==0&&(process.exitCode=n)}function n7e(e,t){let{json:r,exitCode:n}=c7e(e);if(t)process.stdout.write(JSON.stringify(r)+`
114
- `);else{let{text:i,toStderr:o}=d5t(e);(o?process.stderr:process.stdout).write(i)}n!==0&&(process.exitCode=n)}function f5t(e=dy){nf.mkdirSync(e,{recursive:!0,mode:448});let t=nf.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("agent record directory must be a real directory, not a symlink");nf.chmodSync(e,448),Xa(e)}function j4(e,t=dy){if(!o7e(e))throw new Error("agent record id must be a canonical stable UUID or 32-byte key JKT");return cy.join(t,`${e}.json`)}function Tj(e=dy){return Xa(e)?nf.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>cy.join(e,t)):[]}function m5t(e,t){let r=cy.basename(t),n=r.endsWith(".json")?r.slice(0,-5):"";return(tf(e)?e.agent_id:e.agent_jkt)===n}function Ij(e){let t=aee(e);if(!t)return null;let r;try{r=JSON.parse(t.contents)}catch{throw new Error(`local agent record ${cy.basename(e)} contains invalid JSON`)}if(!kee(r)||!m5t(r,e))throw new Error(`local agent record ${cy.basename(e)} is invalid or misbound to its filename`);return{record:r,mtimeMs:t.mtimeMs}}function hT(e,t=dy){return o7e(e)?Ij(j4(e,t))?.record??null:null}function Ree(e,t=dy){if(!kee(e))throw new Error("refusing to write an invalid agent record");f5t(t);let r=j4(tf(e)?e.agent_id:e.agent_jkt,t);_0(r,JSON.stringify(e,null,2))}function Pj(e=dy){return Oj(e)[0]??null}function Oj(e=dy){return Tj(e).map(t=>Ij(t)).filter(t=>t!==null&&Cee(t.record)).sort((t,r)=>r.mtimeMs-t.mtimeMs).map(({record:t})=>t)}function rf(e=dy){return Tj(e).map(t=>Ij(t)).filter(t=>t!==null&&tf(t.record)).sort((t,r)=>r.mtimeMs-t.mtimeMs).map(({record:t})=>t)[0]??null}function U4(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r===null||typeof r!="object"||Array.isArray(r)?null:r}catch{return null}}function h5t(e){if(!s7e())return;let t=e.command("agent").description("Connect and manage agent runtimes with human-approved Visa identities.");t.command("create").description("Create a secure runtime pairing and authorize it in the browser.").action(async()=>{try{let n=await wT();if(process.stdout.write(["Agent pairing ready.","","Give this skill link to the agent you want to connect:","",` ${n.skillUrl}`,"",`Pairing expires at ${n.expiresAt}.`].join(`
114
+ `);else{let{text:i,toStderr:o}=d5t(e);(o?process.stderr:process.stdout).write(i)}n!==0&&(process.exitCode=n)}function f5t(e=dy){nf.mkdirSync(e,{recursive:!0,mode:448});let t=nf.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("agent record directory must be a real directory, not a symlink");nf.chmodSync(e,448),Xa(e)}function j4(e,t=dy){if(!o7e(e))throw new Error("agent record id must be a canonical stable UUID or 32-byte key JKT");return cy.join(t,`${e}.json`)}function Tj(e=dy){return Xa(e)?nf.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>cy.join(e,t)):[]}function m5t(e,t){let r=cy.basename(t),n=r.endsWith(".json")?r.slice(0,-5):"";return(tf(e)?e.agent_id:e.agent_jkt)===n}function Ij(e){let t=aee(e);if(!t)return null;let r;try{r=JSON.parse(t.contents)}catch{throw new Error(`local agent record ${cy.basename(e)} contains invalid JSON`)}if(!kee(r)||!m5t(r,e))throw new Error(`local agent record ${cy.basename(e)} is invalid or misbound to its filename`);return{record:r,mtimeMs:t.mtimeMs}}function hT(e,t=dy){return o7e(e)?Ij(j4(e,t))?.record??null:null}function Ree(e,t=dy){if(!kee(e))throw new Error("refusing to write an invalid agent record");f5t(t);let r=j4(tf(e)?e.agent_id:e.agent_jkt,t);_0(r,JSON.stringify(e,null,2))}function Pj(e=dy){return Oj(e)[0]??null}function Oj(e=dy){return Tj(e).map(t=>Ij(t)).filter(t=>t!==null&&Cee(t.record)).sort((t,r)=>r.mtimeMs-t.mtimeMs).map(({record:t})=>t)}function rf(e=dy){return Tj(e).map(t=>Ij(t)).filter(t=>t!==null&&tf(t.record)).sort((t,r)=>r.mtimeMs-t.mtimeMs).map(({record:t})=>t)[0]??null}function U4(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r===null||typeof r!="object"||Array.isArray(r)?null:r}catch{return null}}function h5t(e){if(!s7e())return;let t=e.command("agent").description("Connect and manage agent runtimes with human-approved Visa identities.");t.command("create",{hidden:!0}).description("Create a secure runtime pairing and authorize it in the browser.").action(async()=>{try{let n=await wT();if(process.stdout.write(["Agent pairing ready.","","Give this skill link to the agent you want to connect:","",` ${n.skillUrl}`,"",`Pairing expires at ${n.expiresAt}.`].join(`
115
115
  `)+`
116
116
  `),!process.stdin.isTTY){process.stdout.write(`
117
117
  When the agent returns a code, run:
@@ -123,7 +123,7 @@ Verification code from the agent: `)).trim()}finally{i.close()}let s=await uy({p
123
123
  `),await YS(s.authorizationUrl);let a="";for(;a!=="activated";){await new Promise(u=>setTimeout(u,2e3));let c=await kj({pairingId:n.pairingId,authUrl:n.authUrl});if(c.state!==a&&(a=c.state,process.stdout.write(` ${a}
124
124
  `)),["expired","cancelled","failed","revoked"].includes(a))throw new Error(`pairing ended in state ${a}`)}vT(n.pairingId,"human"),process.stdout.write(`\u2713 Agent activated.
125
125
  `)}catch(n){process.stderr.write(`agent create failed: ${n instanceof Error?n.message:String(n)}
126
- `),process.exit(1)}}),t.command("verify [pairing-id] [code]").description("Verify the code returned by an agent (recovery path for a closed create prompt).").action(async(n,i)=>{try{let o=n?sd(n,"human"):xj();if(!o)throw new Error("pending pairing not found on this machine");let s=i?.trim();if(!s&&process.stdin.isTTY){let c=(0,xee.createInterface)({input:process.stdin,output:process.stdout});try{s=(await c.question("Verification code from the agent: ")).trim()}finally{c.close()}}if(!s)throw new Error("verification code required");let a=await uy({pairing:o,code:s});if(!a.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`\u2713 Agent channel verified.
126
+ `),process.exit(1)}}),t.command("verify [pairing-id] [code]",{hidden:!0}).description("Verify the code returned by an agent (recovery path for a closed create prompt).").action(async(n,i)=>{try{let o=n?sd(n,"human"):xj();if(!o)throw new Error("pending pairing not found on this machine");let s=i?.trim();if(!s&&process.stdin.isTTY){let c=(0,xee.createInterface)({input:process.stdin,output:process.stdout});try{s=(await c.question("Verification code from the agent: ")).trim()}finally{c.close()}}if(!s)throw new Error("verification code required");let a=await uy({pairing:o,code:s});if(!a.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`\u2713 Agent channel verified.
127
127
  `),await YS(a.authorizationUrl)}catch(o){process.stderr.write(`agent verify failed: ${o instanceof Error?o.message:String(o)}
128
128
  `),process.exitCode=1}}),t.command("login").description("Restore the account session for an existing v4 user without pairing or payment authority.").option("--format <format>","Output: table (human) or json (machine)","table").option("--no-open","Do not open a browser; print the v4 sign-in URL only.").option("--wait","After presenting the URL, poll until the session is stored.").option("--url <url>","Override the v4 web origin (else VISA_VERIFY_WEB_URL / default).").option("--attempts <n>","(with --wait) poll attempts",n=>parseInt(n,10)).option("--interval <seconds>","(with --wait) seconds between polls",n=>parseInt(n,10)).option("--timeout <seconds>","(with --wait) overall wall-clock bound",n=>parseInt(n,10)).action(async n=>{let i=T_(n.format);try{let o=pT(n.url??Lh());await f9e(o);let{challenge:s,confirmCode:a}=yTe(o),c=`${p9e(o)}?cli=${encodeURIComponent(s)}&mode=login`,u=n.open!==!1&&!GS().headless;u&&await YS(c,{log:()=>{}});let d={status:"pending",browserUrl:c,confirmCode:a,opened:u,requiresBrowser:!0,expiresAt:new Date(Date.now()+hj).toISOString()};if(n.wait){i?process.stdout.write(JSON.stringify(d)+`
129
129
  `):(process.stdout.write(e7e({loginUrl:c,confirmCode:a,opened:u})),process.stdout.write(`
@@ -153,11 +153,11 @@ Verification code from the agent: `)).trim()}finally{i.close()}let s=await uy({p
153
153
  "pair this runtime with my Visa agent identity" \u2014 to run identity-only pairing.
154
154
  `)}catch(o){let s=o instanceof Error?o.message:String(o);if(i){process.stdout.write(JSON.stringify({installed:!1,error:s})+`
155
155
  `),process.exitCode=1;return}process.stderr.write(`agent skill failed: ${s}
156
- `),process.exitCode=1}}),t.command("claim <pairing-id>").description("Claim a pairing as this runtime, retain its pending identity key locally, and wait for approval.").requiredOption("--runtime <runtime>","Runtime name, for example codex or claude-code").requiredOption("--context <label>","Short context label shown to the human").action(async(n,i)=>{try{let{pending:o,verificationCode:s}=await I_({pairingId:n,runtime:i.runtime,contextLabel:i.context});process.stdout.write(["","Ask the human to enter this verification code in their terminal:","",` ${s}`,"","Then compare this request-key fingerprint on the approval page:","",` ${o.identityKeyJkt}`,"","Waiting for approval\u2026"].join(`
156
+ `),process.exitCode=1}}),t.command("claim <pairing-id>",{hidden:!0}).description("Claim a pairing as this runtime, retain its pending identity key locally, and wait for approval.").requiredOption("--runtime <runtime>","Runtime name, for example codex or claude-code").requiredOption("--context <label>","Short context label shown to the human").action(async(n,i)=>{try{let{pending:o,verificationCode:s}=await I_({pairingId:n,runtime:i.runtime,contextLabel:i.context});process.stdout.write(["","Ask the human to enter this verification code in their terminal:","",` ${s}`,"","Then compare this request-key fingerprint on the approval page:","",` ${o.identityKeyJkt}`,"","Waiting for approval\u2026"].join(`
157
157
  `));let a=await Sj({pending:o,onState:c=>process.stdout.write(` ${c}
158
158
  `)});process.stdout.write(`\u2713 Activated ${a.name} (agent ${a.agentId}; key fingerprint ${a.identityKeyJkt}). The exportable identity key and activation credentials are stored in an owner-only 0600 file on this macOS/Linux runtime. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet.
159
159
  `)}catch(o){process.stderr.write(`agent claim failed: ${o instanceof Error?o.message:String(o)}
160
- `),process.exitCode=1}}),t.command("resume <pairing-id>").description("Resume artifact delivery for a runtime pairing claimed on this machine.").action(async n=>{try{let i=sd(n,"runtime");if(!i)throw new Error("runtime pairing not found on this machine");process.stdout.write(`Verification code for the human: ${$B(n,i.claimToken)}
160
+ `),process.exitCode=1}}),t.command("resume <pairing-id>",{hidden:!0}).description("Resume artifact delivery for a runtime pairing claimed on this machine.").action(async n=>{try{let i=sd(n,"runtime");if(!i)throw new Error("runtime pairing not found on this machine");process.stdout.write(`Verification code for the human: ${$B(n,i.claimToken)}
161
161
  Full request-key fingerprint to compare exactly: ${i.identityKeyJkt}
162
162
  `);let o=await Sj({pending:i,onState:s=>process.stdout.write(` ${s}
163
163
  `)});process.stdout.write(`\u2713 Activated ${o.name} (agent ${o.agentId}; key fingerprint ${o.identityKeyJkt}). The exportable identity key remains in an owner-only 0600 file on this macOS/Linux runtime. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet.
@@ -168,7 +168,7 @@ Full request-key fingerprint to compare exactly: ${i.identityKeyJkt}
168
168
  `)});process.stdout.write(Oee(l))}catch(s){process.stderr.write(`agent ${n.commandName} failed: ${s instanceof Error?s.message:String(s)}
169
169
  `),process.exitCode=1}})};r({capability:"card",commandName:"grant-card",description:"Attach card spending authority to an already-paired agent (initiate + claim the capability ceremony).",instrumentNoun:"Card",approvalSurface:"your Visa account settings \u2192 agent card \u2192 Spend"}),r({capability:"wallet",commandName:"grant-wallet",description:"Attach wallet (x402) spending authority to an already-paired agent (initiate + claim the capability ceremony).",instrumentNoun:"Wallet",approvalSurface:"your Visa account settings \u2192 agent wallet \u2192 Spend"}),t.command("grant-activate <attach-id>").description("Finish a spending-grant ceremony: wait for the human approval, then activate the grant.").option("--attempts <n>","Poll attempts before giving up",n=>parseInt(n,10)).option("--interval <seconds>","Seconds between polls",n=>parseInt(n,10)).option("--timeout <seconds>","Overall wall-clock bound",n=>parseInt(n,10)).action(async(n,i)=>{if(!ZTe("agent grant-activate"))try{let o=wee(n);if(!o)throw new Error("capability-attach ceremony not found on this machine");let s=Pee(i),a=await Aee({pending:o,maxPolls:s.maxPolls,pollIntervalMs:s.pollIntervalMs,onState:c=>process.stdout.write(` ${c}
170
170
  `)});process.stdout.write(Oee(a))}catch(o){process.stderr.write(`agent grant-activate failed: ${o instanceof Error?o.message:String(o)}
171
- `),process.exitCode=1}}),t.command("cancel [pairing-id]").description("Cancel a pending pairing created on this machine.").action(async n=>{try{let i=n?sd(n,"human"):xj();if(!i)throw new Error("pending pairing not found on this machine");let o=await Nee({pairing:i});if(o.state!=="cancelled")throw new Error(`pairing cannot be cancelled from state ${o.state}`);process.stdout.write(`\u2713 Pairing ${i.pairingId} cancelled.
171
+ `),process.exitCode=1}}),t.command("cancel [pairing-id]",{hidden:!0}).description("Cancel a pending pairing created on this machine.").action(async n=>{try{let i=n?sd(n,"human"):xj();if(!i)throw new Error("pending pairing not found on this machine");let o=await Nee({pairing:i});if(o.state!=="cancelled")throw new Error(`pairing cannot be cancelled from state ${o.state}`);process.stdout.write(`\u2713 Pairing ${i.pairingId} cancelled.
172
172
  `)}catch(i){process.stderr.write(`agent cancel failed: ${i instanceof Error?i.message:String(i)}
173
173
  `),process.exitCode=1}}),t.command("list").description("List locally stored agent identities.").action(()=>{let n=Tj();if(n.length===0){process.stdout.write("No agents yet. Run `visa agent enroll` to pair one.\n");return}for(let i of n)try{let o=Ij(i)?.record;if(!o)continue;process.stdout.write(tf(o)?`${o.agent_id} ${o.display_name} ${o.pairing_status} identity-key:${o.identity_key.jkt} ${o.created_at}
174
174
  `:`[legacy-v1 key:${o.agent_jkt}] ${o.name} ${o.pairing_status} ${o.created_at}
@@ -177,7 +177,7 @@ Full request-key fingerprint to compare exactly: ${i.identityKeyJkt}
177
177
  `:`Agent not found: ${n}
178
178
  `),process.exitCode=1;return}if(tf(i)){let s=U4(i.activation_credentials.binding_jwt);process.stdout.write([`agent id: ${i.agent_id}`,`name: ${i.display_name}`,`owner id: ${i.owner_public_id}`,`key fingerprint: ${i.identity_key.jkt} (Ed25519, runtime custody)`,`created: ${i.created_at}`,`auth server: ${i.auth_url}`,`pairing: ${i.pairing_id}`,`status: ${i.pairing_status}`,`key file: ${j4(i.agent_id)}`,"key custody: exportable owner-only runtime file (mode 0600; macOS/Linux)","key recovery: unavailable; copying transfers identity proof and loss blocks new proofs","binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (stored binding is malformed)",""].join(`
179
179
  `));return}let o=i.binding_jwt?U4(i.binding_jwt):null;process.stdout.write(["record: legacy v1 (key-addressed; no stable agent id)",`key jkt: ${i.agent_jkt}`,`name: ${i.name}`,`created: ${i.created_at}`,`auth server: ${i.auth_url}`,`pairing: ${i.pairing_id}`,`status: ${i.pairing_status}`,`public key: ${i.public_key_jwk.x} (Ed25519, OKP)`,"registration: stored",`key file: ${j4(i.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",o?JSON.stringify(o,null,2):" (no binding stored or malformed JWT)",""].join(`
180
- `))})}var nf,i7e,cy,xee,dy,See,Tee,t5t,ay=P(()=>{"use strict";nf=Me(require("fs")),i7e=Me(require("os")),cy=Me(require("path")),xee=require("node:readline/promises");m_();lQ();vB();lT();yj();gTe();RTe();jTe();Rj();GTe();XX();g4();dy=cy.join(i7e.homedir(),".visa-cli","agents");See=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Tee=32768,t5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var Lee={};Ai(Lee,{SUBWAY_PROTOCOL:()=>w7e,registerDirect:()=>P5t,resolveDirect:()=>O5t});function Uee(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 ad(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 Mee(e,t){return e<<3|t}function ET(e,t,r){e.push(Mee(t,2)),Uee(e,r.length);for(let n of r)e.push(n)}function y5t(e,t){let r=[];return ET(r,1,jee.encode(e)),t&&t.length>0&&ET(r,2,jee.encode(t)),Uint8Array.from(r)}function g5t(e,t,r){let n=[];return r!==0n&&(n.push(Mee(1,0)),Uee(n,r)),ET(n,2,y5t(e,t)),Uint8Array.from(n)}function b5t(e){let t=[];return ET(t,1,jee.encode(e)),Uint8Array.from(t)}function _5t(e,t){let r=[];return t!==0n&&(r.push(Mee(1,0)),Uee(r,t)),ET(r,3,b5t(e)),Uint8Array.from(r)}function v5t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ad(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.error=_7e.decode(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function w5t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=ad(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]=ad(e,t),u=c,d=u+Number(a);r.error=_7e.decode(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function qee(e,t,r){if(r===0)return ad(e,t)[1];if(r===2){let[n,i]=ad(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 v7e(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ad(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.registerNameResponse=v5t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.resolveNameResponse=w5t(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function E5t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Dee(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function A5t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Dee(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:v7e(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function x5t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Dee(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:v7e(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Bee(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 I5t(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>l7e)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Dee(Bee(t).subarray(0,4)),n>l7e))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Bee(t).subarray(0,n)}return Bee(t)}async function E7e(e){return(0,p7e.createLibp2p)({...e?{privateKey:await(0,y7e.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,f7e.tcp)()],connectionEncrypters:[(0,m7e.noise)()],streamMuxers:[(0,h7e.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function A7e(e,t,r){let n=await e.dialProtocol((0,g7e.multiaddr)(t),w7e,{signal:AbortSignal.timeout(S5t)});n.send(E5t(r));let i;return Promise.race([I5t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),T5t)})]).finally(()=>clearTimeout(i))}async function P5t(e){let t=await E7e(e.seed);try{let r=await A7e(t,e.relayMultiaddr,g5t(e.name,e.binding,e.requestId??1n)),n=A5t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function O5t(e){let t=await E7e(e.seed);try{let r=await A7e(t,e.relayMultiaddr,_5t(e.name,e.requestId??1n)),n=x5t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,b7e.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var p7e,f7e,m7e,h7e,y7e,g7e,b7e,jee,_7e,w7e,S5t,T5t,l7e,zee=P(()=>{"use strict";MQ();p7e=require("libp2p"),f7e=require("@libp2p/tcp"),m7e=require("@chainsafe/libp2p-noise"),h7e=require("@chainsafe/libp2p-yamux"),y7e=require("@libp2p/crypto/keys"),g7e=require("@multiformats/multiaddr"),b7e=require("uint8arrays/to-string"),jee=new TextEncoder,_7e=new TextDecoder;w7e="/subway/p2p/1.0.0",S5t=15e3,T5t=15e3,l7e=1<<20});var xT={};Ai(xT,{DEFAULT_VISA_RELAY_MULTIADDR:()=>x7e,MESH:()=>Ao,RELAY_URL:()=>Kee,connectOrThrow:()=>Uj,ensureMailbox:()=>ete,hydrateInbox:()=>k7e,isSubwayEnabled:()=>Wee,listRegistered:()=>N5t,loadBindingFor:()=>Yee,loadRegistry:()=>P_,makeClient:()=>jj,meshName:()=>of,pairedVisaBinding:()=>P7e,pairedVisaBindingForIdentity:()=>O7e,persistInbox:()=>Qee,readInbox:()=>q5t,registerName:()=>Zee,resolveActingName:()=>C5t,resolveMeshName:()=>k5t,seedSubwayKeyFromExactIdentity:()=>I7e,seedSubwayKeyFromTapAgent:()=>T7e,sendMessage:()=>R5t,sendVia:()=>D5t,subwayKeyPath:()=>Jee,visaRelayMultiaddr:()=>$ee});function $ee(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??x7e}function of(e){return e.includes(".")?e:`${e}.${Ao}`}function Wee(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 Gee(){Ds.mkdirSync(M4,{recursive:!0,mode:448})}function S7e(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Jee(e){return AT.join(M4,`${S7e(e)}.key`)}function P_(){if(!Ds.existsSync(Vee))return{};try{return JSON.parse(Ds.readFileSync(Vee,"utf8"))}catch{return{}}}function Hee(e){Gee(),Ds.writeFileSync(Vee,JSON.stringify(e,null,2),{mode:384})}function Fee(){try{return Bj.userInfo().username}catch{return"local"}}function T7e(e){if(Ds.existsSync(e))return null;let t=Pj();if(!t)return null;try{let r=x4(t.private_key_jwk);return Gee(),Ds.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function I7e(e,t){let r=x4(t.identityPrivateJwk);if(Yp(Yh(p_(r)))!==t.identityKeyJkt)throw new Jp("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ds.existsSync(e)){if(Yp(Yh(p_(rT(e))))!==t.identityKeyJkt)throw new Jp("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return Gee(),Ds.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function jj(e,t={}){return new oTe({name:of(e),url:Kee,keyPath:Jee(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Yee(e){if(Ao!=="visa")return;let t=P_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function Uj(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Kee})`)),t))])}function C5t(e){if(e)return e;let t=Object.keys(P_());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function P7e(e,t=Date.now()){let r=Pj();if(!r?.binding_jwt)return null;let n=U4(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function O7e(e,t,r=Date.now()){for(let n of Oj()){if(n.agent_jkt!==t)continue;let i=U4(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function Zee(e,t={}){let r=Jee(e),n=of(e),i,o;if(t.exactIdentity){if(o=Ao==="visa"?O7e(n,t.exactIdentity.identityKeyJkt):null,Ao==="visa"&&!o)throw new Jp;i=I7e(r,t.exactIdentity)}else i=T7e(r),o=Ao==="visa"?P7e(n):null;let s,a={};if(o){if(!Ds.existsSync(r))throw new Jp("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(Yp(Yh(p_(rT(r))))!==o.identityKeyJkt)throw new Jp("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Ao==="visa")throw new Jp;let c=Ao==="visa"?$ee():process.env.SUBWAY_RELAY_MULTIADDR;if(Ao==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(zee(),Lee)),l=await d({relayMultiaddr:c,seed:rT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=P_();return p[e]={relayName:n,mesh:Ao,peerId:l.peerId,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(p),{relayName:n,mesh:Ao,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Ao==="visa"&&!process.env.SUBWAY_RELAY){let d=P_();return d[e]={relayName:n,mesh:Ao,peerId:null,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(d),{relayName:n,mesh:Ao,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=jj(e,{autoReconnect:!1,binding:s});try{await Uj(u);let d=P_();return d[e]={relayName:n,mesh:Ao,peerId:u.peerId,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(d),{relayName:n,mesh:Ao,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function k5t(e){let t=of(e),r=Ao==="visa"?$ee():process.env.SUBWAY_RELAY_MULTIADDR;if(Ao==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(zee(),Lee)),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 R5t(e,t,r){let n=jj(e,{autoReconnect:!1,binding:Yee(e)});try{await Uj(n);let i=of(t);return await n.sendSigned(i,"chat",r),{to:i,as:of(e)}}finally{n.disconnect()}}function N5t(){let e=P_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function C7e(e,t=M4){return AT.join(t,`${S7e(e)}.inbox.json`)}function j5t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function k7e(e,t=M4){try{let r=JSON.parse(Ds.readFileSync(C7e(e,t),"utf8"));return Array.isArray(r)?r.filter(j5t).slice(-Xee):[]}catch{return[]}}function Qee(e,t,r=M4){try{Ds.mkdirSync(r,{recursive:!0,mode:448}),Ds.writeFileSync(C7e(e,r),JSON.stringify(t.slice(-Xee),null,2),{mode:384})}catch{}}function U5t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Qee(e,t.buffer))},B5t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function M5t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Qee(e,t.buffer)}async function ete(e){let t=Nj.get(e);if(t)return{relayName:of(e),peerId:t.client.peerId};let r=jj(e,{autoReconnect:!0,binding:Yee(e)}),n=k7e(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Xee&&n.shift(),U5t(e,i)}),Nj.set(e,i),await Uj(r),{relayName:of(e),peerId:r.peerId}}async function q5t(e,t=20,r=!1){await ete(e);let n=Nj.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,M5t(e,n)),i}async function D5t(e,t,r){await ete(e);let n=Nj.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=of(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:of(e)}}var Ds,Bj,AT,Ao,x7e,Kee,M4,Vee,Nj,Xee,B5t,O_=P(()=>{"use strict";sTe();m_();Ds=Me(require("fs")),Bj=Me(require("os")),AT=Me(require("path"));nT();ay();Ao=process.env.SUBWAY_MESH??"relay",x7e="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Kee=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";M4=AT.join(Bj.homedir(),".visa-cli","subway"),Vee=AT.join(M4,"registry.json");Nj=new Map,Xee=200,B5t=100});var W7e={};Ai(W7e,{PAIRING_DIR:()=>af,cancelPairing:()=>Nee,claimPairing:()=>I_,getPairingStatus:()=>kj,initiatePairing:()=>wT,latestPendingHumanPairing:()=>xj,latestPendingRuntimePairing:()=>Fj,pairingFilePath:()=>Hj,pollAndActivatePairing:()=>Sj,readPendingPairing:()=>sd,registerOnVisaMeshIfEnabled:()=>Cj,removePendingPairing:()=>vT,tryActivatePairing:()=>ute,verifyPairing:()=>uy,writePendingPairing:()=>cte});async function Cj(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await Zee(e),!0}catch(t){return Ne.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function Qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function nte(e){return typeof e=="string"&&H5t.test(e)}function q4(e){return typeof e=="string"&&F5t.test(e)}function ST(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function q7e(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function qj(e){if(typeof e!="string"||e.length===0||e.length>M7e)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&q7e(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function zj(e){if(e.length===0||e.length>M7e)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&q7e(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function ite(e){if(typeof e!="string")return!1;try{return zj(e)===e}catch{return!1}}function K5t(e){return Qa(e)&&sf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)}function W5t(e){return Qa(e)&&sf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)&&Sr(e.d)}function G5t(e,t){try{let r=f_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function Mj(e,t){if(typeof e!="string"||V5t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function D7e(e){if(!Qa(e)||!sf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=Mj(e.runtime,100),r=Mj(e.contextLabel,200),n=e.cliVersion===void 0?void 0:Mj(e.cliVersion,64),i=e.platform===void 0?void 0:Mj(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function J5t(e){if(!Qa(e))return!1;let t=D7e(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function L7e(e){return Qa(e)?sf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===Rt&&q4(e.pairingId)&&nte(e.agentId)&&Sr(e.verifier)&&ite(e.authUrl)&&qj(e.skillUrl)&&ST(e.expiresAt)&&ST(e.createdAt):!1}function z7e(e){return!Qa(e)||!sf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==Rt||!q4(e.pairingId)||!nte(e.agentId)||!ite(e.authUrl)||!Sr(e.claimToken)||!Sr(e.serverNonce)||!Sr(e.identityKeyJkt)||!K5t(e.identityPublicJwk)||!W5t(e.identityPrivateJwk)||!J5t(e.runtime)||!ST(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&Yp(e.identityPublicJwk)===e.identityKeyJkt&&G5t(e.identityPrivateJwk,e.identityPublicJwk)}function Y5t(e){return Qa(e)&&sf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===Rt&&Sr(e.verifier)&&ite(e.authUrl)&&ST(e.createdAt)}function TT(e,t,r){if(!Qa(e)||e.protocolVersion!==Rt||!q4(e.pairingId)||!nte(e.agentId)||typeof e.state!="string"||!$5t.has(e.state)||!ST(e.expiresAt)||e.skillUrl!==void 0&&!qj(e.skillUrl)||e.authorizationUrl!==void 0&&!qj(e.authorizationUrl)||e.serverNonce!==void 0&&!Sr(e.serverNonce)||e.authApiUrl!==void 0&&!qj(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function Hj(e,t,r=af){if(!q4(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return Lj.join(r,`${e}.${t}.json`)}function H7e(e){Pl.mkdirSync(e,{recursive:!0,mode:448});let t=Pl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Pl.chmodSync(e,448),Xa(e)}function ote(e){return Lj.join(e,L5t)}function ste(e){let t=x_(ote(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!Y5t(r))throw new Error("local pairing initiation state is invalid");return r}function Z5t(e,t){H7e(t),_0(ote(t),JSON.stringify(e,null,2))}function R7e(e,t){let r=ste(t);if(!r)return;let n=sd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&ate(t)}function ate(e){ste(e)&&Xa(e)&&Pl.rmSync(ote(e),{force:!0})}function cte(e,t=af){if(!(e.role==="human"?L7e(e):z7e(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");H7e(t);let n=Hj(e.pairingId,e.role,t);_0(n,JSON.stringify(e,null,2))}function vT(e,t,r=af){sd(e,t,r)&&Xa(r)&&Pl.rmSync(Hj(e,t,r),{force:!0})}function tte(e,t=af){vT(e,"human",t),vT(e,"runtime",t),ate(t)}function sd(e,t,r=af){if(!q4(e))return null;let n=x_(Hj(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!L7e(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!z7e(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function F7e(e,t){return Xa(t)?Pl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!q4(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return sd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function xj(e=af){return F7e("human",e)}function Fj(e=af){return F7e("runtime",e)}function Dj(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function rte(e,t){return t?t.aborted?Promise.reject(Dj(t)):new Promise((r,n)=>{let i=()=>n(Dj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function C_(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${N7e}ms`)),N7e);s.unref?.();try{if(i.signal.aborted)throw Dj(i.signal);let a=await rte(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":U7e,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await rte(a.json(),i.signal)}catch{if(i.signal.aborted)throw Dj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=Qa(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function wT(e={}){let t=zj(e.authUrl??rd()),r=e.pairingDir??af,n=ste(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<z5t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:Rt,verifier:qxe(),authUrl:t,createdAt:new Date().toISOString()};o||Z5t(s,r);let a=s.verifier,{body:c}=await C_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,cliChallenge:Dxe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(TT(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:Rt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:tQ(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return cte(u,r),e.retainInitiationDraft||ate(r),u}function V7e(e){return e.authorizationUrl?{...e,authorizationUrl:tQ(e.authorizationUrl)}:e}async function uy(e){let{pairing:t}=e,{body:r}=await C_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return TT(r,t.pairingId,t.agentId),V7e(r)}async function kj(e){let t=zj(e.authUrl??rd()),{body:r}=await C_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return TT(r,e.pairingId,e.expectedAgentId),V7e(r)}function $7e(e,t){return Buffer.from(A4(e,Buffer.from(t,"utf8"))).toString("base64url")}function X5t(e){let t=$7e(Buffer.from(e.identityPrivateJwk.d,"base64url"),NQ({protocolVersion:Rt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:f0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:Rt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function B7e(e,t,r){let{body:n}=await C_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X5t(e))},t,{signal:r}),i=n;if(!Qa(i)||!sf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==Rt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==$B(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function I_(e){let t=zj(e.authUrl??rd()),r=e.fetchImpl??fetch,n=e.pairingDir??af,i=D7e({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:U7e});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=sd(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return R7e(o.pairingId,n),B7e(o,r,e.signal)}let s=await kj({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Sr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=Pxe(),c=f_(a.secretKey),u=Yh(a.publicKey),d=Yp(u),l=i,p=VB();NQ({protocolVersion:Rt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:f0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:Rt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return cte(f,n),R7e(f.pairingId,n),B7e(f,r,e.signal)}async function K7e(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await C_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(TT(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw tte(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!Qa(r)||!sf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==Rt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!Qa(r.artifact)||!Sr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=eT(r.artifact),o=JSON.parse(i),s=Fxe(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=$7e(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),zxe({protocolVersion:Rt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:f0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await C_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:Rt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!Qa(d)||!sf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==Rt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!Qa(d.credentials)||!sf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:Rt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Ree)(l,e.agentDir),tte(e.pending.pairingId,e.pairingDir);let p=await Cj(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ne.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function ute(e){return K7e(e)}async function Sj(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await K7e({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await rte(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Nee(e){let{pairing:t}=e,{body:r}=await C_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return TT(r,t.pairingId,t.agentId),r.state==="cancelled"&&tte(t.pairingId,e.pairingDir),r}var Pl,j7e,Lj,U7e,af,L5t,z5t,H5t,F5t,V5t,$5t,M7e,N7e,Rj=P(()=>{"use strict";Pl=Me(require("node:fs")),j7e=Me(require("node:os")),Lj=Me(require("node:path"));m_();m4();vB();Sl();nT();O_();lT();ay();U7e="4.1.0-rc.56",af=Lj.join(j7e.homedir(),".visa-cli","pairings"),L5t=".initiation.v2.json",z5t=15*6e4,H5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,F5t=/^ap_[A-Za-z0-9_-]{24}$/,V5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,$5t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),M7e=2048;N7e=3e4});function G7e(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function Q5t(e,t){return t?t.aborted?Promise.reject(G7e(t)):new Promise((r,n)=>{let i=()=>n(G7e(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function ewt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function J7e(e,t){if(t!==void 0&&ewt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function twt(e){return{status:"activated",protocolVersion:Rt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function bT(e={}){let t=Fj(e.pairingDir);if(t){J7e(t.authUrl,e.authUrl);let s=sd(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await I_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await uy({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:Rt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await wT({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await I_({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await uy({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:Rt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function rwt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function _T(e={}){let t=Fj(e.pairingDir);if(!t)return{status:"no_pending"};let r=sd(t.pairingId,"human",e.pairingDir);try{J7e(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await ute({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return twt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await I_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await uy({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await Q5t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:Rt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:rwt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function bTe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await Za.saveSessionToken(e),!0}catch{return!1}}var yj=P(()=>{"use strict";m_();g4();Rj()});var gte={};Ai(gte,{CardDrawRefusedError:()=>R_,cardDrawIntentHash:()=>uIe,decimalUsdToCents:()=>yte,fetchCardDrawVerdict:()=>Awt,loadCardMandateCapability:()=>Ewt,registerCardMandate:()=>xwt});function gwt(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,hte.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function bwt(e){let{secretKey:t,publicKey:r}=Oxe(e),n=f_(t),i=Yh(r);return{privateJwk:n,publicJwk:i,jkt:gwt(i)}}async function aIe(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:ywt},o=`${oIe(i)}.${oIe(n)}`,s=x4(e.privateJwk),a=A4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function cIe(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(!_wt.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:vwt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,hte.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function wwt(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 yte(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 uIe(e,t){let r=yte(e.amount);return r===null?null:cIe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Ewt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(ay(),ie(d7e)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=wwt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=bwt(x4(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function Wj(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${sIe}ms`)),sIe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function dIe(e){return e.replace(/\/+$/,"")}async function Awt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=dIe(e.authBaseUrl),i=uIe(e.draw,e.drawId);if(i===null)throw new R_(400,["invalid_amount"]);let o=await Wj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new R_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new R_(502,["challenge_malformed"]);let a=await aIe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await Wj(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 R_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function xwt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=dIe(e.authBaseUrl),i=yte(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=cIe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await Wj(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 aIe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await Wj(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 hte,ywt,oIe,_wt,vwt,R_,sIe,bte=P(()=>{"use strict";hte=require("node:crypto");m_();ywt="visa-agent-pop+jwt",oIe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");_wt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),vwt=1;R_=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},sIe=3e4});var PPe=g(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});Nl.formatCents=IPe;Nl.formatUsd=P3t;Nl.formatMicros=pU;Nl.formatMicrosWire=O3t;Nl.formatTxAmount=C3t;Nl.formatDate=k3t;Nl.formatRelativeTime=R3t;Nl.formatTime=N3t;Nl.formatAge=B3t;var TPe=1e6,I3t=100;function IPe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/I3t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function P3t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function pU(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/TPe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function O3t(e,t,r={}){return e&&/^-?\d+$/.test(e)?pU(e,r):t!=null&&Number.isFinite(t)?IPe(t,r):r.fallback??"\u2014"}function C3t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return pU(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?pU(n*TPe,t):t.fallback??"\u2014"}function k3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function R3t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?r8(n,i,a,"minute"):c<24?r8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?r8(n,i,u,"day"):d<4?r8(n,i,d,"week"):l<12?r8(n,i,l,"month"):r8(n,i,p,"year")}function r8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function N3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function B3t(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var n8=g(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.formatAge=Yt.formatTime=Yt.formatRelativeTime=Yt.formatDate=Yt.formatTxAmount=Yt.formatMicrosWire=Yt.formatMicros=Yt.formatUsd=Yt.formatCents=void 0;Yt.micros=j3t;Yt.fromCents=U3t;Yt.fromUsdc=M3t;Yt.fromUsd=q3t;Yt.toCents=D3t;Yt.toCentsForAcquirer=L3t;Yt.toUsdc=z3t;Yt.toWire=H3t;Yt.fromWire=F3t;Yt.toDisplay=V3t;Yt.toUsdRounded2dp=$3t;Yt.add=K3t;Yt.sub=W3t;Yt.clampNonNegative=G3t;Yt.isNonNegative=J3t;Yt.max=Y3t;Yt.min=Z3t;var I0=10000n,OPe=1000000n;function j3t(e){return e}function U3t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*I0}function M3t(e){return e}function q3t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function D3t(e){if(e>=0n)return Number(e/I0);let t=e/I0,r=e%I0;return Number(r===0n?t:t-1n)}function L3t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/I0)}function z3t(e){return e}function H3t(e){return e.toString()}function F3t(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function V3t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/OPe,a=o%OPe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function $3t(e){let t=e<0n,r=t?-e:e,n=r/I0,o=r%I0*2n,s;o<I0?s=n:o>I0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function K3t(e,t){return e+t}function W3t(e,t){return e-t}function G3t(e){return e<0n?0n:e}function J3t(e){return e>=0n}function Y3t(e,t){return e>t?e:t}function Z3t(e,t){return e<t?e:t}var P0=PPe();Object.defineProperty(Yt,"formatCents",{enumerable:!0,get:function(){return P0.formatCents}});Object.defineProperty(Yt,"formatUsd",{enumerable:!0,get:function(){return P0.formatUsd}});Object.defineProperty(Yt,"formatMicros",{enumerable:!0,get:function(){return P0.formatMicros}});Object.defineProperty(Yt,"formatMicrosWire",{enumerable:!0,get:function(){return P0.formatMicrosWire}});Object.defineProperty(Yt,"formatTxAmount",{enumerable:!0,get:function(){return P0.formatTxAmount}});Object.defineProperty(Yt,"formatDate",{enumerable:!0,get:function(){return P0.formatDate}});Object.defineProperty(Yt,"formatRelativeTime",{enumerable:!0,get:function(){return P0.formatRelativeTime}});Object.defineProperty(Yt,"formatTime",{enumerable:!0,get:function(){return P0.formatTime}});Object.defineProperty(Yt,"formatAge",{enumerable:!0,get:function(){return P0.formatAge}})});var zte=g(rc=>{"use strict";var X3t=rc&&rc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Q3t=rc&&rc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),kPe=rc&&rc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&X3t(r,t,n[i]);return Q3t(r,t),r}})();Object.defineProperty(rc,"__esModule",{value:!0});rc.pruneResponsesDir=Lte;rc.isTextualContentType=fU;rc.isValidUtf8=NPe;rc.spillFilename=BPe;rc.describePaidBody=qte;rc.capturePaidResponse=oEt;var pf=kPe(require("fs")),VT=kPe(require("path")),eEt=require("node:crypto"),RPe=16*1024,Mte=2*1024,tEt=64*1024*1024,rEt=3e4,Dte=256*1024*1024;function Lte(e,t=Dte,r){try{let n=r?VT.basename(r):null,i=pf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=pf.statSync(VT.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{pf.rmSync(VT.join(e,s.name),{force:!0})}catch{}}catch{}}var nEt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function fU(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||nEt.has(t)}function NPe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var iEt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function BPe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=iEt[o]??(fU(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jPe(e,t,r){let n=BPe(t,r,new Date),i=VT.extname(n),o=n.slice(0,n.length-i.length);return VT.join(e,`${o}-${(0,eEt.randomBytes)(8).toString("hex")}${i}`)}function UPe(e){pf.mkdirSync(e,{recursive:!0,mode:448})}function CPe(e,t){let r=0;for(;r<t.length;){let n=pf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function qte(e,t,r,n,i){let o=r?fU(r):NPe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=RPe)return{...s,body:n.toString("utf-8")};UPe(i);let a=jPe(i,e,r);return pf.writeFileSync(a,n,{flag:"wx",mode:384}),Lte(i,Dte,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Mte).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function oEt(e,t,r,n={}){let i=n.maxBytes??tEt,o=n.timeoutMs??rEt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return qte(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(pf.closeSync(p),p=null)},E=()=>{if(v(),m)try{pf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((O,M)=>{x=setTimeout(()=>M(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),C;try{C=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(C.done)break;let T=Buffer.from(C.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Mte){let O=T.subarray(0,Math.min(T.length,Mte-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=RPe)continue;UPe(r),f=jPe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=pf.openSync(m,"wx",384);for(let O of u)CPe(p,O);u.length=0,d=0}else CPe(p,T)}if(p===null){let A=Buffer.concat(u,d);return qte(e,t.status,t.headers.get("content-type"),A,r)}v(),pf.renameSync(m,f),m=null,Lte(r,Dte,f);let _=t.headers.get("content-type"),w=_?fU(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var gy=g(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.TURNKEY_API_BASE_URL_ENV=so.CIRCLE_TESTNET_FAUCET_URL=so.NETWORK_ENV=so.NETWORKS=void 0;so.resolveNetwork=sEt;so.turnkeyApiBaseUrl=cEt;so.explorerTxUrl=uEt;so.explorerAddressUrl=dEt;so.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};so.NETWORK_ENV="VISA_V4_NETWORK";so.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var MPe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function sEt(e=process.env){let t=(e[so.NETWORK_ENV]??"").trim();if(t==="")return so.NETWORKS["base-mainnet"];let r=MPe[t.toLowerCase()];if(!r)throw new Error(`unknown ${so.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(MPe).join(", "));return so.NETWORKS[r]}so.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var aEt="https://api.turnkey.com";function cEt(e=process.env){let t=(e[so.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?aEt:t}function uEt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function dEt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qPe=g(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0});mU.version=void 0;mU.version="1.2.3"});var Y_=g(hU=>{"use strict";Object.defineProperty(hU,"__esModule",{value:!0});hU.BaseError=void 0;var lEt=qPe(),Hte=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${lEt.version}`].join(`
180
+ `))})}var nf,i7e,cy,xee,dy,See,Tee,t5t,ay=P(()=>{"use strict";nf=Me(require("fs")),i7e=Me(require("os")),cy=Me(require("path")),xee=require("node:readline/promises");m_();lQ();vB();lT();yj();gTe();RTe();jTe();Rj();GTe();XX();g4();dy=cy.join(i7e.homedir(),".visa-cli","agents");See=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Tee=32768,t5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var Lee={};Ai(Lee,{SUBWAY_PROTOCOL:()=>w7e,registerDirect:()=>P5t,resolveDirect:()=>O5t});function Uee(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 ad(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 Mee(e,t){return e<<3|t}function ET(e,t,r){e.push(Mee(t,2)),Uee(e,r.length);for(let n of r)e.push(n)}function y5t(e,t){let r=[];return ET(r,1,jee.encode(e)),t&&t.length>0&&ET(r,2,jee.encode(t)),Uint8Array.from(r)}function g5t(e,t,r){let n=[];return r!==0n&&(n.push(Mee(1,0)),Uee(n,r)),ET(n,2,y5t(e,t)),Uint8Array.from(n)}function b5t(e){let t=[];return ET(t,1,jee.encode(e)),Uint8Array.from(t)}function _5t(e,t){let r=[];return t!==0n&&(r.push(Mee(1,0)),Uee(r,t)),ET(r,3,b5t(e)),Uint8Array.from(r)}function v5t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ad(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.error=_7e.decode(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function w5t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=ad(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]=ad(e,t),u=c,d=u+Number(a);r.error=_7e.decode(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function qee(e,t,r){if(r===0)return ad(e,t)[1];if(r===2){let[n,i]=ad(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 v7e(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=ad(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=ad(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.registerNameResponse=v5t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=ad(e,t),u=c,d=u+Number(a);r.resolveNameResponse=w5t(e.subarray(u,d)),t=d}else t=qee(e,t,s)}return r}function E5t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Dee(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function A5t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Dee(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:v7e(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function x5t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Dee(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:v7e(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Bee(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 I5t(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>l7e)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Dee(Bee(t).subarray(0,4)),n>l7e))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Bee(t).subarray(0,n)}return Bee(t)}async function E7e(e){return(0,p7e.createLibp2p)({...e?{privateKey:await(0,y7e.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,f7e.tcp)()],connectionEncrypters:[(0,m7e.noise)()],streamMuxers:[(0,h7e.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function A7e(e,t,r){let n=await e.dialProtocol((0,g7e.multiaddr)(t),w7e,{signal:AbortSignal.timeout(S5t)});n.send(E5t(r));let i;return Promise.race([I5t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),T5t)})]).finally(()=>clearTimeout(i))}async function P5t(e){let t=await E7e(e.seed);try{let r=await A7e(t,e.relayMultiaddr,g5t(e.name,e.binding,e.requestId??1n)),n=A5t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function O5t(e){let t=await E7e(e.seed);try{let r=await A7e(t,e.relayMultiaddr,_5t(e.name,e.requestId??1n)),n=x5t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,b7e.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var p7e,f7e,m7e,h7e,y7e,g7e,b7e,jee,_7e,w7e,S5t,T5t,l7e,zee=P(()=>{"use strict";MQ();p7e=require("libp2p"),f7e=require("@libp2p/tcp"),m7e=require("@chainsafe/libp2p-noise"),h7e=require("@chainsafe/libp2p-yamux"),y7e=require("@libp2p/crypto/keys"),g7e=require("@multiformats/multiaddr"),b7e=require("uint8arrays/to-string"),jee=new TextEncoder,_7e=new TextDecoder;w7e="/subway/p2p/1.0.0",S5t=15e3,T5t=15e3,l7e=1<<20});var xT={};Ai(xT,{DEFAULT_VISA_RELAY_MULTIADDR:()=>x7e,MESH:()=>Ao,RELAY_URL:()=>Kee,connectOrThrow:()=>Uj,ensureMailbox:()=>ete,hydrateInbox:()=>k7e,isSubwayEnabled:()=>Wee,listRegistered:()=>N5t,loadBindingFor:()=>Yee,loadRegistry:()=>P_,makeClient:()=>jj,meshName:()=>of,pairedVisaBinding:()=>P7e,pairedVisaBindingForIdentity:()=>O7e,persistInbox:()=>Qee,readInbox:()=>q5t,registerName:()=>Zee,resolveActingName:()=>C5t,resolveMeshName:()=>k5t,seedSubwayKeyFromExactIdentity:()=>I7e,seedSubwayKeyFromTapAgent:()=>T7e,sendMessage:()=>R5t,sendVia:()=>D5t,subwayKeyPath:()=>Jee,visaRelayMultiaddr:()=>$ee});function $ee(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??x7e}function of(e){return e.includes(".")?e:`${e}.${Ao}`}function Wee(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 Gee(){Ds.mkdirSync(M4,{recursive:!0,mode:448})}function S7e(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Jee(e){return AT.join(M4,`${S7e(e)}.key`)}function P_(){if(!Ds.existsSync(Vee))return{};try{return JSON.parse(Ds.readFileSync(Vee,"utf8"))}catch{return{}}}function Hee(e){Gee(),Ds.writeFileSync(Vee,JSON.stringify(e,null,2),{mode:384})}function Fee(){try{return Bj.userInfo().username}catch{return"local"}}function T7e(e){if(Ds.existsSync(e))return null;let t=Pj();if(!t)return null;try{let r=x4(t.private_key_jwk);return Gee(),Ds.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function I7e(e,t){let r=x4(t.identityPrivateJwk);if(Yp(Yh(p_(r)))!==t.identityKeyJkt)throw new Jp("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ds.existsSync(e)){if(Yp(Yh(p_(rT(e))))!==t.identityKeyJkt)throw new Jp("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return Gee(),Ds.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function jj(e,t={}){return new oTe({name:of(e),url:Kee,keyPath:Jee(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Yee(e){if(Ao!=="visa")return;let t=P_()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function Uj(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Kee})`)),t))])}function C5t(e){if(e)return e;let t=Object.keys(P_());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function P7e(e,t=Date.now()){let r=Pj();if(!r?.binding_jwt)return null;let n=U4(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function O7e(e,t,r=Date.now()){for(let n of Oj()){if(n.agent_jkt!==t)continue;let i=U4(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function Zee(e,t={}){let r=Jee(e),n=of(e),i,o;if(t.exactIdentity){if(o=Ao==="visa"?O7e(n,t.exactIdentity.identityKeyJkt):null,Ao==="visa"&&!o)throw new Jp;i=I7e(r,t.exactIdentity)}else i=T7e(r),o=Ao==="visa"?P7e(n):null;let s,a={};if(o){if(!Ds.existsSync(r))throw new Jp("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(Yp(Yh(p_(rT(r))))!==o.identityKeyJkt)throw new Jp("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Ao==="visa")throw new Jp;let c=Ao==="visa"?$ee():process.env.SUBWAY_RELAY_MULTIADDR;if(Ao==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(zee(),Lee)),l=await d({relayMultiaddr:c,seed:rT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=P_();return p[e]={relayName:n,mesh:Ao,peerId:l.peerId,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(p),{relayName:n,mesh:Ao,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Ao==="visa"&&!process.env.SUBWAY_RELAY){let d=P_();return d[e]={relayName:n,mesh:Ao,peerId:null,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(d),{relayName:n,mesh:Ao,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=jj(e,{autoReconnect:!1,binding:s});try{await Uj(u);let d=P_();return d[e]={relayName:n,mesh:Ao,peerId:u.peerId,owner:Fee(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},Hee(d),{relayName:n,mesh:Ao,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function k5t(e){let t=of(e),r=Ao==="visa"?$ee():process.env.SUBWAY_RELAY_MULTIADDR;if(Ao==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(zee(),Lee)),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 R5t(e,t,r){let n=jj(e,{autoReconnect:!1,binding:Yee(e)});try{await Uj(n);let i=of(t);return await n.sendSigned(i,"chat",r),{to:i,as:of(e)}}finally{n.disconnect()}}function N5t(){let e=P_();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function C7e(e,t=M4){return AT.join(t,`${S7e(e)}.inbox.json`)}function j5t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function k7e(e,t=M4){try{let r=JSON.parse(Ds.readFileSync(C7e(e,t),"utf8"));return Array.isArray(r)?r.filter(j5t).slice(-Xee):[]}catch{return[]}}function Qee(e,t,r=M4){try{Ds.mkdirSync(r,{recursive:!0,mode:448}),Ds.writeFileSync(C7e(e,r),JSON.stringify(t.slice(-Xee),null,2),{mode:384})}catch{}}function U5t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Qee(e,t.buffer))},B5t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function M5t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Qee(e,t.buffer)}async function ete(e){let t=Nj.get(e);if(t)return{relayName:of(e),peerId:t.client.peerId};let r=jj(e,{autoReconnect:!0,binding:Yee(e)}),n=k7e(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Xee&&n.shift(),U5t(e,i)}),Nj.set(e,i),await Uj(r),{relayName:of(e),peerId:r.peerId}}async function q5t(e,t=20,r=!1){await ete(e);let n=Nj.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,M5t(e,n)),i}async function D5t(e,t,r){await ete(e);let n=Nj.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=of(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:of(e)}}var Ds,Bj,AT,Ao,x7e,Kee,M4,Vee,Nj,Xee,B5t,O_=P(()=>{"use strict";sTe();m_();Ds=Me(require("fs")),Bj=Me(require("os")),AT=Me(require("path"));nT();ay();Ao=process.env.SUBWAY_MESH??"relay",x7e="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Kee=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";M4=AT.join(Bj.homedir(),".visa-cli","subway"),Vee=AT.join(M4,"registry.json");Nj=new Map,Xee=200,B5t=100});var W7e={};Ai(W7e,{PAIRING_DIR:()=>af,cancelPairing:()=>Nee,claimPairing:()=>I_,getPairingStatus:()=>kj,initiatePairing:()=>wT,latestPendingHumanPairing:()=>xj,latestPendingRuntimePairing:()=>Fj,pairingFilePath:()=>Hj,pollAndActivatePairing:()=>Sj,readPendingPairing:()=>sd,registerOnVisaMeshIfEnabled:()=>Cj,removePendingPairing:()=>vT,tryActivatePairing:()=>ute,verifyPairing:()=>uy,writePendingPairing:()=>cte});async function Cj(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await Zee(e),!0}catch(t){return Ne.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function Qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function nte(e){return typeof e=="string"&&H5t.test(e)}function q4(e){return typeof e=="string"&&F5t.test(e)}function ST(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function q7e(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function qj(e){if(typeof e!="string"||e.length===0||e.length>M7e)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&q7e(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function zj(e){if(e.length===0||e.length>M7e)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&q7e(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function ite(e){if(typeof e!="string")return!1;try{return zj(e)===e}catch{return!1}}function K5t(e){return Qa(e)&&sf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)}function W5t(e){return Qa(e)&&sf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Sr(e.x)&&Sr(e.d)}function G5t(e,t){try{let r=f_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function Mj(e,t){if(typeof e!="string"||V5t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function D7e(e){if(!Qa(e)||!sf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=Mj(e.runtime,100),r=Mj(e.contextLabel,200),n=e.cliVersion===void 0?void 0:Mj(e.cliVersion,64),i=e.platform===void 0?void 0:Mj(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function J5t(e){if(!Qa(e))return!1;let t=D7e(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function L7e(e){return Qa(e)?sf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===Rt&&q4(e.pairingId)&&nte(e.agentId)&&Sr(e.verifier)&&ite(e.authUrl)&&qj(e.skillUrl)&&ST(e.expiresAt)&&ST(e.createdAt):!1}function z7e(e){return!Qa(e)||!sf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==Rt||!q4(e.pairingId)||!nte(e.agentId)||!ite(e.authUrl)||!Sr(e.claimToken)||!Sr(e.serverNonce)||!Sr(e.identityKeyJkt)||!K5t(e.identityPublicJwk)||!W5t(e.identityPrivateJwk)||!J5t(e.runtime)||!ST(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&Yp(e.identityPublicJwk)===e.identityKeyJkt&&G5t(e.identityPrivateJwk,e.identityPublicJwk)}function Y5t(e){return Qa(e)&&sf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===Rt&&Sr(e.verifier)&&ite(e.authUrl)&&ST(e.createdAt)}function TT(e,t,r){if(!Qa(e)||e.protocolVersion!==Rt||!q4(e.pairingId)||!nte(e.agentId)||typeof e.state!="string"||!$5t.has(e.state)||!ST(e.expiresAt)||e.skillUrl!==void 0&&!qj(e.skillUrl)||e.authorizationUrl!==void 0&&!qj(e.authorizationUrl)||e.serverNonce!==void 0&&!Sr(e.serverNonce)||e.authApiUrl!==void 0&&!qj(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function Hj(e,t,r=af){if(!q4(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return Lj.join(r,`${e}.${t}.json`)}function H7e(e){Pl.mkdirSync(e,{recursive:!0,mode:448});let t=Pl.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");Pl.chmodSync(e,448),Xa(e)}function ote(e){return Lj.join(e,L5t)}function ste(e){let t=x_(ote(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!Y5t(r))throw new Error("local pairing initiation state is invalid");return r}function Z5t(e,t){H7e(t),_0(ote(t),JSON.stringify(e,null,2))}function R7e(e,t){let r=ste(t);if(!r)return;let n=sd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&ate(t)}function ate(e){ste(e)&&Xa(e)&&Pl.rmSync(ote(e),{force:!0})}function cte(e,t=af){if(!(e.role==="human"?L7e(e):z7e(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");H7e(t);let n=Hj(e.pairingId,e.role,t);_0(n,JSON.stringify(e,null,2))}function vT(e,t,r=af){sd(e,t,r)&&Xa(r)&&Pl.rmSync(Hj(e,t,r),{force:!0})}function tte(e,t=af){vT(e,"human",t),vT(e,"runtime",t),ate(t)}function sd(e,t,r=af){if(!q4(e))return null;let n=x_(Hj(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!L7e(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!z7e(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function F7e(e,t){return Xa(t)?Pl.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!q4(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return sd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function xj(e=af){return F7e("human",e)}function Fj(e=af){return F7e("runtime",e)}function Dj(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function rte(e,t){return t?t.aborted?Promise.reject(Dj(t)):new Promise((r,n)=>{let i=()=>n(Dj(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function C_(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${N7e}ms`)),N7e);s.unref?.();try{if(i.signal.aborted)throw Dj(i.signal);let a=await rte(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":U7e,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await rte(a.json(),i.signal)}catch{if(i.signal.aborted)throw Dj(i.signal);c={}}if(!a.ok&&a.status!==202){let u=Qa(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function wT(e={}){let t=zj(e.authUrl??rd()),r=e.pairingDir??af,n=ste(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<z5t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:Rt,verifier:qxe(),authUrl:t,createdAt:new Date().toISOString()};o||Z5t(s,r);let a=s.verifier,{body:c}=await C_(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,cliChallenge:Dxe(a)})},e.fetchImpl??fetch,{signal:e.signal});if(TT(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:Rt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:tQ(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return cte(u,r),e.retainInitiationDraft||ate(r),u}function V7e(e){return e.authorizationUrl?{...e,authorizationUrl:tQ(e.authorizationUrl)}:e}async function uy(e){let{pairing:t}=e,{body:r}=await C_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return TT(r,t.pairingId,t.agentId),V7e(r)}async function kj(e){let t=zj(e.authUrl??rd()),{body:r}=await C_(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return TT(r,e.pairingId,e.expectedAgentId),V7e(r)}function $7e(e,t){return Buffer.from(A4(e,Buffer.from(t,"utf8"))).toString("base64url")}function X5t(e){let t=$7e(Buffer.from(e.identityPrivateJwk.d,"base64url"),NQ({protocolVersion:Rt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:f0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:Rt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function B7e(e,t,r){let{body:n}=await C_(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X5t(e))},t,{signal:r}),i=n;if(!Qa(i)||!sf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==Rt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==$B(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function I_(e){let t=zj(e.authUrl??rd()),r=e.fetchImpl??fetch,n=e.pairingDir??af,i=D7e({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:U7e});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=sd(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return R7e(o.pairingId,n),B7e(o,r,e.signal)}let s=await kj({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Sr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=Pxe(),c=f_(a.secretKey),u=Yh(a.publicKey),d=Yp(u),l=i,p=VB();NQ({protocolVersion:Rt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:f0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:Rt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return cte(f,n),R7e(f.pairingId,n),B7e(f,r,e.signal)}async function K7e(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await C_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(TT(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw tte(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!Qa(r)||!sf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==Rt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!Qa(r.artifact)||!Sr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=eT(r.artifact),o=JSON.parse(i),s=Fxe(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=$7e(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),zxe({protocolVersion:Rt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:f0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await C_(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:Rt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!Qa(d)||!sf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==Rt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!Qa(d.credentials)||!sf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:Rt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Ree)(l,e.agentDir),tte(e.pending.pairingId,e.pairingDir);let p=await Cj(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ne.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function ute(e){return K7e(e)}async function Sj(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await K7e({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await rte(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Nee(e){let{pairing:t}=e,{body:r}=await C_(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:Rt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return TT(r,t.pairingId,t.agentId),r.state==="cancelled"&&tte(t.pairingId,e.pairingDir),r}var Pl,j7e,Lj,U7e,af,L5t,z5t,H5t,F5t,V5t,$5t,M7e,N7e,Rj=P(()=>{"use strict";Pl=Me(require("node:fs")),j7e=Me(require("node:os")),Lj=Me(require("node:path"));m_();m4();vB();Sl();nT();O_();lT();ay();U7e="4.1.0-rc.57",af=Lj.join(j7e.homedir(),".visa-cli","pairings"),L5t=".initiation.v2.json",z5t=15*6e4,H5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,F5t=/^ap_[A-Za-z0-9_-]{24}$/,V5t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,$5t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),M7e=2048;N7e=3e4});function G7e(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function Q5t(e,t){return t?t.aborted?Promise.reject(G7e(t)):new Promise((r,n)=>{let i=()=>n(G7e(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function ewt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function J7e(e,t){if(t!==void 0&&ewt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function twt(e){return{status:"activated",protocolVersion:Rt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function bT(e={}){let t=Fj(e.pairingDir);if(t){J7e(t.authUrl,e.authUrl);let s=sd(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await I_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await uy({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:Rt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await wT({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await I_({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await uy({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:Rt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function rwt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function _T(e={}){let t=Fj(e.pairingDir);if(!t)return{status:"no_pending"};let r=sd(t.pairingId,"human",e.pairingDir);try{J7e(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await ute({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return twt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await I_({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await uy({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await Q5t(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:Rt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:rwt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function bTe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await Za.saveSessionToken(e),!0}catch{return!1}}var yj=P(()=>{"use strict";m_();g4();Rj()});var gte={};Ai(gte,{CardDrawRefusedError:()=>R_,cardDrawIntentHash:()=>uIe,decimalUsdToCents:()=>yte,fetchCardDrawVerdict:()=>Awt,loadCardMandateCapability:()=>Ewt,registerCardMandate:()=>xwt});function gwt(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,hte.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function bwt(e){let{secretKey:t,publicKey:r}=Oxe(e),n=f_(t),i=Yh(r);return{privateJwk:n,publicJwk:i,jkt:gwt(i)}}async function aIe(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:ywt},o=`${oIe(i)}.${oIe(n)}`,s=x4(e.privateJwk),a=A4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function cIe(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(!_wt.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:vwt,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,hte.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function wwt(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 yte(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 uIe(e,t){let r=yte(e.amount);return r===null?null:cIe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function Ewt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(ay(),ie(d7e)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=wwt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=bwt(x4(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function Wj(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${sIe}ms`)),sIe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function dIe(e){return e.replace(/\/+$/,"")}async function Awt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=dIe(e.authBaseUrl),i=uIe(e.draw,e.drawId);if(i===null)throw new R_(400,["invalid_amount"]);let o=await Wj(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new R_(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new R_(502,["challenge_malformed"]);let a=await aIe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await Wj(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 R_(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function xwt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=dIe(e.authBaseUrl),i=yte(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=cIe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await Wj(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 aIe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await Wj(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 hte,ywt,oIe,_wt,vwt,R_,sIe,bte=P(()=>{"use strict";hte=require("node:crypto");m_();ywt="visa-agent-pop+jwt",oIe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");_wt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),vwt=1;R_=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},sIe=3e4});var PPe=g(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});Nl.formatCents=IPe;Nl.formatUsd=P3t;Nl.formatMicros=pU;Nl.formatMicrosWire=O3t;Nl.formatTxAmount=C3t;Nl.formatDate=k3t;Nl.formatRelativeTime=R3t;Nl.formatTime=N3t;Nl.formatAge=B3t;var TPe=1e6,I3t=100;function IPe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/I3t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function P3t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function pU(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/TPe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function O3t(e,t,r={}){return e&&/^-?\d+$/.test(e)?pU(e,r):t!=null&&Number.isFinite(t)?IPe(t,r):r.fallback??"\u2014"}function C3t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return pU(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?pU(n*TPe,t):t.fallback??"\u2014"}function k3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function R3t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?r8(n,i,a,"minute"):c<24?r8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?r8(n,i,u,"day"):d<4?r8(n,i,d,"week"):l<12?r8(n,i,l,"month"):r8(n,i,p,"year")}function r8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function N3t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function B3t(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var n8=g(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.formatAge=Yt.formatTime=Yt.formatRelativeTime=Yt.formatDate=Yt.formatTxAmount=Yt.formatMicrosWire=Yt.formatMicros=Yt.formatUsd=Yt.formatCents=void 0;Yt.micros=j3t;Yt.fromCents=U3t;Yt.fromUsdc=M3t;Yt.fromUsd=q3t;Yt.toCents=D3t;Yt.toCentsForAcquirer=L3t;Yt.toUsdc=z3t;Yt.toWire=H3t;Yt.fromWire=F3t;Yt.toDisplay=V3t;Yt.toUsdRounded2dp=$3t;Yt.add=K3t;Yt.sub=W3t;Yt.clampNonNegative=G3t;Yt.isNonNegative=J3t;Yt.max=Y3t;Yt.min=Z3t;var I0=10000n,OPe=1000000n;function j3t(e){return e}function U3t(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*I0}function M3t(e){return e}function q3t(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function D3t(e){if(e>=0n)return Number(e/I0);let t=e/I0,r=e%I0;return Number(r===0n?t:t-1n)}function L3t(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/I0)}function z3t(e){return e}function H3t(e){return e.toString()}function F3t(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function V3t(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/OPe,a=o%OPe,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function $3t(e){let t=e<0n,r=t?-e:e,n=r/I0,o=r%I0*2n,s;o<I0?s=n:o>I0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function K3t(e,t){return e+t}function W3t(e,t){return e-t}function G3t(e){return e<0n?0n:e}function J3t(e){return e>=0n}function Y3t(e,t){return e>t?e:t}function Z3t(e,t){return e<t?e:t}var P0=PPe();Object.defineProperty(Yt,"formatCents",{enumerable:!0,get:function(){return P0.formatCents}});Object.defineProperty(Yt,"formatUsd",{enumerable:!0,get:function(){return P0.formatUsd}});Object.defineProperty(Yt,"formatMicros",{enumerable:!0,get:function(){return P0.formatMicros}});Object.defineProperty(Yt,"formatMicrosWire",{enumerable:!0,get:function(){return P0.formatMicrosWire}});Object.defineProperty(Yt,"formatTxAmount",{enumerable:!0,get:function(){return P0.formatTxAmount}});Object.defineProperty(Yt,"formatDate",{enumerable:!0,get:function(){return P0.formatDate}});Object.defineProperty(Yt,"formatRelativeTime",{enumerable:!0,get:function(){return P0.formatRelativeTime}});Object.defineProperty(Yt,"formatTime",{enumerable:!0,get:function(){return P0.formatTime}});Object.defineProperty(Yt,"formatAge",{enumerable:!0,get:function(){return P0.formatAge}})});var zte=g(rc=>{"use strict";var X3t=rc&&rc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Q3t=rc&&rc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),kPe=rc&&rc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&X3t(r,t,n[i]);return Q3t(r,t),r}})();Object.defineProperty(rc,"__esModule",{value:!0});rc.pruneResponsesDir=Lte;rc.isTextualContentType=fU;rc.isValidUtf8=NPe;rc.spillFilename=BPe;rc.describePaidBody=qte;rc.capturePaidResponse=oEt;var pf=kPe(require("fs")),VT=kPe(require("path")),eEt=require("node:crypto"),RPe=16*1024,Mte=2*1024,tEt=64*1024*1024,rEt=3e4,Dte=256*1024*1024;function Lte(e,t=Dte,r){try{let n=r?VT.basename(r):null,i=pf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=pf.statSync(VT.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{pf.rmSync(VT.join(e,s.name),{force:!0})}catch{}}catch{}}var nEt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function fU(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||nEt.has(t)}function NPe(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var iEt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function BPe(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=iEt[o]??(fU(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jPe(e,t,r){let n=BPe(t,r,new Date),i=VT.extname(n),o=n.slice(0,n.length-i.length);return VT.join(e,`${o}-${(0,eEt.randomBytes)(8).toString("hex")}${i}`)}function UPe(e){pf.mkdirSync(e,{recursive:!0,mode:448})}function CPe(e,t){let r=0;for(;r<t.length;){let n=pf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function qte(e,t,r,n,i){let o=r?fU(r):NPe(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=RPe)return{...s,body:n.toString("utf-8")};UPe(i);let a=jPe(i,e,r);return pf.writeFileSync(a,n,{flag:"wx",mode:384}),Lte(i,Dte,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Mte).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function oEt(e,t,r,n={}){let i=n.maxBytes??tEt,o=n.timeoutMs??rEt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return qte(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(pf.closeSync(p),p=null)},E=()=>{if(v(),m)try{pf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((O,M)=>{x=setTimeout(()=>M(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),C;try{C=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(C.done)break;let T=Buffer.from(C.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Mte){let O=T.subarray(0,Math.min(T.length,Mte-y));h.push(Buffer.from(O)),y+=O.length}if(p===null){if(u.push(T),d+=T.length,d<=RPe)continue;UPe(r),f=jPe(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=pf.openSync(m,"wx",384);for(let O of u)CPe(p,O);u.length=0,d=0}else CPe(p,T)}if(p===null){let A=Buffer.concat(u,d);return qte(e,t.status,t.headers.get("content-type"),A,r)}v(),pf.renameSync(m,f),m=null,Lte(r,Dte,f);let _=t.headers.get("content-type"),w=_?fU(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var gy=g(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.TURNKEY_API_BASE_URL_ENV=so.CIRCLE_TESTNET_FAUCET_URL=so.NETWORK_ENV=so.NETWORKS=void 0;so.resolveNetwork=sEt;so.turnkeyApiBaseUrl=cEt;so.explorerTxUrl=uEt;so.explorerAddressUrl=dEt;so.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};so.NETWORK_ENV="VISA_V4_NETWORK";so.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var MPe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function sEt(e=process.env){let t=(e[so.NETWORK_ENV]??"").trim();if(t==="")return so.NETWORKS["base-mainnet"];let r=MPe[t.toLowerCase()];if(!r)throw new Error(`unknown ${so.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(MPe).join(", "));return so.NETWORKS[r]}so.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var aEt="https://api.turnkey.com";function cEt(e=process.env){let t=(e[so.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?aEt:t}function uEt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function dEt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qPe=g(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0});mU.version=void 0;mU.version="1.2.3"});var Y_=g(hU=>{"use strict";Object.defineProperty(hU,"__esModule",{value:!0});hU.BaseError=void 0;var lEt=qPe(),Hte=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${lEt.version}`].join(`
181
181
  `);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};hU.BaseError=Hte});var DPe=g(Fte=>{"use strict";Object.defineProperty(Fte,"__esModule",{value:!0});Fte.narrow=pEt;function pEt(e){return e}});var $T=g(O0=>{"use strict";Object.defineProperty(O0,"__esModule",{value:!0});O0.isTupleRegex=O0.integerRegex=O0.bytesRegex=void 0;O0.execTyped=fEt;function fEt(e,t){return e.exec(t)?.groups}O0.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;O0.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;O0.isTupleRegex=/^\(.+?\).*?$/});var Kte=g($te=>{"use strict";Object.defineProperty($te,"__esModule",{value:!0});$te.formatAbiParameter=Vte;var mEt=$T(),LPe=/^tuple(?<array>(\[(\d*)\])*)$/;function Vte(e){let t=e.type;if(LPe.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=Vte(o),i<r-1&&(t+=", ")}let n=(0,mEt.execTyped)(LPe,e.type);return t+=`)${n?.array||""}`,Vte({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var Gte=g(Wte=>{"use strict";Object.defineProperty(Wte,"__esModule",{value:!0});Wte.formatAbiParameters=yEt;var hEt=Kte();function yEt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,hEt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var Yte=g(Jte=>{"use strict";Object.defineProperty(Jte,"__esModule",{value:!0});Jte.formatAbiItem=gEt;var KT=Gte();function gEt(e){return e.type==="function"?`function ${e.name}(${(0,KT.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,KT.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,KT.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,KT.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,KT.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var zPe=g(Zte=>{"use strict";Object.defineProperty(Zte,"__esModule",{value:!0});Zte.formatAbi=_Et;var bEt=Yte();function _Et(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,bEt.formatAbiItem)(i);t.push(o)}return t}});var Z_=g(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.functionModifiers=xi.eventModifiers=xi.modifiers=void 0;xi.isErrorSignature=vEt;xi.execErrorSignature=wEt;xi.isEventSignature=EEt;xi.execEventSignature=AEt;xi.isFunctionSignature=xEt;xi.execFunctionSignature=SEt;xi.isStructSignature=TEt;xi.execStructSignature=IEt;xi.isConstructorSignature=PEt;xi.execConstructorSignature=OEt;xi.isFallbackSignature=CEt;xi.execFallbackSignature=kEt;xi.isReceiveSignature=NEt;var i8=$T(),HPe=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function vEt(e){return HPe.test(e)}function wEt(e){return(0,i8.execTyped)(HPe,e)}var FPe=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function EEt(e){return FPe.test(e)}function AEt(e){return(0,i8.execTyped)(FPe,e)}var VPe=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function xEt(e){return VPe.test(e)}function SEt(e){return(0,i8.execTyped)(VPe,e)}var $Pe=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function TEt(e){return $Pe.test(e)}function IEt(e){return(0,i8.execTyped)($Pe,e)}var KPe=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function PEt(e){return KPe.test(e)}function OEt(e){return(0,i8.execTyped)(KPe,e)}var WPe=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function CEt(e){return WPe.test(e)}function kEt(e){return(0,i8.execTyped)(WPe,e)}var REt=/^receive\(\) external payable$/;function NEt(e){return REt.test(e)}xi.modifiers=new Set(["memory","indexed","storage","calldata"]);xi.eventModifiers=new Set(["indexed"]);xi.functionModifiers=new Set(["calldata","memory","storage"])});var WT=g(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});by.UnknownSolidityTypeError=by.UnknownTypeError=by.InvalidAbiItemError=void 0;var tre=Y_(),Xte=class extends tre.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};by.InvalidAbiItemError=Xte;var Qte=class extends tre.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};by.UnknownTypeError=Qte;var ere=class extends tre.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};by.UnknownSolidityTypeError=ere});var o8=g(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.InvalidAbiTypeParameterError=zs.InvalidFunctionModifierError=zs.InvalidModifierError=zs.SolidityProtectedKeywordError=zs.InvalidParameterError=zs.InvalidAbiParametersError=zs.InvalidAbiParameterError=void 0;var X_=Y_(),rre=class extends X_.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};zs.InvalidAbiParameterError=rre;var nre=class extends X_.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};zs.InvalidAbiParametersError=nre;var ire=class extends X_.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};zs.InvalidParameterError=ire;var ore=class extends X_.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};zs.SolidityProtectedKeywordError=ore;var sre=class extends X_.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};zs.InvalidModifierError=sre;var are=class extends X_.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};zs.InvalidFunctionModifierError=are;var cre=class extends X_.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};zs.InvalidAbiTypeParameterError=cre});var yU=g(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});_y.InvalidStructSignatureError=_y.UnknownSignatureError=_y.InvalidSignatureError=void 0;var pre=Y_(),ure=class extends pre.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};_y.InvalidSignatureError=ure;var dre=class extends pre.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};_y.UnknownSignatureError=dre;var lre=class extends pre.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};_y.InvalidStructSignatureError=lre});var mre=g(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0});gU.CircularReferenceError=void 0;var BEt=Y_(),fre=class extends BEt.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};gU.CircularReferenceError=fre});var yre=g(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0});bU.InvalidParenthesisError=void 0;var jEt=Y_(),hre=class extends jEt.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};bU.InvalidParenthesisError=hre});var GPe=g(GT=>{"use strict";Object.defineProperty(GT,"__esModule",{value:!0});GT.parameterCache=void 0;GT.getParameterCacheKey=UEt;function UEt(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}GT.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var e6=g(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.parseSignature=DEt;au.parseFunctionSignature=JPe;au.parseEventSignature=YPe;au.parseErrorSignature=ZPe;au.parseConstructorSignature=XPe;au.parseFallbackSignature=QPe;au.parseAbiParameter=Q_;au.splitParameters=md;au.isSolidityType=eOe;au.isSolidityKeyword=tOe;au.isValidDataLocation=rOe;var s8=$T(),MEt=WT(),_U=o8(),a8=yU(),qEt=yre(),vU=GPe(),ga=Z_();function DEt(e,t={}){if((0,ga.isFunctionSignature)(e))return JPe(e,t);if((0,ga.isEventSignature)(e))return YPe(e,t);if((0,ga.isErrorSignature)(e))return ZPe(e,t);if((0,ga.isConstructorSignature)(e))return XPe(e,t);if((0,ga.isFallbackSignature)(e))return QPe(e);if((0,ga.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new a8.UnknownSignatureError({signature:e})}function JPe(e,t={}){let r=(0,ga.execFunctionSignature)(e);if(!r)throw new a8.InvalidSignatureError({signature:e,type:"function"});let n=md(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(Q_(n[a],{modifiers:ga.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=md(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(Q_(a[u],{modifiers:ga.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function YPe(e,t={}){let r=(0,ga.execEventSignature)(e);if(!r)throw new a8.InvalidSignatureError({signature:e,type:"event"});let n=md(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Q_(n[s],{modifiers:ga.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function ZPe(e,t={}){let r=(0,ga.execErrorSignature)(e);if(!r)throw new a8.InvalidSignatureError({signature:e,type:"error"});let n=md(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Q_(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function XPe(e,t={}){let r=(0,ga.execConstructorSignature)(e);if(!r)throw new a8.InvalidSignatureError({signature:e,type:"constructor"});let n=md(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Q_(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function QPe(e){let t=(0,ga.execFallbackSignature)(e);if(!t)throw new a8.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var LEt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,zEt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,HEt=/^u?int$/;function Q_(e,t){let r=(0,vU.getParameterCacheKey)(e,t?.type,t?.structs);if(vU.parameterCache.has(r))return vU.parameterCache.get(r);let n=s8.isTupleRegex.test(e),i=(0,s8.execTyped)(n?zEt:LEt,e);if(!i)throw new _U.InvalidParameterError({param:e});if(i.name&&tOe(i.name))throw new _U.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=md(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(Q_(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(HEt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!eOe(c))throw new MEt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new _U.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(ga.functionModifiers.has(i.modifier)&&!rOe(c,!!i.array))throw new _U.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return vU.parameterCache.set(r,d),d}function md(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?md(a,[...t,r.trim()]):md(a,t,`${r}${s}`,n);case"(":return md(a,t,`${r}${s}`,n+1);case")":return md(a,t,`${r}${s}`,n-1);default:return md(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new qEt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function eOe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||s8.bytesRegex.test(e)||s8.integerRegex.test(e)}var FEt=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function tOe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||s8.bytesRegex.test(e)||s8.integerRegex.test(e)||FEt.test(e)}function rOe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var JT=g(gre=>{"use strict";Object.defineProperty(gre,"__esModule",{value:!0});gre.parseStructs=WEt;var nOe=$T(),VEt=WT(),$Et=o8(),iOe=yU(),KEt=mre(),oOe=Z_(),sOe=e6();function WEt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,oOe.isStructSignature)(a))continue;let c=(0,oOe.execStructSignature)(a);if(!c)throw new iOe.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let p=0;p<l;p++){let m=u[p].trim();if(!m)continue;let h=(0,sOe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new iOe.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=aOe(c,t)}return n}var GEt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function aOe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(nOe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,nOe.execTyped)(GEt,s.type);if(!c?.type)throw new $Et.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new KEt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:aOe(t[d],t,new Set([...r,d]))})}else if((0,sOe.isSolidityType)(d))n.push(s);else throw new VEt.UnknownTypeError({type:d})}}return n}});var cOe=g(bre=>{"use strict";Object.defineProperty(bre,"__esModule",{value:!0});bre.parseAbi=XEt;var JEt=Z_(),YEt=JT(),ZEt=e6();function XEt(e){let t=(0,YEt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,JEt.isStructSignature)(o)||r.push((0,ZEt.parseSignature)(o,t))}return r}});var dOe=g(_re=>{"use strict";Object.defineProperty(_re,"__esModule",{value:!0});_re.parseAbiItem=rAt;var QEt=WT(),eAt=Z_(),tAt=JT(),uOe=e6();function rAt(e){let t;if(typeof e=="string")t=(0,uOe.parseSignature)(e);else{let r=(0,tAt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,eAt.isStructSignature)(o)){t=(0,uOe.parseSignature)(o,r);break}}}if(!t)throw new QEt.InvalidAbiItemError({signature:e});return t}});var pOe=g(wre=>{"use strict";Object.defineProperty(wre,"__esModule",{value:!0});wre.parseAbiParameter=oAt;var nAt=o8(),vre=Z_(),iAt=JT(),lOe=e6();function oAt(e){let t;if(typeof e=="string")t=(0,lOe.parseAbiParameter)(e,{modifiers:vre.modifiers});else{let r=(0,iAt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,vre.isStructSignature)(o)){t=(0,lOe.parseAbiParameter)(o,{modifiers:vre.modifiers,structs:r});break}}}if(!t)throw new nAt.InvalidAbiParameterError({param:e});return t}});var hOe=g(Are=>{"use strict";Object.defineProperty(Are,"__esModule",{value:!0});Are.parseAbiParameters=cAt;var sAt=o8(),Ere=Z_(),aAt=JT(),fOe=e6(),mOe=e6();function cAt(e){let t=[];if(typeof e=="string"){let r=(0,fOe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,mOe.parseAbiParameter)(r[i],{modifiers:Ere.modifiers}))}else{let r=(0,aAt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,Ere.isStructSignature)(o))continue;let s=(0,fOe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,mOe.parseAbiParameter)(s[c],{modifiers:Ere.modifiers,structs:r}))}}if(t.length===0)throw new sAt.InvalidAbiParametersError({params:e});return t}});var YT=g(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.CircularReferenceError=lt.InvalidParenthesisError=lt.UnknownSignatureError=lt.InvalidSignatureError=lt.InvalidStructSignatureError=lt.InvalidAbiParameterError=lt.InvalidAbiParametersError=lt.InvalidParameterError=lt.SolidityProtectedKeywordError=lt.InvalidModifierError=lt.InvalidFunctionModifierError=lt.InvalidAbiTypeParameterError=lt.UnknownSolidityTypeError=lt.InvalidAbiItemError=lt.UnknownTypeError=lt.parseAbiParameters=lt.parseAbiParameter=lt.parseAbiItem=lt.parseAbi=lt.formatAbiParameters=lt.formatAbiParameter=lt.formatAbiItem=lt.formatAbi=lt.narrow=lt.BaseError=void 0;var uAt=Y_();Object.defineProperty(lt,"BaseError",{enumerable:!0,get:function(){return uAt.BaseError}});var dAt=DPe();Object.defineProperty(lt,"narrow",{enumerable:!0,get:function(){return dAt.narrow}});var lAt=zPe();Object.defineProperty(lt,"formatAbi",{enumerable:!0,get:function(){return lAt.formatAbi}});var pAt=Yte();Object.defineProperty(lt,"formatAbiItem",{enumerable:!0,get:function(){return pAt.formatAbiItem}});var fAt=Kte();Object.defineProperty(lt,"formatAbiParameter",{enumerable:!0,get:function(){return fAt.formatAbiParameter}});var mAt=Gte();Object.defineProperty(lt,"formatAbiParameters",{enumerable:!0,get:function(){return mAt.formatAbiParameters}});var hAt=cOe();Object.defineProperty(lt,"parseAbi",{enumerable:!0,get:function(){return hAt.parseAbi}});var yAt=dOe();Object.defineProperty(lt,"parseAbiItem",{enumerable:!0,get:function(){return yAt.parseAbiItem}});var gAt=pOe();Object.defineProperty(lt,"parseAbiParameter",{enumerable:!0,get:function(){return gAt.parseAbiParameter}});var bAt=hOe();Object.defineProperty(lt,"parseAbiParameters",{enumerable:!0,get:function(){return bAt.parseAbiParameters}});var xre=WT();Object.defineProperty(lt,"UnknownTypeError",{enumerable:!0,get:function(){return xre.UnknownTypeError}});Object.defineProperty(lt,"InvalidAbiItemError",{enumerable:!0,get:function(){return xre.InvalidAbiItemError}});Object.defineProperty(lt,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return xre.UnknownSolidityTypeError}});var t6=o8();Object.defineProperty(lt,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return t6.InvalidAbiTypeParameterError}});Object.defineProperty(lt,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return t6.InvalidFunctionModifierError}});Object.defineProperty(lt,"InvalidModifierError",{enumerable:!0,get:function(){return t6.InvalidModifierError}});Object.defineProperty(lt,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return t6.SolidityProtectedKeywordError}});Object.defineProperty(lt,"InvalidParameterError",{enumerable:!0,get:function(){return t6.InvalidParameterError}});Object.defineProperty(lt,"InvalidAbiParametersError",{enumerable:!0,get:function(){return t6.InvalidAbiParametersError}});Object.defineProperty(lt,"InvalidAbiParameterError",{enumerable:!0,get:function(){return t6.InvalidAbiParameterError}});var Sre=yU();Object.defineProperty(lt,"InvalidStructSignatureError",{enumerable:!0,get:function(){return Sre.InvalidStructSignatureError}});Object.defineProperty(lt,"InvalidSignatureError",{enumerable:!0,get:function(){return Sre.InvalidSignatureError}});Object.defineProperty(lt,"UnknownSignatureError",{enumerable:!0,get:function(){return Sre.UnknownSignatureError}});var _At=yre();Object.defineProperty(lt,"InvalidParenthesisError",{enumerable:!0,get:function(){return _At.InvalidParenthesisError}});var vAt=mre();Object.defineProperty(lt,"CircularReferenceError",{enumerable:!0,get:function(){return vAt.CircularReferenceError}})});var rr=g(Tre=>{"use strict";Object.defineProperty(Tre,"__esModule",{value:!0});Tre.getAction=wAt;function wAt(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var ff=g(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0});wU.formatAbiItem=AAt;wU.formatAbiParams=Ire;var EAt=Un();function AAt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new EAt.InvalidDefinitionTypeError(e.type);return`${e.name}(${Ire(e.inputs,{includeName:t})})`}function Ire(e,{includeName:t=!1}={}){return e?e.map(r=>xAt(r,{includeName:t})).join(t?", ":","):""}function xAt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Ire(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var is=g(Pre=>{"use strict";Object.defineProperty(Pre,"__esModule",{value:!0});Pre.isHex=SAt;function SAt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var os=g(Ore=>{"use strict";Object.defineProperty(Ore,"__esModule",{value:!0});Ore.size=IAt;var TAt=is();function IAt(e){return(0,TAt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var yOe=g(EU=>{"use strict";Object.defineProperty(EU,"__esModule",{value:!0});EU.version=void 0;EU.version="2.54.6"});var It=g(ZT=>{"use strict";Object.defineProperty(ZT,"__esModule",{value:!0});ZT.BaseError=void 0;ZT.setErrorConfig=PAt;var gOe=yOe(),AU={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${gOe.version}`};function PAt(e){AU=e}var Cre=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=AU.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...AU.version?[`Version: ${AU.version}`]:[]].join(`
182
182
  `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=gOe.version}walk(t){return bOe(this,t)}};ZT.BaseError=Cre;function bOe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?bOe(e.cause,t):t?null:e}});var Un=g(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.UnsupportedPackedAbiType=ut.InvalidDefinitionTypeError=ut.InvalidArrayError=ut.InvalidAbiDecodingTypeError=ut.InvalidAbiEncodingTypeError=ut.DecodeLogTopicsMismatch=ut.DecodeLogDataMismatch=ut.BytesSizeMismatchError=ut.AbiItemAmbiguityError=ut.AbiFunctionSignatureNotFoundError=ut.AbiFunctionOutputsNotFoundError=ut.AbiFunctionNotFoundError=ut.AbiEventNotFoundError=ut.AbiEventSignatureNotFoundError=ut.AbiEventSignatureEmptyTopicsError=ut.AbiErrorSignatureNotFoundError=ut.AbiErrorNotFoundError=ut.AbiErrorInputsNotFoundError=ut.AbiEncodingLengthMismatchError=ut.AbiEncodingBytesSizeMismatchError=ut.AbiEncodingArrayLengthMismatchError=ut.AbiDecodingZeroDataError=ut.AbiDecodingDataSizeTooSmallError=ut.AbiDecodingDataSizeInvalidError=ut.AbiConstructorParamsNotFoundError=ut.AbiConstructorNotFoundError=void 0;var XT=ff(),OAt=os(),an=It(),kre=class extends an.BaseError{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
183
183
  `),{docsPath:t,name:"AbiConstructorNotFoundError"})}};ut.AbiConstructorNotFoundError=kre;var Rre=class extends an.BaseError{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
@@ -20825,7 +20825,7 @@ ${Object.entries(t).sort(([r],[n])=>a0t(r,n)).map(([r,n])=>`${r}=${n}`).join(`
20825
20825
  If building from source, run native/build-win.bat first.`);Yr.mkdirSync($h,{recursive:!0}),Yr.copyFileSync(e,d0);let t=PB(d0);return Yr.writeFileSync(C9e,t,{mode:384}),Yr.writeFileSync(O9e,P9e,{mode:384}),d0}async function Mbt(){return OB()?D9e():Ubt()}var qbt="visa-cli",Dbt="attestation-key";async function Lbt(e){let t=await Mbt(),r;try{r=(await IB(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 jbt(r)}var k9e=!1;function zbt(){if(!OB())return!1;try{return Yr.existsSync(d0)||q9e()!==null?!0:(k9e||(k9e=!0,Ne.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:d0,searchedPrebuiltPaths:M9e})),!1)}catch{return!1}}function L9e(){return wB()||Bbt()?!0:OB()?zbt():!1}async function z9e(){if(OB()){try{let e=await D9e();await IB(e,["delete-key"],{timeout:1e4})}catch{}return}if(await Vh())try{await IB("security",["delete-generic-password","-s",qbt,"-a",Dbt],{timeout:5e3})}catch{}try{await Lbt(["delete-key"])}catch{}}g4();Sl();lQ();yj();ay();var EPe=require("child_process"),dU=Me(require("fs")),lU=Me(require("os")),APe=Me(require("path"));var cf=Me(require("fs")),Vj=Me(require("os")),Ol=Me(require("path"));var nwt="# >>> visa-cli shell hud v2 >>>",iwt="# <<< visa-cli shell hud v2 <<<";function owt(e){let t=e??process.env.SHELL;if(!t)return null;let r=Ol.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 swt(e){let t=lwt();if(e==="zsh")return Ol.join(t,".zshrc");if(e==="bash")return Ol.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return Ol.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function awt(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 cwt(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${Y7e(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Y7e(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!awt(a))return i;let l=d>0?e[d-1]:"";return o===`
20826
20826
  `&&l!==`
20827
20827
  `?`
20828
- `:""})}function uwt(e){return cwt(e,nwt,iwt).trimEnd()}function dwt(e){return uwt(e)!==e.trimEnd()}function $j(e=owt()){if(!e)return!1;try{let t=swt(e),r=cf.readFileSync(t,"utf-8");return dwt(r)}catch{return!1}}function Y7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lwt(){let e=Vj.homedir();if(!e||!Ol.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Ol.resolve(e)}var mRr=1440*60*1e3;var pwt="# visa-cli-hud-v1";function Z7e(e){return typeof e!="string"?!1:e.includes(pwt)?!0:e.includes("visa-cli")&&e.includes("statusline")}FX();m4();EB();var X7e="4.1.0-rc.56";function dte(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function fwt(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=ZX(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function D4(e){return e==null?"\u2014":e?"yes":"no"}async function Q7e(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=YX("auth.serverUrl"),s=rd(),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:D4(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=fwt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:D4(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=fB(),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:D4(!u),source:d}),n.push({key:"client.version",value:X7e,formatted:X7e,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=zh();n.push({key:"dev.mockKeychain",value:p,formatted:D4(p),source:dte("VISA_MOCK_KEYCHAIN",!!l),hint:nQ()});let f=process.env.VISA_MOCK_TOUCHID,m=wB();n.push({key:"dev.mockTouchid",value:m,formatted:D4(m),source:dte("VISA_MOCK_TOUCHID",!!f),hint:nQ()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:D4(!!h),source:dte("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var vte=require("node:os"),OT=require("node:path"),CT=require("node:fs/promises"),pIe=require("node:fs"),fIe=require("node:url"),mIe=require("node:crypto");Sl();var mwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function lte(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!mwt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var w0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function eIe(e){let t;try{t=new URL(e)}catch{throw new w0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new w0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Sl();var hwt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},tIe=300*1e3,pte={},fte=0,IT=null;function mte(){return IT||(IT=(async()=>{try{let e=await xo.getFeatureFlags();pte=e&&e.flags||{},fte=Date.now()}catch(e){pte={},Ne.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{IT=null}})(),IT)}async function rIe(){await mte()}function nIe(){Date.now()-fte<tIe||mte()}async function k_(){Date.now()-fte<tIe||await mte()}function ou(e){let t=hwt[e];return t?pte[t]!==!0:!1}var iIe=require("node:crypto"),PT=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},Kj=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 PT(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??iIe.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 hIe(e){return[(0,OT.join)(e,"checkout-engine","index.js"),(0,OT.join)(e,"..","checkout-engine","index.js")]}function Swt(e,t=pIe.existsSync){return hIe(e).find(r=>t(r))??null}var Gj=null,yIe=async()=>{if(Gj)return Gj;let e=Swt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${hIe(__dirname).join(" and ")}).`);return Gj=(await import((0,fIe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await Twt(),cardMandateRegister:await Iwt()}),Gj};async function Twt(){let e=await Promise.resolve().then(()=>(bte(),gte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function Iwt(){let e=await Promise.resolve().then(()=>(bte(),gte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function wte(){return ou("pay_merchant")?(await k_(),ou("pay_merchant")):!1}var gIe=(0,OT.join)((0,vte.homedir)(),".visa-mcp","agent-credential.json"),bIe=(0,OT.join)((0,vte.homedir)(),".visa-mcp","contact.json"),_Ie=new Kj;function kT(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var Pwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function vIe(e){return Pwt.has(e)?e:null}async function Jj(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?kT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0&&e.source!=="mandate"?e.amountMinor/100:null,payment_currency:vIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function lIe(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?kT(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:vIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function _te(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new w0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function wIe(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=kT(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 EIe(e={},t={}){if(await(t.flagDisabled??wte)())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??_Ie).get(n);return o?wIe(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 AIe(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:QX()&&!process.env.VISA_VERIFY_WEB_URL?null:Lh();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??wte)())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??_Ie,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=eIe(e.url??"").toString(),c=_te(e.amount)}catch(C){if(C instanceof w0)return{success:!1,message:C.message};throw C}let d=t.credentialPath??gIe,l=t.contactPath??bIe;try{await(0,CT.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,CT.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(C);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??yIe,y;try{y=await h()}catch(C){let T=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(C=>xo.emitTelemetry(C)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ne.info("pay_merchant:review",{host:_,currency:u});let C;try{C=await y.review(v)}catch(T){throw await Jj({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await Jj({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${lte(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async C=>{Ne.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...C?{onApprovalUrl:C}:{}})}catch(j){throw await Jj({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",M=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await Jj({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:O,errorMessage:O?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:M,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let U=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:O,action:"pay",reviewId:x,...T,paymentStatus:M,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${U}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${U}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,mIe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ne.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:C,run:async O=>{try{let M=await S(U=>{Ne.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(U)});return Ne.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:M.success===!0}),M}catch(M){throw Ne.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:kT(M instanceof Error?M.message:String(M))}),M}}});return wIe(T,"authorize")}catch(T){if(T instanceof PT)return Ne.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function xIe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:Lh();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??wte)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=_te(e.ceiling)}catch(_){if(_ instanceof w0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=_te(e.perTransaction)}catch(_){if(_ instanceof w0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??gIe,u=t.contactPath??bIe;try{await(0,CT.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,CT.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??yIe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>xo.emitTelemetry(_)),y=Date.now();Ne.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?kT(_.message):String(_);return Ne.warn("start_card_mandate:failed",{message:w}),await lIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ne.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await lIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${lte(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var yPe=require("node:crypto");var pPe=require("node:crypto");var Ur={};Ai(Ur,{BRAND:()=>e4t,DIRTY:()=>N_,EMPTY_PATH:()=>Rwt,INVALID:()=>yt,NEVER:()=>C4t,OK:()=>Ls,ParseStatus:()=>ns,Schema:()=>qt,ZodAny:()=>fy,ZodArray:()=>S0,ZodBigInt:()=>j_,ZodBoolean:()=>U_,ZodBranded:()=>NT,ZodCatch:()=>W_,ZodDate:()=>M_,ZodDefault:()=>K_,ZodDiscriminatedUnion:()=>Xj,ZodEffects:()=>dd,ZodEnum:()=>V_,ZodError:()=>ec,ZodFirstPartyTypeKind:()=>Et,ZodFunction:()=>eU,ZodIntersection:()=>z_,ZodIssueCode:()=>ye,ZodLazy:()=>H_,ZodLiteral:()=>F_,ZodMap:()=>$4,ZodNaN:()=>W4,ZodNativeEnum:()=>$_,ZodNever:()=>Cl,ZodNull:()=>D_,ZodNullable:()=>lf,ZodNumber:()=>B_,ZodObject:()=>tc,ZodOptional:()=>cd,ZodParsedType:()=>Be,ZodPipeline:()=>BT,ZodPromise:()=>my,ZodReadonly:()=>G_,ZodRecord:()=>Qj,ZodSchema:()=>qt,ZodSet:()=>K4,ZodString:()=>py,ZodSymbol:()=>F4,ZodTransformer:()=>dd,ZodTuple:()=>df,ZodType:()=>qt,ZodUndefined:()=>q_,ZodUnion:()=>L_,ZodUnknown:()=>x0,ZodVoid:()=>V4,addIssueToContext:()=>Te,any:()=>pd,array:()=>ue,bigint:()=>i4t,boolean:()=>ld,coerce:()=>su,custom:()=>RIe,date:()=>o4t,datetimeRegex:()=>CIe,defaultErrorMap:()=>E0,discriminatedUnion:()=>p4t,effect:()=>E4t,enum:()=>fd,function:()=>g4t,getErrorMap:()=>L4,getParsedType:()=>uf,instanceof:()=>r4t,intersection:()=>f4t,isAborted:()=>Yj,isAsync:()=>z4,isDirty:()=>Zj,isValid:()=>ly,late:()=>t4t,lazy:()=>b4t,literal:()=>_4t,makeIssue:()=>RT,map:()=>h4t,nan:()=>n4t,nativeEnum:()=>v4t,never:()=>u4t,null:()=>G4,nullable:()=>x4t,number:()=>Tr,object:()=>fe,objectUtil:()=>Ete,oboolean:()=>O4t,onumber:()=>P4t,optional:()=>A4t,ostring:()=>I4t,pipeline:()=>T4t,preprocess:()=>S4t,promise:()=>w4t,quotelessJson:()=>Owt,record:()=>Jt,set:()=>y4t,setErrorMap:()=>kwt,strictObject:()=>l4t,string:()=>L,symbol:()=>s4t,transformer:()=>E4t,tuple:()=>m4t,undefined:()=>a4t,union:()=>J4,unknown:()=>c4t,util:()=>Gt,void:()=>d4t});var Gt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Gt||(Gt={}));var Ete;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ete||(Ete={}));var Be=Gt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),uf=e=>{switch(typeof e){case"undefined":return Be.undefined;case"string":return Be.string;case"number":return Number.isNaN(e)?Be.nan:Be.number;case"boolean":return Be.boolean;case"function":return Be.function;case"bigint":return Be.bigint;case"symbol":return Be.symbol;case"object":return Array.isArray(e)?Be.array:e===null?Be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Be.promise:typeof Map<"u"&&e instanceof Map?Be.map:typeof Set<"u"&&e instanceof Set?Be.set:typeof Date<"u"&&e instanceof Date?Be.date:Be.object;default:return Be.unknown}};var ye=Gt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Owt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ec=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ec.create=e=>new ec(e);var Cwt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Be.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Gt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Gt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gt.assertNever(e)}return{message:r}},E0=Cwt;var SIe=E0;function kwt(e){SIe=e}function L4(){return SIe}var RT=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}},Rwt=[];function Te(e,t){let r=L4(),n=RT({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===E0?void 0:E0].filter(i=>!!i)});e.common.issues.push(n)}var ns=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return yt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return yt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},yt=Object.freeze({status:"aborted"}),N_=e=>({status:"dirty",value:e}),Ls=e=>({status:"valid",value:e}),Yj=e=>e.status==="aborted",Zj=e=>e.status==="dirty",ly=e=>e.status==="valid",z4=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var ud=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}},TIe=(e,t)=>{if(ly(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 ec(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return uf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:uf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ns,ctx:{common:t.parent.common,data:t.data,parsedType:uf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(z4(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:uf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return TIe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:uf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return ly(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=>ly(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:uf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(z4(i)?i:Promise.resolve(i));return TIe(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 dd({schema:this,typeName:Et.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return cd.create(this,this._def)}nullable(){return lf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return S0.create(this)}promise(){return my.create(this,this._def)}or(t){return L_.create([this,t],this._def)}and(t){return z_.create(this,t,this._def)}transform(t){return new dd({...Bt(this._def),schema:this,typeName:Et.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new K_({...Bt(this._def),innerType:this,defaultValue:r,typeName:Et.ZodDefault})}brand(){return new NT({typeName:Et.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new W_({...Bt(this._def),innerType:this,catchValue:r,typeName:Et.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return BT.create(this,t)}readonly(){return G_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Nwt=/^c[^\s-]{8,}$/i,Bwt=/^[0-9a-z]+$/,jwt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Uwt=/^[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,Mwt=/^[a-z0-9_-]{21}$/i,qwt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Dwt=/^[-+]?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)?)??$/,Lwt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zwt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ate,Hwt=/^(?:(?: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])$/,Fwt=/^(?:(?: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])$/,Vwt=/^(([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]))$/,$wt=/^(([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])$/,Kwt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wwt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,PIe="((\\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])))",Gwt=new RegExp(`^${PIe}$`);function OIe(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 Jwt(e){return new RegExp(`^${OIe(e)}$`)}function CIe(e){let t=`${PIe}T${OIe(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 Ywt(e,t){return!!((t==="v4"||!t)&&Hwt.test(e)||(t==="v6"||!t)&&Vwt.test(e))}function Zwt(e,t){if(!qwt.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 Xwt(e,t){return!!((t==="v4"||!t)&&Fwt.test(e)||(t==="v6"||!t)&&$wt.test(e))}var py=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),yt}let n=new ns,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Lwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ate||(Ate=new RegExp(zwt,"u")),Ate.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Uwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Mwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Nwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Bwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")jwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Te(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?CIe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Gwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Jwt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Dwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Ywt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Zwt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Xwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Kwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Wwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...et.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};py.create=e=>new py({checks:[],typeName:Et.ZodString,coerce:e?.coerce??!1,...Bt(e)});function Qwt(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 B_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Be.number){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),yt}let n,i=new ns;for(let o of this._def.checks)o.kind==="int"?Gt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Qwt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Gt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};B_.create=e=>new B_({checks:[],typeName:Et.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var j_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Be.bigint)return this._getInvalidInput(t);let n,i=new ns;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),yt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};j_.create=e=>new j_({checks:[],typeName:Et.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var U_=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),yt}return Ls(t.data)}};U_.create=e=>new U_({typeName:Et.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var M_=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),yt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),yt}let n=new ns,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};M_.create=e=>new M_({checks:[],coerce:e?.coerce||!1,typeName:Et.ZodDate,...Bt(e)});var F4=class extends qt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),yt}return Ls(t.data)}};F4.create=e=>new F4({typeName:Et.ZodSymbol,...Bt(e)});var q_=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),yt}return Ls(t.data)}};q_.create=e=>new q_({typeName:Et.ZodUndefined,...Bt(e)});var D_=class extends qt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),yt}return Ls(t.data)}};D_.create=e=>new D_({typeName:Et.ZodNull,...Bt(e)});var fy=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ls(t.data)}};fy.create=e=>new fy({typeName:Et.ZodAny,...Bt(e)});var x0=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ls(t.data)}};x0.create=e=>new x0({typeName:Et.ZodUnknown,...Bt(e)});var Cl=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),yt}};Cl.create=e=>new Cl({typeName:Et.ZodNever,...Bt(e)});var V4=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),yt}return Ls(t.data)}};V4.create=e=>new V4({typeName:Et.ZodVoid,...Bt(e)});var S0=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Te(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),yt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Te(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Te(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ud(r,s,r.path,a)))).then(s=>ns.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new ud(r,s,r.path,a)));return ns.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};S0.create=(e,t)=>new S0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Et.ZodArray,...Bt(t)});function H4(e){if(e instanceof tc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=cd.create(H4(n))}return new tc({...e._def,shape:()=>t})}else return e instanceof S0?new S0({...e._def,type:H4(e.element)}):e instanceof cd?cd.create(H4(e.unwrap())):e instanceof lf?lf.create(H4(e.unwrap())):e instanceof df?df.create(e.items.map(t=>H4(t))):e}var tc=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Gt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Be.object){let u=this._getOrReturnCtx(t);return Te(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),yt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Cl&&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 ud(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Cl){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Te(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new ud(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=>ns.mergeObjectSync(n,u)):ns.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Et.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Gt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Gt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return H4(this)}partial(t){let r={};for(let n of Gt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Gt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof cd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return kIe(Gt.objectKeys(this.shape))}};tc.create=(e,t)=>new tc({shape:()=>e,unknownKeys:"strip",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});tc.strictCreate=(e,t)=>new tc({shape:()=>e,unknownKeys:"strict",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});tc.lazycreate=(e,t)=>new tc({shape:e,unknownKeys:"strip",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});var L_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new ec(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),yt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new ec(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),yt}}get options(){return this._def.options}};L_.create=(e,t)=>new L_({options:e,typeName:Et.ZodUnion,...Bt(t)});var A0=e=>e instanceof H_?A0(e.schema):e instanceof dd?A0(e.innerType()):e instanceof F_?[e.value]:e instanceof V_?e.options:e instanceof $_?Gt.objectValues(e.enum):e instanceof K_?A0(e._def.innerType):e instanceof q_?[void 0]:e instanceof D_?[null]:e instanceof cd?[void 0,...A0(e.unwrap())]:e instanceof lf?[null,...A0(e.unwrap())]:e instanceof NT||e instanceof G_?A0(e.unwrap()):e instanceof W_?A0(e._def.innerType):[],Xj=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Te(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),yt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=A0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Et.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function xte(e,t){let r=uf(e),n=uf(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Gt.objectKeys(t),o=Gt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=xte(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Be.array&&n===Be.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=xte(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Be.date&&n===Be.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var z_=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Yj(o)||Yj(s))return yt;let a=xte(o.value,s.value);return a.valid?((Zj(o)||Zj(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),yt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};z_.create=(e,t,r)=>new z_({left:e,right:t,typeName:Et.ZodIntersection,...Bt(r)});var df=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Te(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),yt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ud(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ns.mergeArray(r,s)):ns.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};df.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new df({items:e,typeName:Et.ZodTuple,rest:null,...Bt(t)})};var Qj=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.object)return Te(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),yt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new ud(n,a,n.path,a)),value:s._parse(new ud(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ns.mergeObjectAsync(r,i):ns.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:Et.ZodRecord,...Bt(n)}):new e({keyType:py.create(),valueType:t,typeName:Et.ZodRecord,...Bt(r)})}},$4=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.map)return Te(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),yt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new ud(n,a,n.path,[u,"key"])),value:o._parse(new ud(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};$4.create=(e,t,r)=>new $4({valueType:t,keyType:e,typeName:Et.ZodMap,...Bt(r)});var K4=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Te(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),yt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Te(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return yt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new ud(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};K4.create=(e,t)=>new K4({valueType:e,minSize:null,maxSize:null,typeName:Et.ZodSet,...Bt(t)});var eU=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Te(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),yt;function n(a,c){return RT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,L4(),E0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return RT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,L4(),E0].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 my){let a=this;return Ls(async function(...c){let u=new ec([]),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 Ls(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new ec([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new ec([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:df.create(t).rest(x0.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||df.create([]).rest(x0.create()),returns:r||x0.create(),typeName:Et.ZodFunction,...Bt(n)})}},H_=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};H_.create=(e,t)=>new H_({getter:e,typeName:Et.ZodLazy,...Bt(t)});var F_=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),yt}return{status:"valid",value:t.data}}get value(){return this._def.value}};F_.create=(e,t)=>new F_({value:e,typeName:Et.ZodLiteral,...Bt(t)});function kIe(e,t){return new V_({values:e,typeName:Et.ZodEnum,...Bt(t)})}var V_=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Gt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),yt}return Ls(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})}};V_.create=kIe;var $_=class extends qt{_parse(t){let r=Gt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Gt.objectValues(r);return Te(n,{expected:Gt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(Gt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Gt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),yt}return Ls(t.data)}get enum(){return this._def.values}};$_.create=(e,t)=>new $_({values:e,typeName:Et.ZodNativeEnum,...Bt(t)});var my=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),yt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ls(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};my.create=(e,t)=>new my({type:e,typeName:Et.ZodPromise,...Bt(t)});var dd=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Et.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Te(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return yt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?yt:c.status==="dirty"?N_(c.value):r.value==="dirty"?N_(c.value):c});{if(r.value==="aborted")return yt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?yt:a.status==="dirty"?N_(a.value):r.value==="dirty"?N_(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ly(s))return yt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>ly(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):yt);Gt.assertNever(i)}};dd.create=(e,t,r)=>new dd({schema:e,typeName:Et.ZodEffects,effect:t,...Bt(r)});dd.createWithPreprocess=(e,t,r)=>new dd({schema:t,effect:{type:"preprocess",transform:e},typeName:Et.ZodEffects,...Bt(r)});var cd=class extends qt{_parse(t){return this._getType(t)===Be.undefined?Ls(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};cd.create=(e,t)=>new cd({innerType:e,typeName:Et.ZodOptional,...Bt(t)});var lf=class extends qt{_parse(t){return this._getType(t)===Be.null?Ls(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};lf.create=(e,t)=>new lf({innerType:e,typeName:Et.ZodNullable,...Bt(t)});var K_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Be.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};K_.create=(e,t)=>new K_({innerType:e,typeName:Et.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var W_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return z4(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ec(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ec(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};W_.create=(e,t)=>new W_({innerType:e,typeName:Et.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var W4=class extends qt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),yt}return{status:"valid",value:t.data}}};W4.create=e=>new W4({typeName:Et.ZodNaN,...Bt(e)});var e4t=Symbol("zod_brand"),NT=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},BT=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?yt:o.status==="dirty"?(r.dirty(),N_(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?yt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Et.ZodPipeline})}},G_=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(ly(i)&&(i.value=Object.freeze(i.value)),i);return z4(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};G_.create=(e,t)=>new G_({innerType:e,typeName:Et.ZodReadonly,...Bt(t)});function IIe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function RIe(e,t={},r){return e?fy.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=IIe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=IIe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):fy.create()}var t4t={object:tc.lazycreate},Et;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Et||(Et={}));var r4t=(e,t={message:`Input not instance of ${e.name}`})=>RIe(r=>r instanceof e,t),L=py.create,Tr=B_.create,n4t=W4.create,i4t=j_.create,ld=U_.create,o4t=M_.create,s4t=F4.create,a4t=q_.create,G4=D_.create,pd=fy.create,c4t=x0.create,u4t=Cl.create,d4t=V4.create,ue=S0.create,fe=tc.create,l4t=tc.strictCreate,J4=L_.create,p4t=Xj.create,f4t=z_.create,m4t=df.create,Jt=Qj.create,h4t=$4.create,y4t=K4.create,g4t=eU.create,b4t=H_.create,_4t=F_.create,fd=V_.create,v4t=$_.create,w4t=my.create,E4t=dd.create,A4t=cd.create,x4t=lf.create,S4t=dd.createWithPreprocess,T4t=BT.create,I4t=()=>L().optional(),P4t=()=>Tr().optional(),O4t=()=>ld().optional(),su={string:(e=>py.create({...e,coerce:!0})),number:(e=>B_.create({...e,coerce:!0})),boolean:(e=>U_.create({...e,coerce:!0})),bigint:(e=>j_.create({...e,coerce:!0})),date:(e=>M_.create({...e,coerce:!0}))};var C4t=yt;var R4t=fd(["enc","sig"]),N4t=fd(["markdown","plain"]),B4t=fd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),j4t=fd(["error","info","warning"]),X4=fd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),U4t=fd(["completed","failed","pending"]),M4t=fd(["digital","pickup","shipping"]),q4t=fd(["fulfilled","partial","processing","removed"]),D4t=fd(["across","each"]),Ste=fd(["pickup","shipping"]),L4t=fe({config:Jt(L(),pd()),config_schema:L(),id:L(),instrument_schemas:ue(L()),name:L(),spec:L(),version:L()}),z4t=fe({alg:L().optional(),crv:L().optional(),e:L().optional(),kid:L(),kty:L(),n:L().optional(),use:R4t.optional(),x:L().optional(),y:L().optional()}),H4t=fe({config:Jt(L(),pd()).optional(),extends:L().optional(),name:L(),schema:L(),spec:L(),version:L()}),F4t=fe({endpoint:L()}),V4t=fe({schema:L()}),NIe=fe({endpoint:L(),schema:L()}),$4t=NIe,K4t=NIe,ya=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional()}),io=fe({address_country:L().optional(),address_region:L().optional(),currency:L().optional(),eligibility:ue(L()).optional(),intent:L().optional(),language:L().optional(),postal_code:L().optional()}),Tte=io,BIe=fe({id:L()}),W4t=BIe,G4t=BIe,jT=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional()}),tU=fe({type:L()}),Di=fe({"dev.ucp.buyer_ip":L().optional(),"dev.ucp.user_agent":L().optional()}),Ite=Di,jIe=fe({id:L(),image_url:L().optional(),price:Tr(),title:L()}),rU=fe({amount:Tr(),display_text:L().optional(),type:L()}),hy=fe({title:L().optional(),type:L(),url:L()}),T0=fe({code:L().optional(),content:L(),content_type:N4t.optional(),path:L().optional(),severity:B4t.optional(),type:j4t,image_url:L().optional(),presentation:L().optional(),url:L().optional()}),Pte=T0,Q4=fe({id:L(),label:L().optional(),permalink_url:L()}),J4t=fe({amount:Tr(),display_text:L()}),Y4t=fe({config:Jt(L(),pd()).optional(),extends:L().optional(),name:L(),schema:L().optional(),spec:L().optional(),version:L()}),Ote=fe({id:L(),quantity:Tr()}),Z4t=Ote,X4t=Ote,Q4t=Ote,e8t=fe({fulfilled:Tr(),original:Tr().optional(),total:Tr()}),t8t=fe({billing_address:jT.optional(),credential:tU.optional(),display:Jt(L(),pd()).optional(),handler_id:L(),id:L(),type:L()}),r8t=fe({checkout_mandate:L()}),n8t=fe({merchant_authorization:L().optional(),checkout_mandate:L()}),i8t=fe({analytics:ld().optional(),marketing:ld().optional(),preferences:ld().optional(),sale_of_data:ld().optional()});var o8t=i8t;var UIe=fe({codes:ue(L()).optional()}),s8t=UIe,a8t=fe({amount:Tr(),path:L()}),c8t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L().optional(),address:jT.optional(),name:L().optional()}),u8t=fe({carrier:L().optional(),description:L().optional(),earliest_fulfillment_time:su.date().optional(),id:L(),latest_fulfillment_time:su.date().optional(),title:L(),totals:ue(rU)}),d8t=fe({description:L().optional(),fulfillable_on:J4([G4(),L()]).optional(),line_item_ids:ue(L()),type:Ste}),l8t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L(),address:jT.optional(),name:L().optional()}),p8t=fe({max:Tr().optional(),min:Tr().optional()}),UT=fe({taxonomy:L().optional(),value:L()}),MT=fe({html:L().optional(),markdown:L().optional(),plain:L().optional()}),Y4=fe({amount:Tr(),currency:L()}),qT=fe({alt_text:L().optional(),height:Tr().optional(),type:L(),url:L(),width:Tr().optional()}),f8t=fe({id:L().optional(),label:L()}),DT=fe({count:Tr().optional(),scale_max:Tr(),scale_min:Tr().optional(),value:Tr()}),MIe=fe({available:ld().optional(),status:L().optional()}),m8t=MIe,qIe=fe({type:L(),value:L()}),h8t=qIe,y8t=fe({id:L(),match:L().optional()}),Cte=fe({id:L().optional(),label:L(),name:L()}),DIe=Cte,LIe=fe({links:ue(hy).optional(),name:L().optional()}),g8t=LIe,zIe=fe({unit:L(),value:Tr()});var b8t=zIe,_8t=fe({cursor:L().optional(),limit:Tr().optional()}),v8t=fe({cursor:L().optional(),has_next_page:ld(),total_count:Tr().optional()}),w8t=fe({handlers:ue(L4t).optional()}),E8t=fe({a2a:F4t.optional(),embedded:V4t.optional(),mcp:$4t.optional(),rest:K4t.optional(),spec:L(),version:L()}),e8=fe({item:W4t,quantity:Tr()}),A8t=fe({billing_address:jT.optional(),credential:tU.optional(),display:Jt(L(),pd()).optional(),handler_id:L(),id:L(),type:L(),selected:ld().optional()}),LT=fe({id:L().optional(),item:G4t,parent_id:L().optional(),quantity:Tr()}),nU=fe({instruments:ue(A8t).optional()}),x8t=nU,zT=nU,t8=nU,iU=nU,J_=fe({id:L(),item:jIe,parent_id:L().optional(),quantity:Tr(),totals:ue(rU)}),yy=fe({amount:Tr(),display_text:L().optional(),type:L(),lines:ue(J4t).optional()}),kl=fe({capabilities:Jt(L(),ue(Y4t)),version:L()}),S8t=fe({description:L().optional(),id:L(),line_items:ue(Z4t).optional(),occurred_at:su.date(),status:U4t,totals:ue(rU).optional(),type:L()}),T8t=fe({carrier:L().optional(),description:L().optional(),id:L(),line_items:ue(X4t),occurred_at:su.date(),tracking_number:L().optional(),tracking_url:L().optional(),type:L()}),I8t=fe({description:L().optional(),destination:jT,fulfillable_on:L().optional(),id:L(),line_items:ue(Q4t),method_type:M4t}),P8t=fe({id:L(),item:jIe,parent_id:L().optional(),quantity:e8t,status:q4t,totals:ue(rU)}),oNr=fe({payment_data:t8t}),sNr=fe({ap2:r8t.optional()}),aNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,ap2:n8t.optional()}),kte=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),consent:o8t.optional()}),O8t=kte,C8t=kte,HIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional(),discounts:s8t.optional()}),k8t=fe({allocations:ue(a8t).optional(),amount:Tr(),automatic:ld().optional(),code:L().optional(),eligibility:L().optional(),method:D4t.optional(),priority:Tr().optional(),provisional:ld().optional(),title:L()}),FIe=fe({id:L(),line_item_ids:ue(L()),options:ue(u8t).optional(),selected_option_id:J4([G4(),L()]).optional()}),R8t=fe({destinations:ue(l8t).optional(),groups:ue(FIe).optional(),id:L(),line_item_ids:ue(L()),selected_destination_id:J4([G4(),L()]).optional(),type:Ste}),cNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),signals:Di.optional()}),uNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),id:L(),line_items:ue(LT),signals:Di.optional()}),dNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy).optional(),messages:ue(T0).optional(),signals:Di.optional(),totals:ue(yy),ucp:kl}),N8t=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional()}),VIe=N8t,lNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,cart_id:L().optional()}),Rte=fe({categories:ue(L()).optional(),price:p8t.optional()}),Z4=fe({max:Y4,min:Y4}),Nte=fe({name:L(),values:ue(f8t)}),$Ie=fe({amount:Tr(),currency:L(),measure:zIe,reference:b8t}),B8t=$Ie,pNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),id:L(),preferences:ue(L()).optional(),selected:ue(DIe).optional(),signals:Ite.optional()}),fNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),pagination:_8t.optional(),query:L().optional(),signals:Ite.optional()}),j8t=fe({capabilities:ue(H4t),services:Jt(L(),E8t),version:L()}),mNr=fe({attribution:Jt(L(),L()).optional(),payment:x8t,signals:Di.optional()}),KIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl}),U8t=fe({events:ue(T8t).optional(),expectations:ue(I8t).optional()}),WIe=fe({attribution:Jt(L(),L()).optional(),buyer:kte.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional()}),GIe=fe({attribution:Jt(L(),L()).optional(),buyer:C8t.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional()}),JIe=fe({attribution:Jt(L(),L()).optional(),buyer:O8t.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl}),YIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),discounts:UIe.optional()}),M8t=fe({applied:ue(k8t).optional(),codes:ue(L()).optional()}),q8t=fe({destinations:ue(c8t).optional(),groups:ue(FIe).optional(),line_item_ids:ue(L()).optional(),selected_destination_id:J4([G4(),L()]).optional(),type:Ste}),D8t=fe({available_methods:ue(d8t).optional(),methods:ue(R8t).optional()}),ZIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),cart_id:L().optional()}),hNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),ids:ue(L()),signals:Ite.optional()}),L8t=fe({availability:MIe.optional(),barcodes:ue(qIe).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price:Y4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Cte).optional(),price:Y4,rating:DT.optional(),seller:LIe.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:$Ie.optional(),url:L().optional(),inputs:ue(y8t)}),XIe=fe({availability:m8t.optional(),barcodes:ue(h8t).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price:Y4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Cte).optional(),price:Y4,rating:DT.optional(),seller:g8t.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:B8t.optional(),url:L().optional()}),z8t=fe({categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Nte).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(XIe)}),yNr=fe({payment:w8t.optional(),signing_keys:ue(z4t).optional(),ucp:j8t}),QIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional()}),H8t=fe({adjustments:ue(S8t).optional(),attribution:Jt(L(),L()).optional(),checkout_id:L(),currency:L(),fulfillment:U8t,id:L(),label:L().optional(),line_items:ue(P8t),messages:ue(T0).optional(),permalink_url:L(),totals:ue(yy),ucp:kl}),ePe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,discounts:M8t.optional()}),tPe=fe({methods:ue(q8t).optional()}),rPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional(),fulfillment:tPe.optional()}),nPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,fulfillment:D8t.optional()}),F8t=fe({categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Nte).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(L8t)}),V8t=fe({options:ue(Nte).optional(),selected:ue(DIe).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(XIe)}),gNr=fe({messages:ue(Pte).optional(),pagination:v8t.optional(),products:ue(z8t),ucp:kl}),iPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),fulfillment:tPe.optional()}),bNr=fe({messages:ue(Pte).optional(),products:ue(F8t),ucp:kl}),_Nr=fe({messages:ue(Pte).optional(),product:V8t,ucp:kl});var ANr=tU.extend({token:Ur.string().optional()}),$8t=Ur.object({webhook_url:Ur.string().url().optional()}),oPe=KIe.extend(nPe.pick({fulfillment:!0}).shape).extend(ePe.pick({discounts:!0}).shape).extend(JIe.pick({buyer:!0}).shape).extend({platform:$8t.optional()}),sPe=QIe.extend(iPe.pick({fulfillment:!0}).shape).extend(YIe.pick({discounts:!0}).shape).extend(WIe.pick({buyer:!0}).shape).extend(ZIe.pick({cart_id:!0}).shape),aPe=VIe.extend(rPe.pick({fulfillment:!0}).shape).extend(HIe.pick({discounts:!0}).shape).extend(GIe.pick({buyer:!0}).shape);Sl();async function oU(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 sU(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 K8t=3e4,cPe=2*1024*1024,Rl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function uPe(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 dPe(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"?sPe:aPe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function W8t(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 lPe(e,t,r,n){try{e[t](r,n)}catch{}}function G8t(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 aU=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=uPe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=uPe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??K8t,this.boundaryLogger=t.logger??Ne}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:dPe(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:dPe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=sU(this.timeoutMs,this.signal),o=(0,pPe.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 oU(u,cPe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Rl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>cPe)throw new Rl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Rl("UCP MCP response is not valid JSON",void 0,u.status)}if(!W8t(l))throw new Rl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Rl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Rl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Rl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Rl("UCP MCP response is missing result.structuredContent");if(!oPe.safeParse(G8t(p.structuredContent)).success)throw new Rl("UCP checkout response failed schema validation");return lPe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw lPe(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 mPe=require("node:crypto");Sl();var uU="2026-04-08",J8t="dev.ucp.shopping",Y8t="dev.ucp.shopping.checkout",Z8t=1024*1024,X8t=1e4,Q8t="https://ucp.dev",HT=Ur.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),e3t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:HT,schema:HT,transport:Ur.enum(["rest","mcp","a2a","embedded"]),endpoint:HT.optional()}).passthrough(),t3t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:HT,schema:HT,extends:Ur.union([Ur.string(),Ur.array(Ur.string()).min(1)]).optional()}).passthrough(),r3t=Ur.object({ucp:Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Ur.record(Ur.array(e3t)),capabilities:Ur.record(Ur.array(t3t)),payment_handlers:Ur.record(Ur.array(Ur.unknown())).optional()}).passthrough(),signing_keys:Ur.array(Ur.unknown()).optional()}).passthrough();function n3t(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 cU(e,t){if(new URL(e).origin!==Q8t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function fPe(e,t,r,n){try{e[t](r,n)}catch{}}async function i3t(e,t={}){let r=n3t(e,"UCP business URL"),n=sU(t.timeoutMs??X8t,t.signal),i=t.logger??Ne,o=(0,mPe.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 oU(c,Z8t,"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=r3t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return fPe(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 fPe(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 o3t(e){if(e.ucp.version!==uU)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[Y8t]?.find(i=>i.version===uU);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");cU(t.spec,"Checkout capability spec"),cU(t.schema,"Checkout capability schema");let r=e.ucp.services[J8t]?.find(i=>i.version===uU&&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");cU(r.spec,"Shopping service spec"),cU(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 hPe(e,t={}){let r=await i3t(e,t);return{...r,endpoint:o3t(r.profile),version:uU}}var s3t="https://app.visacli.sh/.well-known/ucp";function a3t(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 c3t(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 Bte(e,t=new Set){if(Array.isArray(e))for(let r of e)Bte(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?c3t(n,t):Bte(n,t);return t}function u3t(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=Bte(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 gPe(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 d3t(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 bPe(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??hPe)(e.business),i=await(t.getCheckout??(async(o,s)=>await new aU({endpoint:o.endpoint,platformProfileUrl:a3t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??s3t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function _Pe(e,t={}){let{service:r,checkout:n}=await bPe(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=gPe(n),s=u3t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,yPe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:d3t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function l3t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function vPe(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await bPe(e,t),n=gPe(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=l3t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}m4();function jte(){return rd()}var xo=new y4(()=>Za.getSessionToken()),p3t="4.1.0-rc.56",nBr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
20828
+ `:""})}function uwt(e){return cwt(e,nwt,iwt).trimEnd()}function dwt(e){return uwt(e)!==e.trimEnd()}function $j(e=owt()){if(!e)return!1;try{let t=swt(e),r=cf.readFileSync(t,"utf-8");return dwt(r)}catch{return!1}}function Y7e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lwt(){let e=Vj.homedir();if(!e||!Ol.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Ol.resolve(e)}var mRr=1440*60*1e3;var pwt="# visa-cli-hud-v1";function Z7e(e){return typeof e!="string"?!1:e.includes(pwt)?!0:e.includes("visa-cli")&&e.includes("statusline")}FX();m4();EB();var X7e="4.1.0-rc.57";function dte(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function fwt(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=ZX(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function D4(e){return e==null?"\u2014":e?"yes":"no"}async function Q7e(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=YX("auth.serverUrl"),s=rd(),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:D4(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=fwt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:D4(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=fB(),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:D4(!u),source:d}),n.push({key:"client.version",value:X7e,formatted:X7e,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=zh();n.push({key:"dev.mockKeychain",value:p,formatted:D4(p),source:dte("VISA_MOCK_KEYCHAIN",!!l),hint:nQ()});let f=process.env.VISA_MOCK_TOUCHID,m=wB();n.push({key:"dev.mockTouchid",value:m,formatted:D4(m),source:dte("VISA_MOCK_TOUCHID",!!f),hint:nQ()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:D4(!!h),source:dte("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var vte=require("node:os"),OT=require("node:path"),CT=require("node:fs/promises"),pIe=require("node:fs"),fIe=require("node:url"),mIe=require("node:crypto");Sl();var mwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function lte(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!mwt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var w0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function eIe(e){let t;try{t=new URL(e)}catch{throw new w0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new w0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Sl();var hwt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},tIe=300*1e3,pte={},fte=0,IT=null;function mte(){return IT||(IT=(async()=>{try{let e=await xo.getFeatureFlags();pte=e&&e.flags||{},fte=Date.now()}catch(e){pte={},Ne.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{IT=null}})(),IT)}async function rIe(){await mte()}function nIe(){Date.now()-fte<tIe||mte()}async function k_(){Date.now()-fte<tIe||await mte()}function ou(e){let t=hwt[e];return t?pte[t]!==!0:!1}var iIe=require("node:crypto"),PT=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},Kj=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 PT(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??iIe.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 hIe(e){return[(0,OT.join)(e,"checkout-engine","index.js"),(0,OT.join)(e,"..","checkout-engine","index.js")]}function Swt(e,t=pIe.existsSync){return hIe(e).find(r=>t(r))??null}var Gj=null,yIe=async()=>{if(Gj)return Gj;let e=Swt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${hIe(__dirname).join(" and ")}).`);return Gj=(await import((0,fIe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await Twt(),cardMandateRegister:await Iwt()}),Gj};async function Twt(){let e=await Promise.resolve().then(()=>(bte(),gte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function Iwt(){let e=await Promise.resolve().then(()=>(bte(),gte));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function wte(){return ou("pay_merchant")?(await k_(),ou("pay_merchant")):!1}var gIe=(0,OT.join)((0,vte.homedir)(),".visa-mcp","agent-credential.json"),bIe=(0,OT.join)((0,vte.homedir)(),".visa-mcp","contact.json"),_Ie=new Kj;function kT(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var Pwt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function vIe(e){return Pwt.has(e)?e:null}async function Jj(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?kT(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0&&e.source!=="mandate"?e.amountMinor/100:null,payment_currency:vIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function lIe(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?kT(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:vIe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ne.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function _te(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new w0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function wIe(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=kT(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 EIe(e={},t={}){if(await(t.flagDisabled??wte)())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??_Ie).get(n);return o?wIe(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 AIe(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:QX()&&!process.env.VISA_VERIFY_WEB_URL?null:Lh();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??wte)())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??_Ie,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=eIe(e.url??"").toString(),c=_te(e.amount)}catch(C){if(C instanceof w0)return{success:!1,message:C.message};throw C}let d=t.credentialPath??gIe,l=t.contactPath??bIe;try{await(0,CT.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,CT.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let C=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(C);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??yIe,y;try{y=await h()}catch(C){let T=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw C}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(C=>xo.emitTelemetry(C)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ne.info("pay_merchant:review",{host:_,currency:u});let C;try{C=await y.review(v)}catch(T){throw await Jj({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await Jj({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${lte(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async C=>{Ne.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...C?{onApprovalUrl:C}:{}})}catch(j){throw await Jj({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:A,submit:m}),j}let O=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",M=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await Jj({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:O,errorMessage:O?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:M,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let U=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:O,action:"pay",reviewId:x,...T,paymentStatus:M,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${U}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${U}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,mIe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ne.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:C,run:async O=>{try{let M=await S(U=>{Ne.info("pay_merchant:approval_handoff_ready",{reviewId:x}),O(U)});return Ne.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:M.success===!0}),M}catch(M){throw Ne.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:kT(M instanceof Error?M.message:String(M))}),M}}});return wIe(T,"authorize")}catch(T){if(T instanceof PT)return Ne.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function xIe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:Lh();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??wte)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=_te(e.ceiling)}catch(_){if(_ instanceof w0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=_te(e.perTransaction)}catch(_){if(_ instanceof w0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??gIe,u=t.contactPath??bIe;try{await(0,CT.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,CT.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??yIe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>xo.emitTelemetry(_)),y=Date.now();Ne.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?kT(_.message):String(_);return Ne.warn("start_card_mandate:failed",{message:w}),await lIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ne.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await lIe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${lte(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var yPe=require("node:crypto");var pPe=require("node:crypto");var Ur={};Ai(Ur,{BRAND:()=>e4t,DIRTY:()=>N_,EMPTY_PATH:()=>Rwt,INVALID:()=>yt,NEVER:()=>C4t,OK:()=>Ls,ParseStatus:()=>ns,Schema:()=>qt,ZodAny:()=>fy,ZodArray:()=>S0,ZodBigInt:()=>j_,ZodBoolean:()=>U_,ZodBranded:()=>NT,ZodCatch:()=>W_,ZodDate:()=>M_,ZodDefault:()=>K_,ZodDiscriminatedUnion:()=>Xj,ZodEffects:()=>dd,ZodEnum:()=>V_,ZodError:()=>ec,ZodFirstPartyTypeKind:()=>Et,ZodFunction:()=>eU,ZodIntersection:()=>z_,ZodIssueCode:()=>ye,ZodLazy:()=>H_,ZodLiteral:()=>F_,ZodMap:()=>$4,ZodNaN:()=>W4,ZodNativeEnum:()=>$_,ZodNever:()=>Cl,ZodNull:()=>D_,ZodNullable:()=>lf,ZodNumber:()=>B_,ZodObject:()=>tc,ZodOptional:()=>cd,ZodParsedType:()=>Be,ZodPipeline:()=>BT,ZodPromise:()=>my,ZodReadonly:()=>G_,ZodRecord:()=>Qj,ZodSchema:()=>qt,ZodSet:()=>K4,ZodString:()=>py,ZodSymbol:()=>F4,ZodTransformer:()=>dd,ZodTuple:()=>df,ZodType:()=>qt,ZodUndefined:()=>q_,ZodUnion:()=>L_,ZodUnknown:()=>x0,ZodVoid:()=>V4,addIssueToContext:()=>Te,any:()=>pd,array:()=>ue,bigint:()=>i4t,boolean:()=>ld,coerce:()=>su,custom:()=>RIe,date:()=>o4t,datetimeRegex:()=>CIe,defaultErrorMap:()=>E0,discriminatedUnion:()=>p4t,effect:()=>E4t,enum:()=>fd,function:()=>g4t,getErrorMap:()=>L4,getParsedType:()=>uf,instanceof:()=>r4t,intersection:()=>f4t,isAborted:()=>Yj,isAsync:()=>z4,isDirty:()=>Zj,isValid:()=>ly,late:()=>t4t,lazy:()=>b4t,literal:()=>_4t,makeIssue:()=>RT,map:()=>h4t,nan:()=>n4t,nativeEnum:()=>v4t,never:()=>u4t,null:()=>G4,nullable:()=>x4t,number:()=>Tr,object:()=>fe,objectUtil:()=>Ete,oboolean:()=>O4t,onumber:()=>P4t,optional:()=>A4t,ostring:()=>I4t,pipeline:()=>T4t,preprocess:()=>S4t,promise:()=>w4t,quotelessJson:()=>Owt,record:()=>Jt,set:()=>y4t,setErrorMap:()=>kwt,strictObject:()=>l4t,string:()=>L,symbol:()=>s4t,transformer:()=>E4t,tuple:()=>m4t,undefined:()=>a4t,union:()=>J4,unknown:()=>c4t,util:()=>Gt,void:()=>d4t});var Gt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Gt||(Gt={}));var Ete;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ete||(Ete={}));var Be=Gt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),uf=e=>{switch(typeof e){case"undefined":return Be.undefined;case"string":return Be.string;case"number":return Number.isNaN(e)?Be.nan:Be.number;case"boolean":return Be.boolean;case"function":return Be.function;case"bigint":return Be.bigint;case"symbol":return Be.symbol;case"object":return Array.isArray(e)?Be.array:e===null?Be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Be.promise:typeof Map<"u"&&e instanceof Map?Be.map:typeof Set<"u"&&e instanceof Set?Be.set:typeof Date<"u"&&e instanceof Date?Be.date:Be.object;default:return Be.unknown}};var ye=Gt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Owt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ec=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ec.create=e=>new ec(e);var Cwt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Be.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Gt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Gt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Gt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Gt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Gt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Gt.assertNever(e)}return{message:r}},E0=Cwt;var SIe=E0;function kwt(e){SIe=e}function L4(){return SIe}var RT=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}},Rwt=[];function Te(e,t){let r=L4(),n=RT({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===E0?void 0:E0].filter(i=>!!i)});e.common.issues.push(n)}var ns=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return yt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return yt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},yt=Object.freeze({status:"aborted"}),N_=e=>({status:"dirty",value:e}),Ls=e=>({status:"valid",value:e}),Yj=e=>e.status==="aborted",Zj=e=>e.status==="dirty",ly=e=>e.status==="valid",z4=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var ud=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}},TIe=(e,t)=>{if(ly(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 ec(e.common.issues);return this._error=r,this._error}}};function Bt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var qt=class{get description(){return this._def.description}_getType(t){return uf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:uf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ns,ctx:{common:t.parent.common,data:t.data,parsedType:uf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(z4(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:uf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return TIe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:uf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return ly(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=>ly(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:uf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(z4(i)?i:Promise.resolve(i));return TIe(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 dd({schema:this,typeName:Et.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return cd.create(this,this._def)}nullable(){return lf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return S0.create(this)}promise(){return my.create(this,this._def)}or(t){return L_.create([this,t],this._def)}and(t){return z_.create(this,t,this._def)}transform(t){return new dd({...Bt(this._def),schema:this,typeName:Et.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new K_({...Bt(this._def),innerType:this,defaultValue:r,typeName:Et.ZodDefault})}brand(){return new NT({typeName:Et.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new W_({...Bt(this._def),innerType:this,catchValue:r,typeName:Et.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return BT.create(this,t)}readonly(){return G_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Nwt=/^c[^\s-]{8,}$/i,Bwt=/^[0-9a-z]+$/,jwt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Uwt=/^[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,Mwt=/^[a-z0-9_-]{21}$/i,qwt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Dwt=/^[-+]?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)?)??$/,Lwt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zwt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ate,Hwt=/^(?:(?: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])$/,Fwt=/^(?:(?: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])$/,Vwt=/^(([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]))$/,$wt=/^(([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])$/,Kwt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wwt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,PIe="((\\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])))",Gwt=new RegExp(`^${PIe}$`);function OIe(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 Jwt(e){return new RegExp(`^${OIe(e)}$`)}function CIe(e){let t=`${PIe}T${OIe(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 Ywt(e,t){return!!((t==="v4"||!t)&&Hwt.test(e)||(t==="v6"||!t)&&Vwt.test(e))}function Zwt(e,t){if(!qwt.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 Xwt(e,t){return!!((t==="v4"||!t)&&Fwt.test(e)||(t==="v6"||!t)&&$wt.test(e))}var py=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Be.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.string,received:o.parsedType}),yt}let n=new ns,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Lwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ate||(Ate=new RegExp(zwt,"u")),Ate.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Uwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Mwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Nwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Bwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")jwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Te(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?CIe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Gwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Jwt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Dwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Ywt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Zwt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Xwt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Kwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Wwt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...et.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};py.create=e=>new py({checks:[],typeName:Et.ZodString,coerce:e?.coerce??!1,...Bt(e)});function Qwt(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 B_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Be.number){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.number,received:o.parsedType}),yt}let n,i=new ns;for(let o of this._def.checks)o.kind==="int"?Gt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Qwt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Gt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};B_.create=e=>new B_({checks:[],typeName:Et.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var j_=class e extends qt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Be.bigint)return this._getInvalidInput(t);let n,i=new ns;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Gt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.bigint,received:r.parsedType}),yt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};j_.create=e=>new j_({checks:[],typeName:Et.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var U_=class extends qt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Be.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.boolean,received:n.parsedType}),yt}return Ls(t.data)}};U_.create=e=>new U_({typeName:Et.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var M_=class e extends qt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Be.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:Be.date,received:o.parsedType}),yt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),yt}let n=new ns,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Gt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};M_.create=e=>new M_({checks:[],coerce:e?.coerce||!1,typeName:Et.ZodDate,...Bt(e)});var F4=class extends qt{_parse(t){if(this._getType(t)!==Be.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.symbol,received:n.parsedType}),yt}return Ls(t.data)}};F4.create=e=>new F4({typeName:Et.ZodSymbol,...Bt(e)});var q_=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.undefined,received:n.parsedType}),yt}return Ls(t.data)}};q_.create=e=>new q_({typeName:Et.ZodUndefined,...Bt(e)});var D_=class extends qt{_parse(t){if(this._getType(t)!==Be.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.null,received:n.parsedType}),yt}return Ls(t.data)}};D_.create=e=>new D_({typeName:Et.ZodNull,...Bt(e)});var fy=class extends qt{constructor(){super(...arguments),this._any=!0}_parse(t){return Ls(t.data)}};fy.create=e=>new fy({typeName:Et.ZodAny,...Bt(e)});var x0=class extends qt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ls(t.data)}};x0.create=e=>new x0({typeName:Et.ZodUnknown,...Bt(e)});var Cl=class extends qt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:Be.never,received:r.parsedType}),yt}};Cl.create=e=>new Cl({typeName:Et.ZodNever,...Bt(e)});var V4=class extends qt{_parse(t){if(this._getType(t)!==Be.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.void,received:n.parsedType}),yt}return Ls(t.data)}};V4.create=e=>new V4({typeName:Et.ZodVoid,...Bt(e)});var S0=class e extends qt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Be.array)return Te(r,{code:ye.invalid_type,expected:Be.array,received:r.parsedType}),yt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Te(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Te(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ud(r,s,r.path,a)))).then(s=>ns.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new ud(r,s,r.path,a)));return ns.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};S0.create=(e,t)=>new S0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Et.ZodArray,...Bt(t)});function H4(e){if(e instanceof tc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=cd.create(H4(n))}return new tc({...e._def,shape:()=>t})}else return e instanceof S0?new S0({...e._def,type:H4(e.element)}):e instanceof cd?cd.create(H4(e.unwrap())):e instanceof lf?lf.create(H4(e.unwrap())):e instanceof df?df.create(e.items.map(t=>H4(t))):e}var tc=class e extends qt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Gt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Be.object){let u=this._getOrReturnCtx(t);return Te(u,{code:ye.invalid_type,expected:Be.object,received:u.parsedType}),yt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Cl&&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 ud(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Cl){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Te(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new ud(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=>ns.mergeObjectSync(n,u)):ns.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Et.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Gt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Gt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return H4(this)}partial(t){let r={};for(let n of Gt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Gt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof cd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return kIe(Gt.objectKeys(this.shape))}};tc.create=(e,t)=>new tc({shape:()=>e,unknownKeys:"strip",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});tc.strictCreate=(e,t)=>new tc({shape:()=>e,unknownKeys:"strict",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});tc.lazycreate=(e,t)=>new tc({shape:e,unknownKeys:"strip",catchall:Cl.create(),typeName:Et.ZodObject,...Bt(t)});var L_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new ec(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),yt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new ec(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),yt}}get options(){return this._def.options}};L_.create=(e,t)=>new L_({options:e,typeName:Et.ZodUnion,...Bt(t)});var A0=e=>e instanceof H_?A0(e.schema):e instanceof dd?A0(e.innerType()):e instanceof F_?[e.value]:e instanceof V_?e.options:e instanceof $_?Gt.objectValues(e.enum):e instanceof K_?A0(e._def.innerType):e instanceof q_?[void 0]:e instanceof D_?[null]:e instanceof cd?[void 0,...A0(e.unwrap())]:e instanceof lf?[null,...A0(e.unwrap())]:e instanceof NT||e instanceof G_?A0(e.unwrap()):e instanceof W_?A0(e._def.innerType):[],Xj=class e extends qt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.object)return Te(r,{code:ye.invalid_type,expected:Be.object,received:r.parsedType}),yt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=A0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:Et.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function xte(e,t){let r=uf(e),n=uf(t);if(e===t)return{valid:!0,data:e};if(r===Be.object&&n===Be.object){let i=Gt.objectKeys(t),o=Gt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=xte(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Be.array&&n===Be.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=xte(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Be.date&&n===Be.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var z_=class extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Yj(o)||Yj(s))return yt;let a=xte(o.value,s.value);return a.valid?((Zj(o)||Zj(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),yt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};z_.create=(e,t,r)=>new z_({left:e,right:t,typeName:Et.ZodIntersection,...Bt(r)});var df=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.array)return Te(n,{code:ye.invalid_type,expected:Be.array,received:n.parsedType}),yt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ud(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ns.mergeArray(r,s)):ns.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};df.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new df({items:e,typeName:Et.ZodTuple,rest:null,...Bt(t)})};var Qj=class e extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.object)return Te(n,{code:ye.invalid_type,expected:Be.object,received:n.parsedType}),yt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new ud(n,a,n.path,a)),value:s._parse(new ud(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ns.mergeObjectAsync(r,i):ns.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof qt?new e({keyType:t,valueType:r,typeName:Et.ZodRecord,...Bt(n)}):new e({keyType:py.create(),valueType:t,typeName:Et.ZodRecord,...Bt(r)})}},$4=class extends qt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.map)return Te(n,{code:ye.invalid_type,expected:Be.map,received:n.parsedType}),yt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new ud(n,a,n.path,[u,"key"])),value:o._parse(new ud(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return yt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};$4.create=(e,t,r)=>new $4({valueType:t,keyType:e,typeName:Et.ZodMap,...Bt(r)});var K4=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Be.set)return Te(n,{code:ye.invalid_type,expected:Be.set,received:n.parsedType}),yt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Te(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return yt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new ud(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};K4.create=(e,t)=>new K4({valueType:e,minSize:null,maxSize:null,typeName:Et.ZodSet,...Bt(t)});var eU=class e extends qt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.function)return Te(r,{code:ye.invalid_type,expected:Be.function,received:r.parsedType}),yt;function n(a,c){return RT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,L4(),E0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return RT({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,L4(),E0].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 my){let a=this;return Ls(async function(...c){let u=new ec([]),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 Ls(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new ec([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new ec([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:df.create(t).rest(x0.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||df.create([]).rest(x0.create()),returns:r||x0.create(),typeName:Et.ZodFunction,...Bt(n)})}},H_=class extends qt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};H_.create=(e,t)=>new H_({getter:e,typeName:Et.ZodLazy,...Bt(t)});var F_=class extends qt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),yt}return{status:"valid",value:t.data}}get value(){return this._def.value}};F_.create=(e,t)=>new F_({value:e,typeName:Et.ZodLiteral,...Bt(t)});function kIe(e,t){return new V_({values:e,typeName:Et.ZodEnum,...Bt(t)})}var V_=class e extends qt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Gt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),yt}return Ls(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})}};V_.create=kIe;var $_=class extends qt{_parse(t){let r=Gt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Be.string&&n.parsedType!==Be.number){let i=Gt.objectValues(r);return Te(n,{expected:Gt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),yt}if(this._cache||(this._cache=new Set(Gt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Gt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),yt}return Ls(t.data)}get enum(){return this._def.values}};$_.create=(e,t)=>new $_({values:e,typeName:Et.ZodNativeEnum,...Bt(t)});var my=class extends qt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Be.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:Be.promise,received:r.parsedType}),yt;let n=r.parsedType===Be.promise?r.data:Promise.resolve(r.data);return Ls(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};my.create=(e,t)=>new my({type:e,typeName:Et.ZodPromise,...Bt(t)});var dd=class extends qt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Et.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Te(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return yt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?yt:c.status==="dirty"?N_(c.value):r.value==="dirty"?N_(c.value):c});{if(r.value==="aborted")return yt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?yt:a.status==="dirty"?N_(a.value):r.value==="dirty"?N_(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?yt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ly(s))return yt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>ly(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):yt);Gt.assertNever(i)}};dd.create=(e,t,r)=>new dd({schema:e,typeName:Et.ZodEffects,effect:t,...Bt(r)});dd.createWithPreprocess=(e,t,r)=>new dd({schema:t,effect:{type:"preprocess",transform:e},typeName:Et.ZodEffects,...Bt(r)});var cd=class extends qt{_parse(t){return this._getType(t)===Be.undefined?Ls(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};cd.create=(e,t)=>new cd({innerType:e,typeName:Et.ZodOptional,...Bt(t)});var lf=class extends qt{_parse(t){return this._getType(t)===Be.null?Ls(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};lf.create=(e,t)=>new lf({innerType:e,typeName:Et.ZodNullable,...Bt(t)});var K_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Be.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};K_.create=(e,t)=>new K_({innerType:e,typeName:Et.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var W_=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return z4(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ec(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ec(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};W_.create=(e,t)=>new W_({innerType:e,typeName:Et.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var W4=class extends qt{_parse(t){if(this._getType(t)!==Be.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:Be.nan,received:n.parsedType}),yt}return{status:"valid",value:t.data}}};W4.create=e=>new W4({typeName:Et.ZodNaN,...Bt(e)});var e4t=Symbol("zod_brand"),NT=class extends qt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},BT=class e extends qt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?yt:o.status==="dirty"?(r.dirty(),N_(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?yt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Et.ZodPipeline})}},G_=class extends qt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(ly(i)&&(i.value=Object.freeze(i.value)),i);return z4(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};G_.create=(e,t)=>new G_({innerType:e,typeName:Et.ZodReadonly,...Bt(t)});function IIe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function RIe(e,t={},r){return e?fy.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=IIe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=IIe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):fy.create()}var t4t={object:tc.lazycreate},Et;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Et||(Et={}));var r4t=(e,t={message:`Input not instance of ${e.name}`})=>RIe(r=>r instanceof e,t),L=py.create,Tr=B_.create,n4t=W4.create,i4t=j_.create,ld=U_.create,o4t=M_.create,s4t=F4.create,a4t=q_.create,G4=D_.create,pd=fy.create,c4t=x0.create,u4t=Cl.create,d4t=V4.create,ue=S0.create,fe=tc.create,l4t=tc.strictCreate,J4=L_.create,p4t=Xj.create,f4t=z_.create,m4t=df.create,Jt=Qj.create,h4t=$4.create,y4t=K4.create,g4t=eU.create,b4t=H_.create,_4t=F_.create,fd=V_.create,v4t=$_.create,w4t=my.create,E4t=dd.create,A4t=cd.create,x4t=lf.create,S4t=dd.createWithPreprocess,T4t=BT.create,I4t=()=>L().optional(),P4t=()=>Tr().optional(),O4t=()=>ld().optional(),su={string:(e=>py.create({...e,coerce:!0})),number:(e=>B_.create({...e,coerce:!0})),boolean:(e=>U_.create({...e,coerce:!0})),bigint:(e=>j_.create({...e,coerce:!0})),date:(e=>M_.create({...e,coerce:!0}))};var C4t=yt;var R4t=fd(["enc","sig"]),N4t=fd(["markdown","plain"]),B4t=fd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),j4t=fd(["error","info","warning"]),X4=fd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),U4t=fd(["completed","failed","pending"]),M4t=fd(["digital","pickup","shipping"]),q4t=fd(["fulfilled","partial","processing","removed"]),D4t=fd(["across","each"]),Ste=fd(["pickup","shipping"]),L4t=fe({config:Jt(L(),pd()),config_schema:L(),id:L(),instrument_schemas:ue(L()),name:L(),spec:L(),version:L()}),z4t=fe({alg:L().optional(),crv:L().optional(),e:L().optional(),kid:L(),kty:L(),n:L().optional(),use:R4t.optional(),x:L().optional(),y:L().optional()}),H4t=fe({config:Jt(L(),pd()).optional(),extends:L().optional(),name:L(),schema:L(),spec:L(),version:L()}),F4t=fe({endpoint:L()}),V4t=fe({schema:L()}),NIe=fe({endpoint:L(),schema:L()}),$4t=NIe,K4t=NIe,ya=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional()}),io=fe({address_country:L().optional(),address_region:L().optional(),currency:L().optional(),eligibility:ue(L()).optional(),intent:L().optional(),language:L().optional(),postal_code:L().optional()}),Tte=io,BIe=fe({id:L()}),W4t=BIe,G4t=BIe,jT=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional()}),tU=fe({type:L()}),Di=fe({"dev.ucp.buyer_ip":L().optional(),"dev.ucp.user_agent":L().optional()}),Ite=Di,jIe=fe({id:L(),image_url:L().optional(),price:Tr(),title:L()}),rU=fe({amount:Tr(),display_text:L().optional(),type:L()}),hy=fe({title:L().optional(),type:L(),url:L()}),T0=fe({code:L().optional(),content:L(),content_type:N4t.optional(),path:L().optional(),severity:B4t.optional(),type:j4t,image_url:L().optional(),presentation:L().optional(),url:L().optional()}),Pte=T0,Q4=fe({id:L(),label:L().optional(),permalink_url:L()}),J4t=fe({amount:Tr(),display_text:L()}),Y4t=fe({config:Jt(L(),pd()).optional(),extends:L().optional(),name:L(),schema:L().optional(),spec:L().optional(),version:L()}),Ote=fe({id:L(),quantity:Tr()}),Z4t=Ote,X4t=Ote,Q4t=Ote,e8t=fe({fulfilled:Tr(),original:Tr().optional(),total:Tr()}),t8t=fe({billing_address:jT.optional(),credential:tU.optional(),display:Jt(L(),pd()).optional(),handler_id:L(),id:L(),type:L()}),r8t=fe({checkout_mandate:L()}),n8t=fe({merchant_authorization:L().optional(),checkout_mandate:L()}),i8t=fe({analytics:ld().optional(),marketing:ld().optional(),preferences:ld().optional(),sale_of_data:ld().optional()});var o8t=i8t;var UIe=fe({codes:ue(L()).optional()}),s8t=UIe,a8t=fe({amount:Tr(),path:L()}),c8t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L().optional(),address:jT.optional(),name:L().optional()}),u8t=fe({carrier:L().optional(),description:L().optional(),earliest_fulfillment_time:su.date().optional(),id:L(),latest_fulfillment_time:su.date().optional(),title:L(),totals:ue(rU)}),d8t=fe({description:L().optional(),fulfillable_on:J4([G4(),L()]).optional(),line_item_ids:ue(L()),type:Ste}),l8t=fe({address_country:L().optional(),address_locality:L().optional(),address_region:L().optional(),extended_address:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),postal_code:L().optional(),street_address:L().optional(),id:L(),address:jT.optional(),name:L().optional()}),p8t=fe({max:Tr().optional(),min:Tr().optional()}),UT=fe({taxonomy:L().optional(),value:L()}),MT=fe({html:L().optional(),markdown:L().optional(),plain:L().optional()}),Y4=fe({amount:Tr(),currency:L()}),qT=fe({alt_text:L().optional(),height:Tr().optional(),type:L(),url:L(),width:Tr().optional()}),f8t=fe({id:L().optional(),label:L()}),DT=fe({count:Tr().optional(),scale_max:Tr(),scale_min:Tr().optional(),value:Tr()}),MIe=fe({available:ld().optional(),status:L().optional()}),m8t=MIe,qIe=fe({type:L(),value:L()}),h8t=qIe,y8t=fe({id:L(),match:L().optional()}),Cte=fe({id:L().optional(),label:L(),name:L()}),DIe=Cte,LIe=fe({links:ue(hy).optional(),name:L().optional()}),g8t=LIe,zIe=fe({unit:L(),value:Tr()});var b8t=zIe,_8t=fe({cursor:L().optional(),limit:Tr().optional()}),v8t=fe({cursor:L().optional(),has_next_page:ld(),total_count:Tr().optional()}),w8t=fe({handlers:ue(L4t).optional()}),E8t=fe({a2a:F4t.optional(),embedded:V4t.optional(),mcp:$4t.optional(),rest:K4t.optional(),spec:L(),version:L()}),e8=fe({item:W4t,quantity:Tr()}),A8t=fe({billing_address:jT.optional(),credential:tU.optional(),display:Jt(L(),pd()).optional(),handler_id:L(),id:L(),type:L(),selected:ld().optional()}),LT=fe({id:L().optional(),item:G4t,parent_id:L().optional(),quantity:Tr()}),nU=fe({instruments:ue(A8t).optional()}),x8t=nU,zT=nU,t8=nU,iU=nU,J_=fe({id:L(),item:jIe,parent_id:L().optional(),quantity:Tr(),totals:ue(rU)}),yy=fe({amount:Tr(),display_text:L().optional(),type:L(),lines:ue(J4t).optional()}),kl=fe({capabilities:Jt(L(),ue(Y4t)),version:L()}),S8t=fe({description:L().optional(),id:L(),line_items:ue(Z4t).optional(),occurred_at:su.date(),status:U4t,totals:ue(rU).optional(),type:L()}),T8t=fe({carrier:L().optional(),description:L().optional(),id:L(),line_items:ue(X4t),occurred_at:su.date(),tracking_number:L().optional(),tracking_url:L().optional(),type:L()}),I8t=fe({description:L().optional(),destination:jT,fulfillable_on:L().optional(),id:L(),line_items:ue(Q4t),method_type:M4t}),P8t=fe({id:L(),item:jIe,parent_id:L().optional(),quantity:e8t,status:q4t,totals:ue(rU)}),oNr=fe({payment_data:t8t}),sNr=fe({ap2:r8t.optional()}),aNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,ap2:n8t.optional()}),kte=fe({email:L().optional(),first_name:L().optional(),last_name:L().optional(),phone_number:L().optional(),consent:o8t.optional()}),O8t=kte,C8t=kte,HIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional(),discounts:s8t.optional()}),k8t=fe({allocations:ue(a8t).optional(),amount:Tr(),automatic:ld().optional(),code:L().optional(),eligibility:L().optional(),method:D4t.optional(),priority:Tr().optional(),provisional:ld().optional(),title:L()}),FIe=fe({id:L(),line_item_ids:ue(L()),options:ue(u8t).optional(),selected_option_id:J4([G4(),L()]).optional()}),R8t=fe({destinations:ue(l8t).optional(),groups:ue(FIe).optional(),id:L(),line_item_ids:ue(L()),selected_destination_id:J4([G4(),L()]).optional(),type:Ste}),cNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),signals:Di.optional()}),uNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),id:L(),line_items:ue(LT),signals:Di.optional()}),dNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy).optional(),messages:ue(T0).optional(),signals:Di.optional(),totals:ue(yy),ucp:kl}),N8t=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional()}),VIe=N8t,lNr=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,cart_id:L().optional()}),Rte=fe({categories:ue(L()).optional(),price:p8t.optional()}),Z4=fe({max:Y4,min:Y4}),Nte=fe({name:L(),values:ue(f8t)}),$Ie=fe({amount:Tr(),currency:L(),measure:zIe,reference:b8t}),B8t=$Ie,pNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),id:L(),preferences:ue(L()).optional(),selected:ue(DIe).optional(),signals:Ite.optional()}),fNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),pagination:_8t.optional(),query:L().optional(),signals:Ite.optional()}),j8t=fe({capabilities:ue(H4t),services:Jt(L(),E8t),version:L()}),mNr=fe({attribution:Jt(L(),L()).optional(),payment:x8t,signals:Di.optional()}),KIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl}),U8t=fe({events:ue(T8t).optional(),expectations:ue(I8t).optional()}),WIe=fe({attribution:Jt(L(),L()).optional(),buyer:kte.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional()}),GIe=fe({attribution:Jt(L(),L()).optional(),buyer:C8t.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional()}),JIe=fe({attribution:Jt(L(),L()).optional(),buyer:O8t.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl}),YIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),discounts:UIe.optional()}),M8t=fe({applied:ue(k8t).optional(),codes:ue(L()).optional()}),q8t=fe({destinations:ue(c8t).optional(),groups:ue(FIe).optional(),line_item_ids:ue(L()).optional(),selected_destination_id:J4([G4(),L()]).optional(),type:Ste}),D8t=fe({available_methods:ue(d8t).optional(),methods:ue(R8t).optional()}),ZIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),cart_id:L().optional()}),hNr=fe({attribution:Jt(L(),L()).optional(),context:Tte.optional(),filters:Rte.optional(),ids:ue(L()),signals:Ite.optional()}),L8t=fe({availability:MIe.optional(),barcodes:ue(qIe).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price:Y4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Cte).optional(),price:Y4,rating:DT.optional(),seller:LIe.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:$Ie.optional(),url:L().optional(),inputs:ue(y8t)}),XIe=fe({availability:m8t.optional(),barcodes:ue(h8t).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price:Y4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Cte).optional(),price:Y4,rating:DT.optional(),seller:g8t.optional(),sku:L().optional(),tags:ue(L()).optional(),title:L(),unit_price:B8t.optional(),url:L().optional()}),z8t=fe({categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Nte).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(XIe)}),yNr=fe({payment:w8t.optional(),signing_keys:ue(z4t).optional(),ucp:j8t}),QIe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional()}),H8t=fe({adjustments:ue(S8t).optional(),attribution:Jt(L(),L()).optional(),checkout_id:L(),currency:L(),fulfillment:U8t,id:L(),label:L().optional(),line_items:ue(P8t),messages:ue(T0).optional(),permalink_url:L(),totals:ue(yy),ucp:kl}),ePe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,discounts:M8t.optional()}),tPe=fe({methods:ue(q8t).optional()}),rPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(LT),payment:iU.optional(),signals:Di.optional(),fulfillment:tPe.optional()}),nPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),continue_url:L().optional(),currency:L(),expires_at:su.date().optional(),id:L(),line_items:ue(J_),links:ue(hy),messages:ue(T0).optional(),order:Q4.optional(),payment:t8.optional(),signals:Di.optional(),status:X4,totals:ue(yy),ucp:kl,fulfillment:D8t.optional()}),F8t=fe({categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),options:ue(Nte).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(L8t)}),V8t=fe({options:ue(Nte).optional(),selected:ue(DIe).optional(),categories:ue(UT).optional(),description:MT,handle:L().optional(),id:L(),list_price_range:Z4.optional(),media:ue(qT).optional(),metadata:Jt(L(),pd()).optional(),price_range:Z4,rating:DT.optional(),tags:ue(L()).optional(),title:L(),url:L().optional(),variants:ue(XIe)}),gNr=fe({messages:ue(Pte).optional(),pagination:v8t.optional(),products:ue(z8t),ucp:kl}),iPe=fe({attribution:Jt(L(),L()).optional(),buyer:ya.optional(),context:io.optional(),line_items:ue(e8),payment:zT.optional(),signals:Di.optional(),fulfillment:tPe.optional()}),bNr=fe({messages:ue(Pte).optional(),products:ue(F8t),ucp:kl}),_Nr=fe({messages:ue(Pte).optional(),product:V8t,ucp:kl});var ANr=tU.extend({token:Ur.string().optional()}),$8t=Ur.object({webhook_url:Ur.string().url().optional()}),oPe=KIe.extend(nPe.pick({fulfillment:!0}).shape).extend(ePe.pick({discounts:!0}).shape).extend(JIe.pick({buyer:!0}).shape).extend({platform:$8t.optional()}),sPe=QIe.extend(iPe.pick({fulfillment:!0}).shape).extend(YIe.pick({discounts:!0}).shape).extend(WIe.pick({buyer:!0}).shape).extend(ZIe.pick({cart_id:!0}).shape),aPe=VIe.extend(rPe.pick({fulfillment:!0}).shape).extend(HIe.pick({discounts:!0}).shape).extend(GIe.pick({buyer:!0}).shape);Sl();async function oU(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 sU(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 K8t=3e4,cPe=2*1024*1024,Rl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function uPe(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 dPe(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"?sPe:aPe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function W8t(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 lPe(e,t,r,n){try{e[t](r,n)}catch{}}function G8t(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 aU=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=uPe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=uPe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??K8t,this.boundaryLogger=t.logger??Ne}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:dPe(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:dPe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=sU(this.timeoutMs,this.signal),o=(0,pPe.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 oU(u,cPe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new Rl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>cPe)throw new Rl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new Rl("UCP MCP response is not valid JSON",void 0,u.status)}if(!W8t(l))throw new Rl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new Rl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new Rl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new Rl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new Rl("UCP MCP response is missing result.structuredContent");if(!oPe.safeParse(G8t(p.structuredContent)).success)throw new Rl("UCP checkout response failed schema validation");return lPe(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw lPe(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 mPe=require("node:crypto");Sl();var uU="2026-04-08",J8t="dev.ucp.shopping",Y8t="dev.ucp.shopping.checkout",Z8t=1024*1024,X8t=1e4,Q8t="https://ucp.dev",HT=Ur.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),e3t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:HT,schema:HT,transport:Ur.enum(["rest","mcp","a2a","embedded"]),endpoint:HT.optional()}).passthrough(),t3t=Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:HT,schema:HT,extends:Ur.union([Ur.string(),Ur.array(Ur.string()).min(1)]).optional()}).passthrough(),r3t=Ur.object({ucp:Ur.object({version:Ur.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Ur.record(Ur.array(e3t)),capabilities:Ur.record(Ur.array(t3t)),payment_handlers:Ur.record(Ur.array(Ur.unknown())).optional()}).passthrough(),signing_keys:Ur.array(Ur.unknown()).optional()}).passthrough();function n3t(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 cU(e,t){if(new URL(e).origin!==Q8t)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function fPe(e,t,r,n){try{e[t](r,n)}catch{}}async function i3t(e,t={}){let r=n3t(e,"UCP business URL"),n=sU(t.timeoutMs??X8t,t.signal),i=t.logger??Ne,o=(0,mPe.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 oU(c,Z8t,"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=r3t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return fPe(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 fPe(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 o3t(e){if(e.ucp.version!==uU)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[Y8t]?.find(i=>i.version===uU);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");cU(t.spec,"Checkout capability spec"),cU(t.schema,"Checkout capability schema");let r=e.ucp.services[J8t]?.find(i=>i.version===uU&&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");cU(r.spec,"Shopping service spec"),cU(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 hPe(e,t={}){let r=await i3t(e,t);return{...r,endpoint:o3t(r.profile),version:uU}}var s3t="https://app.visacli.sh/.well-known/ucp";function a3t(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 c3t(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 Bte(e,t=new Set){if(Array.isArray(e))for(let r of e)Bte(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?c3t(n,t):Bte(n,t);return t}function u3t(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=Bte(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 gPe(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 d3t(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 bPe(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??hPe)(e.business),i=await(t.getCheckout??(async(o,s)=>await new aU({endpoint:o.endpoint,platformProfileUrl:a3t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??s3t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function _Pe(e,t={}){let{service:r,checkout:n}=await bPe(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=gPe(n),s=u3t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,yPe.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:d3t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function l3t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function vPe(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await bPe(e,t),n=gPe(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=l3t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}m4();function jte(){return rd()}var xo=new y4(()=>Za.getSessionToken()),p3t="4.1.0-rc.57",nBr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
20829
20829
  `);function f3t(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=JS(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(u9e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=GS();if(r.headless)return Ne.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[jte(),Lh()].filter(s=>!!s).map(s=>V9e(t,s)).find(Boolean)??null;if(!i)return Ne.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=K9e(i);return o?((0,EPe.execFile)(o.cmd,o.args,s=>{s&&Ne.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Ne.info(`No browser command for platform "${lU.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function m3t(){let e=!1,t;try{let n=APe.join(lU.homedir(),".claude","settings.json");if(dU.existsSync(n)){let i=JSON.parse(dU.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=Z7e(o)}}catch{}let r=$j();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function h3t(e){let t=await xo.getStatus(e);t.hud=m3t(),!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=p3t;try{let r=rf();if(r){let n=await xo.getAgentTapStatus(r.identity_key.jkt);n&&(t.tap={status:n.status,registeredAt:n.registeredAt})}}catch(r){Ne.warn({component:"get-status-tap",msg:"tap_status_unavailable",error:r?.message})}return t}async function y3t(e,t){return await xo.feedback(e.message,e.transaction_id,t)}async function g3t(e){let t=await Q7e({api:xo,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 Ute=new Set(["auth.serverUrl"]);function FT(){return Object.keys(KS).filter(e=>!Ute.has(e)).sort()}function xPe(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:FT()}}async function b3t(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(Ute.has(e.key))return Ne.warn("config:set:rejected:mcp-forbidden",{key:e.key}),xPe(e.key,"set");Ne.info("config:set",{key:e.key});try{let t=a9e(e.key,e.value);return Ne.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let r=t instanceof c0?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof c0?`Unknown setting "${e.key}". MCP-settable keys: ${FT().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ne.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:FT()}}}async function _3t(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(Ute.has(e.key))return Ne.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),xPe(e.key,"unset");Ne.info("config:unset",{key:e.key});try{let t=c9e(e.key);return Ne.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let r=t instanceof c0?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof c0?`Unknown setting "${e.key}". MCP-settable keys: ${FT().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ne.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:FT()}}}async function v3t(e=jte(),t=!1){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};if(!t){let r=rf();if(r){let n=r.display_name,i;if(process.env.SUBWAY_MESH==="visa"&&n){let{registerOnVisaMeshIfEnabled:s}=await Promise.resolve().then(()=>(Rj(),W7e));i=await s(n)}Ne.info("agent:enroll_already_connected",{keyBound:!0,meshRegistered:i});let o=i===void 0?"":i?` Registered ${n??"this device"} on the .visa mesh.`:` Could not reach the .visa mesh \u2014 run \`visa register ${n??"<name>"}\` to join it.`;return{success:!0,alreadyConnected:!0,...n?{name:n}:{},keyBound:!0,...i!==void 0?{meshRegistered:i}:{},message:`This device is already connected${n?` as ${n}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).`+o+' Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.'}}}try{let r=await bT({authUrl:e,runtime:"visa-cli-mcp",contextLabel:"Pair this MCP runtime"});Ne.info("agent:pairing_open",{pairingId:r.pairingId,agentId:r.agentId});let n=f3t(r.authorizationUrl),i=n.url??r.authorizationUrl;return{success:!0,protocolVersion:r.protocolVersion,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:r.requestKeyFingerprint,opened:n.opened,requiresBrowser:!n.opened,browserUrl:i,expiresAt:r.expiresAt,message:n.opened?`Opened the authorization page for agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, approve the runtime, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`:`Open ${i} to approve agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`}}catch(r){return{success:!1,message:r instanceof Error?r.message:String(r)}}}async function w3t(e=jte()){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};let t=await _T({authUrl:e});switch(Ne.info("agent:enroll_claim",{status:t.status}),t.status){case"activated":return{success:!0,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,displayName:t.displayName,identityKeyJkt:t.identityKeyJkt,message:`Agent ${t.displayName} (${t.agentId}) is paired to this runtime. Its exportable Ed25519 private identity key remains in an owner-only local file. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet. Payment methods and communication channels are configured separately.`};case"no_pending":return{success:!1,message:'No pairing is in progress on this device \u2014 call enroll_agent with {"action":"start"} first.'};case"not_ready":return{success:!1,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:t.likelyExpired,message:t.likelyExpired?"This pairing has likely expired. Start a fresh pairing ceremony.":`Authorization is not complete for agent ${t.agentId}. Approve the browser request, then claim again.`};case"error":return{success:!1,message:t.message}}}async function wPe(){if(await Za.clearAll(),!!L9e())try{await z9e()}catch(e){Ne.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function E3t(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Ne.info("reset:attempt"),e.localOnly)return await wPe(),Ne.info("reset:success",{localOnly:!0}),{success:!0,message:"Device account state reset locally. The account session credential and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."};try{await xo.logout(void 0,t)}catch{}return await wPe(),Ne.info("reset:success"),{success:!0,message:"Device account state reset. The server session, local account credential, and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."}}async function A3t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(O_(),xT)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{VisaBindingRequiredError:r}=await Promise.resolve().then(()=>(nT(),Kxe));return t instanceof r?{success:!1,binding_required:!0,reason:t.reason,recovery_tool:null,error:t.message,message:`${t.message} Pairing alone does not provision a .visa name or TAP/channel binding.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function x3t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(O_(),xT));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function S3t(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(()=>(O_(),xT)),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 T3t(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(O_(),xT)),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 oo=class{static async subwayRegister(t){return A3t(t||{})}static async subwayFind(t){return x3t(t||{})}static async subwaySend(t){return S3t(t||{})}static async subwayInbox(t){return T3t(t||{})}static async getStatus(t){return h3t(t)}static async feedback(t,r){return y3t(t,r)}static async configList(t){return g3t(t||{})}static async configSet(t){return b3t(t||{})}static async configUnset(t){return _3t(t||{})}static async reset(t,r){return E3t(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?v3t(void 0,t?.force===!0):n==="claim"?w3t():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens identity-pairing approval) or "claim" (activates the approved identity on this runtime).`}}static async payMerchant(t={},r){return AIe(t)}static async ucpCheckoutHandoff(t,r){return ou("ucp_checkout_handoff")&&(await k_(),ou("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."}:_Pe(t)}static async ucpCheckoutReconcile(t,r){if(ou("ucp_checkout_reconcile")&&(await k_(),ou("ucp_checkout_reconcile")))return{success:!1,message:"ucp_checkout_reconcile requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=Date.now(),i=(()=>{try{return new URL(t.business).hostname}catch{return"invalid"}})();Ne.info("ucp_checkout_reconcile:start",{businessHost:i});try{let o=await vPe(t);return Ne.info("ucp_checkout_reconcile:complete",{businessHost:i,checkoutStatus:o.checkoutStatus,reconciliationStatus:o.status,durationMs:Date.now()-n}),o}catch(o){throw Ne.warn("ucp_checkout_reconcile:failed",{businessHost:i,durationMs:Date.now()-n,errorName:o instanceof Error?o.name:"unknown"}),o}}static async payMerchantStatus(t={},r){return EIe(t)}static async startCardMandate(t={},r){return xIe(t)}static async submitFeedback(t,r,n){Ne.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await xo.submitFeedback(t,r,n);return Ne.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Ne.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Ne.info("feedback:list",{limit:t||20});try{let n=await xo.getFeedback(t,r);return Ne.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Ne.error("feedback:error",{error:i}),n}}};function SPe(e){return e==="pay_merchant"}Sl();var dgt="VISA_V4_WALLET_EXPERIMENT",xOr=null;function SOr(){return xOr??!0}var TOr=new Set(["1","true","on","yes"]),IOr=new Set(["0","false","off","no"]),lgt=!1;function RAe(e,t){return lgt||(lgt=!0,Ne.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function BX(){let e=(process.env[dgt]??"").trim().toLowerCase();if(TOr.has(e))return RAe(!0,"env-on");if(IOr.has(e))return RAe(!1,"env-off");e!==""&&Ne.warn("wallet-experiment:unrecognized-env-value",{env:dgt,fallback:"bundled-runtime"});let t=SOr();return RAe(t,t?"bundled-runtime":"runtime-unavailable")}var pgt=null;function fgt(){return pgt??=kAe(),pgt}var POr={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 OOr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...POr},required:[...e.inputSchema.required||[],"user_context"]}}}function NAe(){return BX()?fgt().WALLET_TOOL_DEFS.map(OOr):[]}function mgt(e){return BX()?fgt().WALLET_TOOL_NAMES.includes(e):!1}async function hgt(e,t,r={}){let i=await(await Promise.resolve().then(()=>Me(kAe()))).dispatchWalletTool(e,t,{logger:Ne,merchantDirectorySearch:r.merchantDirectorySearch});if(r.emitTelemetry&&(e==="wallet_pay"||e==="wallet_directory_pay"))try{let o=COr(e,t,i);o&&await r.emitTelemetry([o])}catch(o){Ne.warn("wallet-experiment:telemetry-failed",{tool:e,error:o instanceof Error?o.message:String(o)})}return i}function COr(e,t,r){if(e!=="wallet_pay"&&e!=="wallet_directory_pay")return null;let n=r.payment&&typeof r.payment=="object"&&!Array.isArray(r.payment)?r.payment:null,i=r.receipt&&typeof r.receipt=="object"&&!Array.isArray(r.receipt)?r.receipt:null,o=r.status==="reconciling"&&r.settled===!1&&r.authorizationDisclosed===!0&&r.reservationRecorded===!0&&n?.status==="indeterminate",s=r.settled===!1&&r.authorizationDisclosed===!0&&n?.status==="indeterminate";if(!o&&!i&&!s)return null;let a=o?n:i??n,c=typeof a.exposureUsd=="string"?a.exposureUsd:typeof a.amountUsd=="string"?a.amountUsd:"",u=Number(c.replace(/[$,\s]/g,""));if(!Number.isFinite(u)||u<=0)return null;let d=r.directory&&typeof r.directory=="object"&&!Array.isArray(r.directory)?r.directory:null,l=d?.selection&&typeof d.selection=="object"&&!Array.isArray(d.selection)?d.selection:null,p=typeof t.url=="string"?t.url:typeof l?.url=="string"?l.url:"",f="Pay-per-use service";try{f=new URL(p).hostname.toLowerCase()}catch{}let m=typeof a.timestamp=="string"?a.timestamp:new Date().toISOString(),h=typeof a.network=="string"?a.network:null,y=typeof a.scheme=="string"?a.scheme:null,v=typeof a.merchantReportedTxHash=="string"?a.merchantReportedTxHash:typeof a.txHash=="string"?a.txHash:null,E=typeof a.authorizationRef=="string"?a.authorizationRef:typeof a.settlementHash=="string"?a.settlementHash:null,_=r.response&&typeof r.response=="object"&&!Array.isArray(r.response)?r.response:null,w=typeof _?.status=="number"&&Number.isInteger(_.status)?_.status:null;return{timestamp:m,tool_name:e,user_prompt:"",tool_params:JSON.stringify({merchant_host:f,network:h,scheme:y}),result_success:!0,result_error:null,result_json:JSON.stringify(o?{status:"reconciling",settled:!1,authorizationDisclosed:!0,reservationRecorded:!0,payment:{status:"indeterminate",network:h,scheme:y,...E?{authorizationRef:E}:{},...v?{merchantReportedTxHash:v}:{}}}:{status:"unverified",authorizationDisclosed:!0,reservationRecorded:!1,payment:{status:"legacy_unverified",network:h,scheme:y,...E?{authorizationRef:E}:{},...v?{merchantReportedTxHash:v}:{}}}),payment_rail:"stablecoin",payment_amount:u,payment_currency:"USDC",merchant_name:f,transaction_id:null,tx_hash:null,protocol:"x402",http_status:w,duration_ms:0,source:"cli",endpoint:"/v4/wallet",resolved_model:null,session_budget_id:null}}Sl();var BAe=["pay_merchant"],kOr={pay_merchant:"merchant checkout"};function ROr(e){return kOr[e]||e}var ygt={};function ggt(e){let t=ygt[e]??0;return ygt[e]=t+1,t}function bgt(e,t,r){return BAe.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${ROr(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 UX=Me(require("crypto")),MX=Me(require("tty")),u4=Me(require("fs")),UAe=Me(require("os")),jX=Me(require("path"));rQ();g4();var NOr=new Set(["connect","disconnect","connections"]);function BOr(e){return e!==void 0&&NOr.has(e)}function jOr(e){return/-rc\.|-beta\./.test(e)}function jAe(e){return UX.createHash("sha256").update(e.trim()).digest("hex")}function _gt(e){return u0==="SKIP"?!0:UX.timingSafeEqual(Buffer.from(jAe(e)),Buffer.from(u0))}function UOr(){return jX.join(UAe.homedir(),".visa-mcp","agent-credential.json")}function MOr(){let e=process.env.VISA_V4_HOME||jX.join(UAe.homedir(),".visa-v4");return jX.join(e,"turnkey.json")}function qOr(){try{let e=u4.readFileSync(UOr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=u4.readFileSync(MOr(),"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 DOr(){try{let e=u4.openSync("/dev/tty","r+"),t=new MX.ReadStream(e),r=new MX.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{u4.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 LOr(e){return new Promise((t,r)=>{let n;try{n=DOr()}catch(d){r(d);return}let{input:i,output:o,cleanupStreams:s}=n,a=()=>{i.off("data",u);try{i.setRawMode?.(!1)}catch{}s()};o.write(e),i.setRawMode?.(!0),i.resume(),i.setEncoding("utf8");let c="",u=d=>{d==="\r"||d===`
20830
20830
  `?(o.write(`
20831
20831
  `),a(),t(c)):d===""?(o.write(`