@ambprotocol/ride-cli 1.4.0 → 1.5.0

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.
Files changed (2) hide show
  1. package/amb +293 -146
  2. package/package.json +3 -3
package/amb CHANGED
@@ -1,21 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var y={services:{authServerUrl:"https://backend.clutchwalletserver.xyz",authWebappUrl:"https://tada-agent.clutchwalletserver.xyz",privyAppId:"cmoh8lukp03r90cl5vn7go5w5",cryptoGatewayUrl:"https://backend.clutchwalletserver.xyz/tada-ton",memberGatewayUrls:{SG:"https://cli.tadaapis.com",US:"https://cli-us.tadaapis.com"},defaultRegion:"SG"},networks:{depositNetworks:["ETHEREUM"],paymentNetwork:"BASE",paymentCurrency:"USDC_base",paymentUsdcAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",bridgeSource:"ETHEREUM",bridgeDestination:"BASE"},providers:{tada:{memberClientId:"tada-rider-cli",memberClientSecret:"5a04db79fc131fa632cf1d4ac5659ca49349f1746e949b5dde7649e4bd58547c"}},artifact:{cliVersion:"1.4.0",gitSha:"2c401ca5"},install:{mode:"npm",repoBranch:"main",expectedCliSha:"2c401ca5",minimumCliVersion:"1.3.0"},bridgePolicy:{minimumUsdc:"1",maxFeeBufferPct:20,burnGraceBlocks:30,mintMaxAttempts:5,leaseSeconds:120,logChunkBlocks:2e3}};import Bo from"fs";import{spawn as Yu}from"child_process";function Tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sn(e){return e==null?"null":String(e)}function Ws(e,t){let r=" ".repeat(t),n=[];for(let s of e)if(Tn(s)||Array.isArray(s)){let i=An(s,t+1),o=i[0].slice((t+1)*2);n.push(`${r}- ${o}`,...i.slice(1))}else typeof s=="string"&&s.includes(`
2
+ import { createRequire as __ambCreateRequire } from 'node:module'; const require = __ambCreateRequire(import.meta.url);
3
+ var _A=Object.create;var ed=Object.defineProperty;var EA=Object.getOwnPropertyDescriptor;var TA=Object.getOwnPropertyNames;var bA=Object.getPrototypeOf,vA=Object.prototype.hasOwnProperty;var ne=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xA=(e,t)=>()=>(e&&(t=e(e=0)),t);var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var RA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of TA(t))!vA.call(e,s)&&s!==r&&ed(e,s,{get:()=>t[s],enumerable:!(n=EA(t,s))||n.enumerable});return e};var AA=(e,t,r)=>(r=e!=null?_A(bA(e)):{},RA(t||!e||!e.__esModule?ed(r,"default",{value:e,enumerable:!0}):r,e));var y,p=xA(()=>{y={services:{authServerUrl:"https://backend.clutchwalletserver.xyz",ambTelemetryServiceUrl:"https://backend.clutchwalletserver.xyz/amb-telemetry",authWebappUrl:"https://tada-agent.clutchwalletserver.xyz",privyAppId:"cmoh8lukp03r90cl5vn7go5w5",cryptoGatewayUrl:"https://backend.clutchwalletserver.xyz/tada-ton",memberGatewayUrls:{SG:"https://cli.tadaapis.com",US:"https://cli-us.tadaapis.com"},defaultRegion:"SG"},networks:{depositNetworks:["ETHEREUM"],paymentNetwork:"BASE",paymentCurrency:"USDC_base",paymentUsdcAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",bridgeSource:"ETHEREUM",bridgeDestination:"BASE"},providers:{tada:{memberClientId:"tada-rider-cli",memberClientSecret:"5a04db79fc131fa632cf1d4ac5659ca49349f1746e949b5dde7649e4bd58547c"}},artifact:{cliVersion:"1.5.0",gitSha:"5f5c98b8"},install:{mode:"npm",repoBranch:"main",expectedCliSha:"5f5c98b8",minimumCliVersion:"1.3.0"},bridgePolicy:{minimumUsdc:"1",maxFeeBufferPct:20,burnGraceBlocks:30,mintMaxAttempts:5,leaseSeconds:120,logChunkBlocks:2e3}}});var op=P((oq,ap)=>{"use strict";p();var ip=ne("stream").Stream,Gw=ne("util");ap.exports=Ot;function Ot(){this.source=null,this.dataSize=0,this.maxDataSize=1024*1024,this.pauseStream=!0,this._maxDataSizeExceeded=!1,this._released=!1,this._bufferedEvents=[]}Gw.inherits(Ot,ip);Ot.create=function(e,t){var r=new this;t=t||{};for(var n in t)r[n]=t[n];r.source=e;var s=e.emit;return e.emit=function(){return r._handleEmit(arguments),s.apply(e,arguments)},e.on("error",function(){}),r.pauseStream&&e.pause(),r};Object.defineProperty(Ot.prototype,"readable",{configurable:!0,enumerable:!0,get:function(){return this.source.readable}});Ot.prototype.setEncoding=function(){return this.source.setEncoding.apply(this.source,arguments)};Ot.prototype.resume=function(){this._released||this.release(),this.source.resume()};Ot.prototype.pause=function(){this.source.pause()};Ot.prototype.release=function(){this._released=!0,this._bufferedEvents.forEach(function(e){this.emit.apply(this,e)}.bind(this)),this._bufferedEvents=[]};Ot.prototype.pipe=function(){var e=ip.prototype.pipe.apply(this,arguments);return this.resume(),e};Ot.prototype._handleEmit=function(e){if(this._released){this.emit.apply(this,e);return}e[0]==="data"&&(this.dataSize+=e[1].length,this._checkIfMaxDataSizeExceeded()),this._bufferedEvents.push(e)};Ot.prototype._checkIfMaxDataSizeExceeded=function(){if(!this._maxDataSizeExceeded&&!(this.dataSize<=this.maxDataSize)){this._maxDataSizeExceeded=!0;var e="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this.emit("error",new Error(e))}}});var dp=P((lq,up)=>{"use strict";p();var Hw=ne("util"),lp=ne("stream").Stream,cp=op();up.exports=xe;function xe(){this.writable=!1,this.readable=!0,this.dataSize=0,this.maxDataSize=2*1024*1024,this.pauseStreams=!0,this._released=!1,this._streams=[],this._currentStream=null,this._insideLoop=!1,this._pendingNext=!1}Hw.inherits(xe,lp);xe.create=function(e){var t=new this;e=e||{};for(var r in e)t[r]=e[r];return t};xe.isStreamLike=function(e){return typeof e!="function"&&typeof e!="string"&&typeof e!="boolean"&&typeof e!="number"&&!Buffer.isBuffer(e)};xe.prototype.append=function(e){var t=xe.isStreamLike(e);if(t){if(!(e instanceof cp)){var r=cp.create(e,{maxDataSize:1/0,pauseStream:this.pauseStreams});e.on("data",this._checkDataSize.bind(this)),e=r}this._handleErrors(e),this.pauseStreams&&e.pause()}return this._streams.push(e),this};xe.prototype.pipe=function(e,t){return lp.prototype.pipe.call(this,e,t),this.resume(),e};xe.prototype._getNext=function(){if(this._currentStream=null,this._insideLoop){this._pendingNext=!0;return}this._insideLoop=!0;try{do this._pendingNext=!1,this._realGetNext();while(this._pendingNext)}finally{this._insideLoop=!1}};xe.prototype._realGetNext=function(){var e=this._streams.shift();if(typeof e>"u"){this.end();return}if(typeof e!="function"){this._pipeNext(e);return}var t=e;t(function(r){var n=xe.isStreamLike(r);n&&(r.on("data",this._checkDataSize.bind(this)),this._handleErrors(r)),this._pipeNext(r)}.bind(this))};xe.prototype._pipeNext=function(e){this._currentStream=e;var t=xe.isStreamLike(e);if(t){e.on("end",this._getNext.bind(this)),e.pipe(this,{end:!1});return}var r=e;this.write(r),this._getNext()};xe.prototype._handleErrors=function(e){var t=this;e.on("error",function(r){t._emitError(r)})};xe.prototype.write=function(e){this.emit("data",e)};xe.prototype.pause=function(){this.pauseStreams&&(this.pauseStreams&&this._currentStream&&typeof this._currentStream.pause=="function"&&this._currentStream.pause(),this.emit("pause"))};xe.prototype.resume=function(){this._released||(this._released=!0,this.writable=!0,this._getNext()),this.pauseStreams&&this._currentStream&&typeof this._currentStream.resume=="function"&&this._currentStream.resume(),this.emit("resume")};xe.prototype.end=function(){this._reset(),this.emit("end")};xe.prototype.destroy=function(){this._reset(),this.emit("close")};xe.prototype._reset=function(){this.writable=!1,this._streams=[],this._currentStream=null};xe.prototype._checkDataSize=function(){if(this._updateDataSize(),!(this.dataSize<=this.maxDataSize)){var e="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this._emitError(new Error(e))}};xe.prototype._updateDataSize=function(){this.dataSize=0;var e=this;this._streams.forEach(function(t){t.dataSize&&(e.dataSize+=t.dataSize)}),this._currentStream&&this._currentStream.dataSize&&(this.dataSize+=this._currentStream.dataSize)};xe.prototype._emitError=function(e){this._reset(),this.emit("error",e)}});var pp=P((dq,$w)=>{$w.exports={"application/1d-interleaved-parityfec":{source:"iana"},"application/3gpdash-qoe-report+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/3gpp-ims+xml":{source:"iana",compressible:!0},"application/3gpphal+json":{source:"iana",compressible:!0},"application/3gpphalforms+json":{source:"iana",compressible:!0},"application/a2l":{source:"iana"},"application/ace+cbor":{source:"iana"},"application/activemessage":{source:"iana"},"application/activity+json":{source:"iana",compressible:!0},"application/alto-costmap+json":{source:"iana",compressible:!0},"application/alto-costmapfilter+json":{source:"iana",compressible:!0},"application/alto-directory+json":{source:"iana",compressible:!0},"application/alto-endpointcost+json":{source:"iana",compressible:!0},"application/alto-endpointcostparams+json":{source:"iana",compressible:!0},"application/alto-endpointprop+json":{source:"iana",compressible:!0},"application/alto-endpointpropparams+json":{source:"iana",compressible:!0},"application/alto-error+json":{source:"iana",compressible:!0},"application/alto-networkmap+json":{source:"iana",compressible:!0},"application/alto-networkmapfilter+json":{source:"iana",compressible:!0},"application/alto-updatestreamcontrol+json":{source:"iana",compressible:!0},"application/alto-updatestreamparams+json":{source:"iana",compressible:!0},"application/aml":{source:"iana"},"application/andrew-inset":{source:"iana",extensions:["ez"]},"application/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"application/at+jwt":{source:"iana"},"application/atf":{source:"iana"},"application/atfx":{source:"iana"},"application/atom+xml":{source:"iana",compressible:!0,extensions:["atom"]},"application/atomcat+xml":{source:"iana",compressible:!0,extensions:["atomcat"]},"application/atomdeleted+xml":{source:"iana",compressible:!0,extensions:["atomdeleted"]},"application/atomicmail":{source:"iana"},"application/atomsvc+xml":{source:"iana",compressible:!0,extensions:["atomsvc"]},"application/atsc-dwd+xml":{source:"iana",compressible:!0,extensions:["dwd"]},"application/atsc-dynamic-event-message":{source:"iana"},"application/atsc-held+xml":{source:"iana",compressible:!0,extensions:["held"]},"application/atsc-rdt+json":{source:"iana",compressible:!0},"application/atsc-rsat+xml":{source:"iana",compressible:!0,extensions:["rsat"]},"application/atxml":{source:"iana"},"application/auth-policy+xml":{source:"iana",compressible:!0},"application/bacnet-xdd+zip":{source:"iana",compressible:!1},"application/batch-smtp":{source:"iana"},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/beep+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/calendar+json":{source:"iana",compressible:!0},"application/calendar+xml":{source:"iana",compressible:!0,extensions:["xcs"]},"application/call-completion":{source:"iana"},"application/cals-1840":{source:"iana"},"application/captive+json":{source:"iana",compressible:!0},"application/cbor":{source:"iana"},"application/cbor-seq":{source:"iana"},"application/cccex":{source:"iana"},"application/ccmp+xml":{source:"iana",compressible:!0},"application/ccxml+xml":{source:"iana",compressible:!0,extensions:["ccxml"]},"application/cdfx+xml":{source:"iana",compressible:!0,extensions:["cdfx"]},"application/cdmi-capability":{source:"iana",extensions:["cdmia"]},"application/cdmi-container":{source:"iana",extensions:["cdmic"]},"application/cdmi-domain":{source:"iana",extensions:["cdmid"]},"application/cdmi-object":{source:"iana",extensions:["cdmio"]},"application/cdmi-queue":{source:"iana",extensions:["cdmiq"]},"application/cdni":{source:"iana"},"application/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"application/clr":{source:"iana"},"application/clue+xml":{source:"iana",compressible:!0},"application/clue_info+xml":{source:"iana",compressible:!0},"application/cms":{source:"iana"},"application/cnrp+xml":{source:"iana",compressible:!0},"application/coap-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{source:"iana"},"application/conference-info+xml":{source:"iana",compressible:!0},"application/cose":{source:"iana"},"application/cose-key":{source:"iana"},"application/cose-key-set":{source:"iana"},"application/cpl+xml":{source:"iana",compressible:!0,extensions:["cpl"]},"application/csrattrs":{source:"iana"},"application/csta+xml":{source:"iana",compressible:!0},"application/cstadata+xml":{source:"iana",compressible:!0},"application/csvm+json":{source:"iana",compressible:!0},"application/cu-seeme":{source:"apache",extensions:["cu"]},"application/cwt":{source:"iana"},"application/cybercash":{source:"iana"},"application/dart":{compressible:!0},"application/dash+xml":{source:"iana",compressible:!0,extensions:["mpd"]},"application/dash-patch+xml":{source:"iana",compressible:!0,extensions:["mpp"]},"application/dashdelta":{source:"iana"},"application/davmount+xml":{source:"iana",compressible:!0,extensions:["davmount"]},"application/dca-rft":{source:"iana"},"application/dcd":{source:"iana"},"application/dec-dx":{source:"iana"},"application/dialog-info+xml":{source:"iana",compressible:!0},"application/dicom":{source:"iana"},"application/dicom+json":{source:"iana",compressible:!0},"application/dicom+xml":{source:"iana",compressible:!0},"application/dii":{source:"iana"},"application/dit":{source:"iana"},"application/dns":{source:"iana"},"application/dns+json":{source:"iana",compressible:!0},"application/dns-message":{source:"iana"},"application/docbook+xml":{source:"apache",compressible:!0,extensions:["dbk"]},"application/dots+cbor":{source:"iana"},"application/dskpp+xml":{source:"iana",compressible:!0},"application/dssc+der":{source:"iana",extensions:["dssc"]},"application/dssc+xml":{source:"iana",compressible:!0,extensions:["xdssc"]},"application/dvcs":{source:"iana"},"application/ecmascript":{source:"iana",compressible:!0,extensions:["es","ecma"]},"application/edi-consent":{source:"iana"},"application/edi-x12":{source:"iana",compressible:!1},"application/edifact":{source:"iana",compressible:!1},"application/efi":{source:"iana"},"application/elm+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/elm+xml":{source:"iana",compressible:!0},"application/emergencycalldata.cap+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/emergencycalldata.comment+xml":{source:"iana",compressible:!0},"application/emergencycalldata.control+xml":{source:"iana",compressible:!0},"application/emergencycalldata.deviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.ecall.msd":{source:"iana"},"application/emergencycalldata.providerinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.serviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.subscriberinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.veds+xml":{source:"iana",compressible:!0},"application/emma+xml":{source:"iana",compressible:!0,extensions:["emma"]},"application/emotionml+xml":{source:"iana",compressible:!0,extensions:["emotionml"]},"application/encaprtp":{source:"iana"},"application/epp+xml":{source:"iana",compressible:!0},"application/epub+zip":{source:"iana",compressible:!1,extensions:["epub"]},"application/eshop":{source:"iana"},"application/exi":{source:"iana",extensions:["exi"]},"application/expect-ct-report+json":{source:"iana",compressible:!0},"application/express":{source:"iana",extensions:["exp"]},"application/fastinfoset":{source:"iana"},"application/fastsoap":{source:"iana"},"application/fdt+xml":{source:"iana",compressible:!0,extensions:["fdt"]},"application/fhir+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/fhir+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/fido.trusted-apps+json":{compressible:!0},"application/fits":{source:"iana"},"application/flexfec":{source:"iana"},"application/font-sfnt":{source:"iana"},"application/font-tdpfr":{source:"iana",extensions:["pfr"]},"application/font-woff":{source:"iana",compressible:!1},"application/framework-attributes+xml":{source:"iana",compressible:!0},"application/geo+json":{source:"iana",compressible:!0,extensions:["geojson"]},"application/geo+json-seq":{source:"iana"},"application/geopackage+sqlite3":{source:"iana"},"application/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"application/gxf":{source:"apache",extensions:["gxf"]},"application/gzip":{source:"iana",compressible:!1,extensions:["gz"]},"application/h224":{source:"iana"},"application/held+xml":{source:"iana",compressible:!0},"application/hjson":{extensions:["hjson"]},"application/http":{source:"iana"},"application/hyperstudio":{source:"iana",extensions:["stk"]},"application/ibe-key-request+xml":{source:"iana",compressible:!0},"application/ibe-pkg-reply+xml":{source:"iana",compressible:!0},"application/ibe-pp-data":{source:"iana"},"application/iges":{source:"iana"},"application/im-iscomposing+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/index":{source:"iana"},"application/index.cmd":{source:"iana"},"application/index.obj":{source:"iana"},"application/index.response":{source:"iana"},"application/index.vnd":{source:"iana"},"application/inkml+xml":{source:"iana",compressible:!0,extensions:["ink","inkml"]},"application/iotp":{source:"iana"},"application/ipfix":{source:"iana",extensions:["ipfix"]},"application/ipp":{source:"iana"},"application/isup":{source:"iana"},"application/its+xml":{source:"iana",compressible:!0,extensions:["its"]},"application/java-archive":{source:"apache",compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{source:"apache",compressible:!1,extensions:["ser"]},"application/java-vm":{source:"apache",compressible:!1,extensions:["class"]},"application/javascript":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"application/jf2feed+json":{source:"iana",compressible:!0},"application/jose":{source:"iana"},"application/jose+json":{source:"iana",compressible:!0},"application/jrd+json":{source:"iana",compressible:!0},"application/jscalendar+json":{source:"iana",compressible:!0},"application/json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{source:"iana",compressible:!0},"application/json-seq":{source:"iana"},"application/json5":{extensions:["json5"]},"application/jsonml+json":{source:"apache",compressible:!0,extensions:["jsonml"]},"application/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"application/jwt":{source:"iana"},"application/kpml-request+xml":{source:"iana",compressible:!0},"application/kpml-response+xml":{source:"iana",compressible:!0},"application/ld+json":{source:"iana",compressible:!0,extensions:["jsonld"]},"application/lgr+xml":{source:"iana",compressible:!0,extensions:["lgr"]},"application/link-format":{source:"iana"},"application/load-control+xml":{source:"iana",compressible:!0},"application/lost+xml":{source:"iana",compressible:!0,extensions:["lostxml"]},"application/lostsync+xml":{source:"iana",compressible:!0},"application/lpf+zip":{source:"iana",compressible:!1},"application/lxf":{source:"iana"},"application/mac-binhex40":{source:"iana",extensions:["hqx"]},"application/mac-compactpro":{source:"apache",extensions:["cpt"]},"application/macwriteii":{source:"iana"},"application/mads+xml":{source:"iana",compressible:!0,extensions:["mads"]},"application/manifest+json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{source:"iana",extensions:["mrc"]},"application/marcxml+xml":{source:"iana",compressible:!0,extensions:["mrcx"]},"application/mathematica":{source:"iana",extensions:["ma","nb","mb"]},"application/mathml+xml":{source:"iana",compressible:!0,extensions:["mathml"]},"application/mathml-content+xml":{source:"iana",compressible:!0},"application/mathml-presentation+xml":{source:"iana",compressible:!0},"application/mbms-associated-procedure-description+xml":{source:"iana",compressible:!0},"application/mbms-deregister+xml":{source:"iana",compressible:!0},"application/mbms-envelope+xml":{source:"iana",compressible:!0},"application/mbms-msk+xml":{source:"iana",compressible:!0},"application/mbms-msk-response+xml":{source:"iana",compressible:!0},"application/mbms-protection-description+xml":{source:"iana",compressible:!0},"application/mbms-reception-report+xml":{source:"iana",compressible:!0},"application/mbms-register+xml":{source:"iana",compressible:!0},"application/mbms-register-response+xml":{source:"iana",compressible:!0},"application/mbms-schedule+xml":{source:"iana",compressible:!0},"application/mbms-user-service-description+xml":{source:"iana",compressible:!0},"application/mbox":{source:"iana",extensions:["mbox"]},"application/media-policy-dataset+xml":{source:"iana",compressible:!0,extensions:["mpf"]},"application/media_control+xml":{source:"iana",compressible:!0},"application/mediaservercontrol+xml":{source:"iana",compressible:!0,extensions:["mscml"]},"application/merge-patch+json":{source:"iana",compressible:!0},"application/metalink+xml":{source:"apache",compressible:!0,extensions:["metalink"]},"application/metalink4+xml":{source:"iana",compressible:!0,extensions:["meta4"]},"application/mets+xml":{source:"iana",compressible:!0,extensions:["mets"]},"application/mf4":{source:"iana"},"application/mikey":{source:"iana"},"application/mipc":{source:"iana"},"application/missing-blocks+cbor-seq":{source:"iana"},"application/mmt-aei+xml":{source:"iana",compressible:!0,extensions:["maei"]},"application/mmt-usd+xml":{source:"iana",compressible:!0,extensions:["musd"]},"application/mods+xml":{source:"iana",compressible:!0,extensions:["mods"]},"application/moss-keys":{source:"iana"},"application/moss-signature":{source:"iana"},"application/mosskey-data":{source:"iana"},"application/mosskey-request":{source:"iana"},"application/mp21":{source:"iana",extensions:["m21","mp21"]},"application/mp4":{source:"iana",extensions:["mp4s","m4p"]},"application/mpeg4-generic":{source:"iana"},"application/mpeg4-iod":{source:"iana"},"application/mpeg4-iod-xmt":{source:"iana"},"application/mrb-consumer+xml":{source:"iana",compressible:!0},"application/mrb-publish+xml":{source:"iana",compressible:!0},"application/msc-ivr+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msc-mixer+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msword":{source:"iana",compressible:!1,extensions:["doc","dot"]},"application/mud+json":{source:"iana",compressible:!0},"application/multipart-core":{source:"iana"},"application/mxf":{source:"iana",extensions:["mxf"]},"application/n-quads":{source:"iana",extensions:["nq"]},"application/n-triples":{source:"iana",extensions:["nt"]},"application/nasdata":{source:"iana"},"application/news-checkgroups":{source:"iana",charset:"US-ASCII"},"application/news-groupinfo":{source:"iana",charset:"US-ASCII"},"application/news-transmission":{source:"iana"},"application/nlsml+xml":{source:"iana",compressible:!0},"application/node":{source:"iana",extensions:["cjs"]},"application/nss":{source:"iana"},"application/oauth-authz-req+jwt":{source:"iana"},"application/oblivious-dns-message":{source:"iana"},"application/ocsp-request":{source:"iana"},"application/ocsp-response":{source:"iana"},"application/octet-stream":{source:"iana",compressible:!1,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{source:"iana",extensions:["oda"]},"application/odm+xml":{source:"iana",compressible:!0},"application/odx":{source:"iana"},"application/oebps-package+xml":{source:"iana",compressible:!0,extensions:["opf"]},"application/ogg":{source:"iana",compressible:!1,extensions:["ogx"]},"application/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{source:"iana",compressible:!0},"application/oscore":{source:"iana"},"application/oxps":{source:"iana",extensions:["oxps"]},"application/p21":{source:"iana"},"application/p21+zip":{source:"iana",compressible:!1},"application/p2p-overlay+xml":{source:"iana",compressible:!0,extensions:["relo"]},"application/parityfec":{source:"iana"},"application/passport":{source:"iana"},"application/patch-ops-error+xml":{source:"iana",compressible:!0,extensions:["xer"]},"application/pdf":{source:"iana",compressible:!1,extensions:["pdf"]},"application/pdx":{source:"iana"},"application/pem-certificate-chain":{source:"iana"},"application/pgp-encrypted":{source:"iana",compressible:!1,extensions:["pgp"]},"application/pgp-keys":{source:"iana",extensions:["asc"]},"application/pgp-signature":{source:"iana",extensions:["asc","sig"]},"application/pics-rules":{source:"apache",extensions:["prf"]},"application/pidf+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pidf-diff+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pkcs10":{source:"iana",extensions:["p10"]},"application/pkcs12":{source:"iana"},"application/pkcs7-mime":{source:"iana",extensions:["p7m","p7c"]},"application/pkcs7-signature":{source:"iana",extensions:["p7s"]},"application/pkcs8":{source:"iana",extensions:["p8"]},"application/pkcs8-encrypted":{source:"iana"},"application/pkix-attr-cert":{source:"iana",extensions:["ac"]},"application/pkix-cert":{source:"iana",extensions:["cer"]},"application/pkix-crl":{source:"iana",extensions:["crl"]},"application/pkix-pkipath":{source:"iana",extensions:["pkipath"]},"application/pkixcmp":{source:"iana",extensions:["pki"]},"application/pls+xml":{source:"iana",compressible:!0,extensions:["pls"]},"application/poc-settings+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/postscript":{source:"iana",compressible:!0,extensions:["ai","eps","ps"]},"application/ppsp-tracker+json":{source:"iana",compressible:!0},"application/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"application/prs.alvestrand.titrax-sheet":{source:"iana"},"application/prs.cww":{source:"iana",extensions:["cww"]},"application/prs.cyn":{source:"iana",charset:"7-BIT"},"application/prs.hpub+zip":{source:"iana",compressible:!1},"application/prs.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0},"application/pskc+xml":{source:"iana",compressible:!0,extensions:["pskcxml"]},"application/pvd+json":{source:"iana",compressible:!0},"application/qsig":{source:"iana"},"application/raml+yaml":{compressible:!0,extensions:["raml"]},"application/raptorfec":{source:"iana"},"application/rdap+json":{source:"iana",compressible:!0},"application/rdf+xml":{source:"iana",compressible:!0,extensions:["rdf","owl"]},"application/reginfo+xml":{source:"iana",compressible:!0,extensions:["rif"]},"application/relax-ng-compact-syntax":{source:"iana",extensions:["rnc"]},"application/remote-printing":{source:"iana"},"application/reputon+json":{source:"iana",compressible:!0},"application/resource-lists+xml":{source:"iana",compressible:!0,extensions:["rl"]},"application/resource-lists-diff+xml":{source:"iana",compressible:!0,extensions:["rld"]},"application/rfc+xml":{source:"iana",compressible:!0},"application/riscos":{source:"iana"},"application/rlmi+xml":{source:"iana",compressible:!0},"application/rls-services+xml":{source:"iana",compressible:!0,extensions:["rs"]},"application/route-apd+xml":{source:"iana",compressible:!0,extensions:["rapd"]},"application/route-s-tsid+xml":{source:"iana",compressible:!0,extensions:["sls"]},"application/route-usd+xml":{source:"iana",compressible:!0,extensions:["rusd"]},"application/rpki-ghostbusters":{source:"iana",extensions:["gbr"]},"application/rpki-manifest":{source:"iana",extensions:["mft"]},"application/rpki-publication":{source:"iana"},"application/rpki-roa":{source:"iana",extensions:["roa"]},"application/rpki-updown":{source:"iana"},"application/rsd+xml":{source:"apache",compressible:!0,extensions:["rsd"]},"application/rss+xml":{source:"apache",compressible:!0,extensions:["rss"]},"application/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"application/rtploopback":{source:"iana"},"application/rtx":{source:"iana"},"application/samlassertion+xml":{source:"iana",compressible:!0},"application/samlmetadata+xml":{source:"iana",compressible:!0},"application/sarif+json":{source:"iana",compressible:!0},"application/sarif-external-properties+json":{source:"iana",compressible:!0},"application/sbe":{source:"iana"},"application/sbml+xml":{source:"iana",compressible:!0,extensions:["sbml"]},"application/scaip+xml":{source:"iana",compressible:!0},"application/scim+json":{source:"iana",compressible:!0},"application/scvp-cv-request":{source:"iana",extensions:["scq"]},"application/scvp-cv-response":{source:"iana",extensions:["scs"]},"application/scvp-vp-request":{source:"iana",extensions:["spq"]},"application/scvp-vp-response":{source:"iana",extensions:["spp"]},"application/sdp":{source:"iana",extensions:["sdp"]},"application/secevent+jwt":{source:"iana"},"application/senml+cbor":{source:"iana"},"application/senml+json":{source:"iana",compressible:!0},"application/senml+xml":{source:"iana",compressible:!0,extensions:["senmlx"]},"application/senml-etch+cbor":{source:"iana"},"application/senml-etch+json":{source:"iana",compressible:!0},"application/senml-exi":{source:"iana"},"application/sensml+cbor":{source:"iana"},"application/sensml+json":{source:"iana",compressible:!0},"application/sensml+xml":{source:"iana",compressible:!0,extensions:["sensmlx"]},"application/sensml-exi":{source:"iana"},"application/sep+xml":{source:"iana",compressible:!0},"application/sep-exi":{source:"iana"},"application/session-info":{source:"iana"},"application/set-payment":{source:"iana"},"application/set-payment-initiation":{source:"iana",extensions:["setpay"]},"application/set-registration":{source:"iana"},"application/set-registration-initiation":{source:"iana",extensions:["setreg"]},"application/sgml":{source:"iana"},"application/sgml-open-catalog":{source:"iana"},"application/shf+xml":{source:"iana",compressible:!0,extensions:["shf"]},"application/sieve":{source:"iana",extensions:["siv","sieve"]},"application/simple-filter+xml":{source:"iana",compressible:!0},"application/simple-message-summary":{source:"iana"},"application/simplesymbolcontainer":{source:"iana"},"application/sipc":{source:"iana"},"application/slate":{source:"iana"},"application/smil":{source:"iana"},"application/smil+xml":{source:"iana",compressible:!0,extensions:["smi","smil"]},"application/smpte336m":{source:"iana"},"application/soap+fastinfoset":{source:"iana"},"application/soap+xml":{source:"iana",compressible:!0},"application/sparql-query":{source:"iana",extensions:["rq"]},"application/sparql-results+xml":{source:"iana",compressible:!0,extensions:["srx"]},"application/spdx+json":{source:"iana",compressible:!0},"application/spirits-event+xml":{source:"iana",compressible:!0},"application/sql":{source:"iana"},"application/srgs":{source:"iana",extensions:["gram"]},"application/srgs+xml":{source:"iana",compressible:!0,extensions:["grxml"]},"application/sru+xml":{source:"iana",compressible:!0,extensions:["sru"]},"application/ssdl+xml":{source:"apache",compressible:!0,extensions:["ssdl"]},"application/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/stix+json":{source:"iana",compressible:!0},"application/swid+xml":{source:"iana",compressible:!0,extensions:["swidtag"]},"application/tamp-apex-update":{source:"iana"},"application/tamp-apex-update-confirm":{source:"iana"},"application/tamp-community-update":{source:"iana"},"application/tamp-community-update-confirm":{source:"iana"},"application/tamp-error":{source:"iana"},"application/tamp-sequence-adjust":{source:"iana"},"application/tamp-sequence-adjust-confirm":{source:"iana"},"application/tamp-status-query":{source:"iana"},"application/tamp-status-response":{source:"iana"},"application/tamp-update":{source:"iana"},"application/tamp-update-confirm":{source:"iana"},"application/tar":{compressible:!0},"application/taxii+json":{source:"iana",compressible:!0},"application/td+json":{source:"iana",compressible:!0},"application/tei+xml":{source:"iana",compressible:!0,extensions:["tei","teicorpus"]},"application/tetra_isi":{source:"iana"},"application/thraud+xml":{source:"iana",compressible:!0,extensions:["tfi"]},"application/timestamp-query":{source:"iana"},"application/timestamp-reply":{source:"iana"},"application/timestamped-data":{source:"iana",extensions:["tsd"]},"application/tlsrpt+gzip":{source:"iana"},"application/tlsrpt+json":{source:"iana",compressible:!0},"application/tnauthlist":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"application/ttml+xml":{source:"iana",compressible:!0,extensions:["ttml"]},"application/tve-trigger":{source:"iana"},"application/tzif":{source:"iana"},"application/tzif-leap":{source:"iana"},"application/ubjson":{compressible:!1,extensions:["ubj"]},"application/ulpfec":{source:"iana"},"application/urc-grpsheet+xml":{source:"iana",compressible:!0},"application/urc-ressheet+xml":{source:"iana",compressible:!0,extensions:["rsheet"]},"application/urc-targetdesc+xml":{source:"iana",compressible:!0,extensions:["td"]},"application/urc-uisocketdesc+xml":{source:"iana",compressible:!0},"application/vcard+json":{source:"iana",compressible:!0},"application/vcard+xml":{source:"iana",compressible:!0},"application/vemmi":{source:"iana"},"application/vividence.scriptfile":{source:"apache"},"application/vnd.1000minds.decision-model+xml":{source:"iana",compressible:!0,extensions:["1km"]},"application/vnd.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{source:"iana"},"application/vnd.3gpp.access-transfer-events+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.bsf+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gmop+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gtpc":{source:"iana"},"application/vnd.3gpp.interworking-data":{source:"iana"},"application/vnd.3gpp.lpp":{source:"iana"},"application/vnd.3gpp.mc-signalling-ear":{source:"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-payload":{source:"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-signalling":{source:"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-floor-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-signed+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-init-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-transmission-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mid-call+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ngap":{source:"iana"},"application/vnd.3gpp.pfcp":{source:"iana"},"application/vnd.3gpp.pic-bw-large":{source:"iana",extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{source:"iana",extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{source:"iana",extensions:["pvb"]},"application/vnd.3gpp.s1ap":{source:"iana"},"application/vnd.3gpp.sms":{source:"iana"},"application/vnd.3gpp.sms+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-ext+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.state-and-event-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ussd+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.bcmcsinfo+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.sms":{source:"iana"},"application/vnd.3gpp2.tcap":{source:"iana",extensions:["tcap"]},"application/vnd.3lightssoftware.imagescal":{source:"iana"},"application/vnd.3m.post-it-notes":{source:"iana",extensions:["pwn"]},"application/vnd.accpac.simply.aso":{source:"iana",extensions:["aso"]},"application/vnd.accpac.simply.imp":{source:"iana",extensions:["imp"]},"application/vnd.acucobol":{source:"iana",extensions:["acu"]},"application/vnd.acucorp":{source:"iana",extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{source:"apache",compressible:!1,extensions:["air"]},"application/vnd.adobe.flash.movie":{source:"iana"},"application/vnd.adobe.formscentral.fcdt":{source:"iana",extensions:["fcdt"]},"application/vnd.adobe.fxp":{source:"iana",extensions:["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{source:"iana"},"application/vnd.adobe.xdp+xml":{source:"iana",compressible:!0,extensions:["xdp"]},"application/vnd.adobe.xfdf":{source:"iana",extensions:["xfdf"]},"application/vnd.aether.imp":{source:"iana"},"application/vnd.afpc.afplinedata":{source:"iana"},"application/vnd.afpc.afplinedata-pagedef":{source:"iana"},"application/vnd.afpc.cmoca-cmresource":{source:"iana"},"application/vnd.afpc.foca-charset":{source:"iana"},"application/vnd.afpc.foca-codedfont":{source:"iana"},"application/vnd.afpc.foca-codepage":{source:"iana"},"application/vnd.afpc.modca":{source:"iana"},"application/vnd.afpc.modca-cmtable":{source:"iana"},"application/vnd.afpc.modca-formdef":{source:"iana"},"application/vnd.afpc.modca-mediummap":{source:"iana"},"application/vnd.afpc.modca-objectcontainer":{source:"iana"},"application/vnd.afpc.modca-overlay":{source:"iana"},"application/vnd.afpc.modca-pagesegment":{source:"iana"},"application/vnd.age":{source:"iana",extensions:["age"]},"application/vnd.ah-barcode":{source:"iana"},"application/vnd.ahead.space":{source:"iana",extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{source:"iana",extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{source:"iana",extensions:["azs"]},"application/vnd.amadeus+json":{source:"iana",compressible:!0},"application/vnd.amazon.ebook":{source:"apache",extensions:["azw"]},"application/vnd.amazon.mobi8-ebook":{source:"iana"},"application/vnd.americandynamics.acc":{source:"iana",extensions:["acc"]},"application/vnd.amiga.ami":{source:"iana",extensions:["ami"]},"application/vnd.amundsen.maze+xml":{source:"iana",compressible:!0},"application/vnd.android.ota":{source:"iana"},"application/vnd.android.package-archive":{source:"apache",compressible:!1,extensions:["apk"]},"application/vnd.anki":{source:"iana"},"application/vnd.anser-web-certificate-issue-initiation":{source:"iana",extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{source:"apache",extensions:["fti"]},"application/vnd.antix.game-component":{source:"iana",extensions:["atx"]},"application/vnd.apache.arrow.file":{source:"iana"},"application/vnd.apache.arrow.stream":{source:"iana"},"application/vnd.apache.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{source:"iana"},"application/vnd.api+json":{source:"iana",compressible:!0},"application/vnd.aplextor.warrp+json":{source:"iana",compressible:!0},"application/vnd.apothekende.reservation+json":{source:"iana",compressible:!0},"application/vnd.apple.installer+xml":{source:"iana",compressible:!0,extensions:["mpkg"]},"application/vnd.apple.keynote":{source:"iana",extensions:["key"]},"application/vnd.apple.mpegurl":{source:"iana",extensions:["m3u8"]},"application/vnd.apple.numbers":{source:"iana",extensions:["numbers"]},"application/vnd.apple.pages":{source:"iana",extensions:["pages"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.arastra.swi":{source:"iana"},"application/vnd.aristanetworks.swi":{source:"iana",extensions:["swi"]},"application/vnd.artisan+json":{source:"iana",compressible:!0},"application/vnd.artsquare":{source:"iana"},"application/vnd.astraea-software.iota":{source:"iana",extensions:["iota"]},"application/vnd.audiograph":{source:"iana",extensions:["aep"]},"application/vnd.autopackage":{source:"iana"},"application/vnd.avalon+json":{source:"iana",compressible:!0},"application/vnd.avistar+xml":{source:"iana",compressible:!0},"application/vnd.balsamiq.bmml+xml":{source:"iana",compressible:!0,extensions:["bmml"]},"application/vnd.balsamiq.bmpr":{source:"iana"},"application/vnd.banana-accounting":{source:"iana"},"application/vnd.bbf.usp.error":{source:"iana"},"application/vnd.bbf.usp.msg":{source:"iana"},"application/vnd.bbf.usp.msg+json":{source:"iana",compressible:!0},"application/vnd.bekitzur-stech+json":{source:"iana",compressible:!0},"application/vnd.bint.med-content":{source:"iana"},"application/vnd.biopax.rdf+xml":{source:"iana",compressible:!0},"application/vnd.blink-idb-value-wrapper":{source:"iana"},"application/vnd.blueice.multipass":{source:"iana",extensions:["mpm"]},"application/vnd.bluetooth.ep.oob":{source:"iana"},"application/vnd.bluetooth.le.oob":{source:"iana"},"application/vnd.bmi":{source:"iana",extensions:["bmi"]},"application/vnd.bpf":{source:"iana"},"application/vnd.bpf3":{source:"iana"},"application/vnd.businessobjects":{source:"iana",extensions:["rep"]},"application/vnd.byu.uapi+json":{source:"iana",compressible:!0},"application/vnd.cab-jscript":{source:"iana"},"application/vnd.canon-cpdl":{source:"iana"},"application/vnd.canon-lips":{source:"iana"},"application/vnd.capasystems-pg+json":{source:"iana",compressible:!0},"application/vnd.cendio.thinlinc.clientconf":{source:"iana"},"application/vnd.century-systems.tcp_stream":{source:"iana"},"application/vnd.chemdraw+xml":{source:"iana",compressible:!0,extensions:["cdxml"]},"application/vnd.chess-pgn":{source:"iana"},"application/vnd.chipnuts.karaoke-mmd":{source:"iana",extensions:["mmd"]},"application/vnd.ciedi":{source:"iana"},"application/vnd.cinderella":{source:"iana",extensions:["cdy"]},"application/vnd.cirpack.isdn-ext":{source:"iana"},"application/vnd.citationstyles.style+xml":{source:"iana",compressible:!0,extensions:["csl"]},"application/vnd.claymore":{source:"iana",extensions:["cla"]},"application/vnd.cloanto.rp9":{source:"iana",extensions:["rp9"]},"application/vnd.clonk.c4group":{source:"iana",extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{source:"iana",extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{source:"iana",extensions:["c11amz"]},"application/vnd.coffeescript":{source:"iana"},"application/vnd.collabio.xodocuments.document":{source:"iana"},"application/vnd.collabio.xodocuments.document-template":{source:"iana"},"application/vnd.collabio.xodocuments.presentation":{source:"iana"},"application/vnd.collabio.xodocuments.presentation-template":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{source:"iana"},"application/vnd.collection+json":{source:"iana",compressible:!0},"application/vnd.collection.doc+json":{source:"iana",compressible:!0},"application/vnd.collection.next+json":{source:"iana",compressible:!0},"application/vnd.comicbook+zip":{source:"iana",compressible:!1},"application/vnd.comicbook-rar":{source:"iana"},"application/vnd.commerce-battelle":{source:"iana"},"application/vnd.commonspace":{source:"iana",extensions:["csp"]},"application/vnd.contact.cmsg":{source:"iana",extensions:["cdbcmsg"]},"application/vnd.coreos.ignition+json":{source:"iana",compressible:!0},"application/vnd.cosmocaller":{source:"iana",extensions:["cmc"]},"application/vnd.crick.clicker":{source:"iana",extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{source:"iana",extensions:["clkk"]},"application/vnd.crick.clicker.palette":{source:"iana",extensions:["clkp"]},"application/vnd.crick.clicker.template":{source:"iana",extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{source:"iana",extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{source:"iana",compressible:!0,extensions:["wbs"]},"application/vnd.cryptii.pipe+json":{source:"iana",compressible:!0},"application/vnd.crypto-shade-file":{source:"iana"},"application/vnd.cryptomator.encrypted":{source:"iana"},"application/vnd.cryptomator.vault":{source:"iana"},"application/vnd.ctc-posml":{source:"iana",extensions:["pml"]},"application/vnd.ctct.ws+xml":{source:"iana",compressible:!0},"application/vnd.cups-pdf":{source:"iana"},"application/vnd.cups-postscript":{source:"iana"},"application/vnd.cups-ppd":{source:"iana",extensions:["ppd"]},"application/vnd.cups-raster":{source:"iana"},"application/vnd.cups-raw":{source:"iana"},"application/vnd.curl":{source:"iana"},"application/vnd.curl.car":{source:"apache",extensions:["car"]},"application/vnd.curl.pcurl":{source:"apache",extensions:["pcurl"]},"application/vnd.cyan.dean.root+xml":{source:"iana",compressible:!0},"application/vnd.cybank":{source:"iana"},"application/vnd.cyclonedx+json":{source:"iana",compressible:!0},"application/vnd.cyclonedx+xml":{source:"iana",compressible:!0},"application/vnd.d2l.coursepackage1p0+zip":{source:"iana",compressible:!1},"application/vnd.d3m-dataset":{source:"iana"},"application/vnd.d3m-problem":{source:"iana"},"application/vnd.dart":{source:"iana",compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{source:"iana",extensions:["rdz"]},"application/vnd.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"application/vnd.debian.binary-package":{source:"iana"},"application/vnd.dece.data":{source:"iana",extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{source:"iana",compressible:!0,extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{source:"iana",extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{source:"iana",extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{source:"iana",extensions:["fe_launch"]},"application/vnd.desmume.movie":{source:"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{source:"iana"},"application/vnd.dm.delegation+xml":{source:"iana",compressible:!0},"application/vnd.dna":{source:"iana",extensions:["dna"]},"application/vnd.document+json":{source:"iana",compressible:!0},"application/vnd.dolby.mlp":{source:"apache",extensions:["mlp"]},"application/vnd.dolby.mobile.1":{source:"iana"},"application/vnd.dolby.mobile.2":{source:"iana"},"application/vnd.doremir.scorecloud-binary-document":{source:"iana"},"application/vnd.dpgraph":{source:"iana",extensions:["dpg"]},"application/vnd.dreamfactory":{source:"iana",extensions:["dfac"]},"application/vnd.drive+json":{source:"iana",compressible:!0},"application/vnd.ds-keypoint":{source:"apache",extensions:["kpxx"]},"application/vnd.dtg.local":{source:"iana"},"application/vnd.dtg.local.flash":{source:"iana"},"application/vnd.dtg.local.html":{source:"iana"},"application/vnd.dvb.ait":{source:"iana",extensions:["ait"]},"application/vnd.dvb.dvbisl+xml":{source:"iana",compressible:!0},"application/vnd.dvb.dvbj":{source:"iana"},"application/vnd.dvb.esgcontainer":{source:"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess2":{source:"iana"},"application/vnd.dvb.ipdcesgpdd":{source:"iana"},"application/vnd.dvb.ipdcroaming":{source:"iana"},"application/vnd.dvb.iptv.alfec-base":{source:"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{source:"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-container+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-generic+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-msglist+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-request+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-response+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-init+xml":{source:"iana",compressible:!0},"application/vnd.dvb.pfr":{source:"iana"},"application/vnd.dvb.service":{source:"iana",extensions:["svc"]},"application/vnd.dxr":{source:"iana"},"application/vnd.dynageo":{source:"iana",extensions:["geo"]},"application/vnd.dzr":{source:"iana"},"application/vnd.easykaraoke.cdgdownload":{source:"iana"},"application/vnd.ecdis-update":{source:"iana"},"application/vnd.ecip.rlp":{source:"iana"},"application/vnd.eclipse.ditto+json":{source:"iana",compressible:!0},"application/vnd.ecowin.chart":{source:"iana",extensions:["mag"]},"application/vnd.ecowin.filerequest":{source:"iana"},"application/vnd.ecowin.fileupdate":{source:"iana"},"application/vnd.ecowin.series":{source:"iana"},"application/vnd.ecowin.seriesrequest":{source:"iana"},"application/vnd.ecowin.seriesupdate":{source:"iana"},"application/vnd.efi.img":{source:"iana"},"application/vnd.efi.iso":{source:"iana"},"application/vnd.emclient.accessrequest+xml":{source:"iana",compressible:!0},"application/vnd.enliven":{source:"iana",extensions:["nml"]},"application/vnd.enphase.envoy":{source:"iana"},"application/vnd.eprints.data+xml":{source:"iana",compressible:!0},"application/vnd.epson.esf":{source:"iana",extensions:["esf"]},"application/vnd.epson.msf":{source:"iana",extensions:["msf"]},"application/vnd.epson.quickanime":{source:"iana",extensions:["qam"]},"application/vnd.epson.salt":{source:"iana",extensions:["slt"]},"application/vnd.epson.ssf":{source:"iana",extensions:["ssf"]},"application/vnd.ericsson.quickcall":{source:"iana"},"application/vnd.espass-espass+zip":{source:"iana",compressible:!1},"application/vnd.eszigno3+xml":{source:"iana",compressible:!0,extensions:["es3","et3"]},"application/vnd.etsi.aoc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.asic-e+zip":{source:"iana",compressible:!1},"application/vnd.etsi.asic-s+zip":{source:"iana",compressible:!1},"application/vnd.etsi.cug+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvcommand+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-bc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-cod+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-npvr+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvservice+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsync+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvueprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mcid+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mheg5":{source:"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{source:"iana",compressible:!0},"application/vnd.etsi.pstn+xml":{source:"iana",compressible:!0},"application/vnd.etsi.sci+xml":{source:"iana",compressible:!0},"application/vnd.etsi.simservs+xml":{source:"iana",compressible:!0},"application/vnd.etsi.timestamp-token":{source:"iana"},"application/vnd.etsi.tsl+xml":{source:"iana",compressible:!0},"application/vnd.etsi.tsl.der":{source:"iana"},"application/vnd.eu.kasparian.car+json":{source:"iana",compressible:!0},"application/vnd.eudora.data":{source:"iana"},"application/vnd.evolv.ecig.profile":{source:"iana"},"application/vnd.evolv.ecig.settings":{source:"iana"},"application/vnd.evolv.ecig.theme":{source:"iana"},"application/vnd.exstream-empower+zip":{source:"iana",compressible:!1},"application/vnd.exstream-package":{source:"iana"},"application/vnd.ezpix-album":{source:"iana",extensions:["ez2"]},"application/vnd.ezpix-package":{source:"iana",extensions:["ez3"]},"application/vnd.f-secure.mobile":{source:"iana"},"application/vnd.familysearch.gedcom+zip":{source:"iana",compressible:!1},"application/vnd.fastcopy-disk-image":{source:"iana"},"application/vnd.fdf":{source:"iana",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"application/vnd.ffsns":{source:"iana"},"application/vnd.ficlab.flb+zip":{source:"iana",compressible:!1},"application/vnd.filmit.zfc":{source:"iana"},"application/vnd.fints":{source:"iana"},"application/vnd.firemonkeys.cloudcell":{source:"iana"},"application/vnd.flographit":{source:"iana",extensions:["gph"]},"application/vnd.fluxtime.clip":{source:"iana",extensions:["ftc"]},"application/vnd.font-fontforge-sfd":{source:"iana"},"application/vnd.framemaker":{source:"iana",extensions:["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{source:"iana",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"iana",extensions:["ltf"]},"application/vnd.fsc.weblaunch":{source:"iana",extensions:["fsc"]},"application/vnd.fujifilm.fb.docuworks":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.container":{source:"iana"},"application/vnd.fujifilm.fb.jfi+xml":{source:"iana",compressible:!0},"application/vnd.fujitsu.oasys":{source:"iana",extensions:["oas"]},"application/vnd.fujitsu.oasys2":{source:"iana",extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{source:"iana",extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{source:"iana",extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{source:"iana",extensions:["bh2"]},"application/vnd.fujixerox.art-ex":{source:"iana"},"application/vnd.fujixerox.art4":{source:"iana"},"application/vnd.fujixerox.ddd":{source:"iana",extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{source:"iana",extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{source:"iana",extensions:["xbd"]},"application/vnd.fujixerox.docuworks.container":{source:"iana"},"application/vnd.fujixerox.hbpl":{source:"iana"},"application/vnd.fut-misnet":{source:"iana"},"application/vnd.futoin+cbor":{source:"iana"},"application/vnd.futoin+json":{source:"iana",compressible:!0},"application/vnd.fuzzysheet":{source:"iana",extensions:["fzs"]},"application/vnd.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.geo+json":{source:"iana",compressible:!0},"application/vnd.geocube+xml":{source:"iana",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.slides":{source:"iana"},"application/vnd.geogebra.tool":{source:"iana",extensions:["ggt"]},"application/vnd.geometry-explorer":{source:"iana",extensions:["gex","gre"]},"application/vnd.geonext":{source:"iana",extensions:["gxt"]},"application/vnd.geoplan":{source:"iana",extensions:["g2w"]},"application/vnd.geospace":{source:"iana",extensions:["g3w"]},"application/vnd.gerber":{source:"iana"},"application/vnd.globalplatform.card-content-mgt":{source:"iana"},"application/vnd.globalplatform.card-content-mgt-response":{source:"iana"},"application/vnd.gmx":{source:"iana",extensions:["gmx"]},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-earth.kml+xml":{source:"iana",compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{source:"iana",compressible:!1,extensions:["kmz"]},"application/vnd.gov.sk.e-form+xml":{source:"iana",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+xml":{source:"iana",compressible:!0},"application/vnd.grafeq":{source:"iana",extensions:["gqf","gqs"]},"application/vnd.gridmp":{source:"iana"},"application/vnd.groove-account":{source:"iana",extensions:["gac"]},"application/vnd.groove-help":{source:"iana",extensions:["ghf"]},"application/vnd.groove-identity-message":{source:"iana",extensions:["gim"]},"application/vnd.groove-injector":{source:"iana",extensions:["grv"]},"application/vnd.groove-tool-message":{source:"iana",extensions:["gtm"]},"application/vnd.groove-tool-template":{source:"iana",extensions:["tpl"]},"application/vnd.groove-vcard":{source:"iana",extensions:["vcg"]},"application/vnd.hal+json":{source:"iana",compressible:!0},"application/vnd.hal+xml":{source:"iana",compressible:!0,extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{source:"iana",compressible:!0,extensions:["zmm"]},"application/vnd.hbci":{source:"iana",extensions:["hbci"]},"application/vnd.hc+json":{source:"iana",compressible:!0},"application/vnd.hcl-bireports":{source:"iana"},"application/vnd.hdt":{source:"iana"},"application/vnd.heroku+json":{source:"iana",compressible:!0},"application/vnd.hhe.lesson-player":{source:"iana",extensions:["les"]},"application/vnd.hl7cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hp-hpgl":{source:"iana",extensions:["hpgl"]},"application/vnd.hp-hpid":{source:"iana",extensions:["hpid"]},"application/vnd.hp-hps":{source:"iana",extensions:["hps"]},"application/vnd.hp-jlyt":{source:"iana",extensions:["jlt"]},"application/vnd.hp-pcl":{source:"iana",extensions:["pcl"]},"application/vnd.hp-pclxl":{source:"iana",extensions:["pclxl"]},"application/vnd.httphone":{source:"iana"},"application/vnd.hydrostatix.sof-data":{source:"iana",extensions:["sfd-hdstx"]},"application/vnd.hyper+json":{source:"iana",compressible:!0},"application/vnd.hyper-item+json":{source:"iana",compressible:!0},"application/vnd.hyperdrive+json":{source:"iana",compressible:!0},"application/vnd.hzn-3d-crossword":{source:"iana"},"application/vnd.ibm.afplinedata":{source:"iana"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"iana",extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{source:"iana",extensions:["irm"]},"application/vnd.ibm.secure-container":{source:"iana",extensions:["sc"]},"application/vnd.iccprofile":{source:"iana",extensions:["icc","icm"]},"application/vnd.ieee.1905":{source:"iana"},"application/vnd.igloader":{source:"iana",extensions:["igl"]},"application/vnd.imagemeter.folder+zip":{source:"iana",compressible:!1},"application/vnd.imagemeter.image+zip":{source:"iana",compressible:!1},"application/vnd.immervision-ivp":{source:"iana",extensions:["ivp"]},"application/vnd.immervision-ivu":{source:"iana",extensions:["ivu"]},"application/vnd.ims.imsccv1p1":{source:"iana"},"application/vnd.ims.imsccv1p2":{source:"iana"},"application/vnd.ims.imsccv1p3":{source:"iana"},"application/vnd.ims.lis.v2.result+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy.id+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings.simple+json":{source:"iana",compressible:!0},"application/vnd.informedcontrol.rms+xml":{source:"iana",compressible:!0},"application/vnd.informix-visionary":{source:"iana"},"application/vnd.infotech.project":{source:"iana"},"application/vnd.infotech.project+xml":{source:"iana",compressible:!0},"application/vnd.innopath.wamp.notification":{source:"iana"},"application/vnd.insors.igm":{source:"iana",extensions:["igm"]},"application/vnd.intercon.formnet":{source:"iana",extensions:["xpw","xpx"]},"application/vnd.intergeo":{source:"iana",extensions:["i2g"]},"application/vnd.intertrust.digibox":{source:"iana"},"application/vnd.intertrust.nncp":{source:"iana"},"application/vnd.intu.qbo":{source:"iana",extensions:["qbo"]},"application/vnd.intu.qfx":{source:"iana",extensions:["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.conceptitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.knowledgeitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsmessage+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.packageitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.planningitem+xml":{source:"iana",compressible:!0},"application/vnd.ipunplugged.rcprofile":{source:"iana",extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{source:"iana",compressible:!0,extensions:["irp"]},"application/vnd.is-xpr":{source:"iana",extensions:["xpr"]},"application/vnd.isac.fcs":{source:"iana",extensions:["fcs"]},"application/vnd.iso11783-10+zip":{source:"iana",compressible:!1},"application/vnd.jam":{source:"iana",extensions:["jam"]},"application/vnd.japannet-directory-service":{source:"iana"},"application/vnd.japannet-jpnstore-wakeup":{source:"iana"},"application/vnd.japannet-payment-wakeup":{source:"iana"},"application/vnd.japannet-registration":{source:"iana"},"application/vnd.japannet-registration-wakeup":{source:"iana"},"application/vnd.japannet-setstore-wakeup":{source:"iana"},"application/vnd.japannet-verification":{source:"iana"},"application/vnd.japannet-verification-wakeup":{source:"iana"},"application/vnd.jcp.javame.midlet-rms":{source:"iana",extensions:["rms"]},"application/vnd.jisp":{source:"iana",extensions:["jisp"]},"application/vnd.joost.joda-archive":{source:"iana",extensions:["joda"]},"application/vnd.jsk.isdn-ngn":{source:"iana"},"application/vnd.kahootz":{source:"iana",extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{source:"iana",extensions:["karbon"]},"application/vnd.kde.kchart":{source:"iana",extensions:["chrt"]},"application/vnd.kde.kformula":{source:"iana",extensions:["kfo"]},"application/vnd.kde.kivio":{source:"iana",extensions:["flw"]},"application/vnd.kde.kontour":{source:"iana",extensions:["kon"]},"application/vnd.kde.kpresenter":{source:"iana",extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{source:"iana",extensions:["ksp"]},"application/vnd.kde.kword":{source:"iana",extensions:["kwd","kwt"]},"application/vnd.kenameaapp":{source:"iana",extensions:["htke"]},"application/vnd.kidspiration":{source:"iana",extensions:["kia"]},"application/vnd.kinar":{source:"iana",extensions:["kne","knp"]},"application/vnd.koan":{source:"iana",extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{source:"iana",extensions:["sse"]},"application/vnd.las":{source:"iana"},"application/vnd.las.las+json":{source:"iana",compressible:!0},"application/vnd.las.las+xml":{source:"iana",compressible:!0,extensions:["lasxml"]},"application/vnd.laszip":{source:"iana"},"application/vnd.leap+json":{source:"iana",compressible:!0},"application/vnd.liberty-request+xml":{source:"iana",compressible:!0},"application/vnd.llamagraphics.life-balance.desktop":{source:"iana",extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{source:"iana",compressible:!0,extensions:["lbe"]},"application/vnd.logipipe.circuit+zip":{source:"iana",compressible:!1},"application/vnd.loom":{source:"iana"},"application/vnd.lotus-1-2-3":{source:"iana",extensions:["123"]},"application/vnd.lotus-approach":{source:"iana",extensions:["apr"]},"application/vnd.lotus-freelance":{source:"iana",extensions:["pre"]},"application/vnd.lotus-notes":{source:"iana",extensions:["nsf"]},"application/vnd.lotus-organizer":{source:"iana",extensions:["org"]},"application/vnd.lotus-screencam":{source:"iana",extensions:["scm"]},"application/vnd.lotus-wordpro":{source:"iana",extensions:["lwp"]},"application/vnd.macports.portpkg":{source:"iana",extensions:["portpkg"]},"application/vnd.mapbox-vector-tile":{source:"iana",extensions:["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.conftoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.license+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.mdcf":{source:"iana"},"application/vnd.mason+json":{source:"iana",compressible:!0},"application/vnd.maxar.archive.3tz+zip":{source:"iana",compressible:!1},"application/vnd.maxmind.maxmind-db":{source:"iana"},"application/vnd.mcd":{source:"iana",extensions:["mcd"]},"application/vnd.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.meridian-slingshot":{source:"iana"},"application/vnd.mfer":{source:"iana",extensions:["mwf"]},"application/vnd.mfmp":{source:"iana",extensions:["mfm"]},"application/vnd.micro+json":{source:"iana",compressible:!0},"application/vnd.micrografx.flo":{source:"iana",extensions:["flo"]},"application/vnd.micrografx.igx":{source:"iana",extensions:["igx"]},"application/vnd.microsoft.portable-executable":{source:"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{source:"iana"},"application/vnd.miele+json":{source:"iana",compressible:!0},"application/vnd.mif":{source:"iana",extensions:["mif"]},"application/vnd.minisoft-hp3000-save":{source:"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{source:"iana"},"application/vnd.mobius.daf":{source:"iana",extensions:["daf"]},"application/vnd.mobius.dis":{source:"iana",extensions:["dis"]},"application/vnd.mobius.mbk":{source:"iana",extensions:["mbk"]},"application/vnd.mobius.mqy":{source:"iana",extensions:["mqy"]},"application/vnd.mobius.msl":{source:"iana",extensions:["msl"]},"application/vnd.mobius.plc":{source:"iana",extensions:["plc"]},"application/vnd.mobius.txf":{source:"iana",extensions:["txf"]},"application/vnd.mophun.application":{source:"iana",extensions:["mpn"]},"application/vnd.mophun.certificate":{source:"iana",extensions:["mpc"]},"application/vnd.motorola.flexsuite":{source:"iana"},"application/vnd.motorola.flexsuite.adsi":{source:"iana"},"application/vnd.motorola.flexsuite.fis":{source:"iana"},"application/vnd.motorola.flexsuite.gotap":{source:"iana"},"application/vnd.motorola.flexsuite.kmr":{source:"iana"},"application/vnd.motorola.flexsuite.ttc":{source:"iana"},"application/vnd.motorola.flexsuite.wem":{source:"iana"},"application/vnd.motorola.iprm":{source:"iana"},"application/vnd.mozilla.xul+xml":{source:"iana",compressible:!0,extensions:["xul"]},"application/vnd.ms-3mfdocument":{source:"iana"},"application/vnd.ms-artgalry":{source:"iana",extensions:["cil"]},"application/vnd.ms-asf":{source:"iana"},"application/vnd.ms-cab-compressed":{source:"iana",extensions:["cab"]},"application/vnd.ms-color.iccprofile":{source:"apache"},"application/vnd.ms-excel":{source:"iana",compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{source:"iana",extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{source:"iana",extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{source:"iana",extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{source:"iana",extensions:["xltm"]},"application/vnd.ms-fontobject":{source:"iana",compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{source:"iana",extensions:["chm"]},"application/vnd.ms-ims":{source:"iana",extensions:["ims"]},"application/vnd.ms-lrm":{source:"iana",extensions:["lrm"]},"application/vnd.ms-office.activex+xml":{source:"iana",compressible:!0},"application/vnd.ms-officetheme":{source:"iana",extensions:["thmx"]},"application/vnd.ms-opentype":{source:"apache",compressible:!0},"application/vnd.ms-outlook":{compressible:!1,extensions:["msg"]},"application/vnd.ms-package.obfuscated-opentype":{source:"apache"},"application/vnd.ms-pki.seccat":{source:"apache",extensions:["cat"]},"application/vnd.ms-pki.stl":{source:"apache",extensions:["stl"]},"application/vnd.ms-playready.initiator+xml":{source:"iana",compressible:!0},"application/vnd.ms-powerpoint":{source:"iana",compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{source:"iana",extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{source:"iana",extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{source:"iana",extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{source:"iana",extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{source:"iana",extensions:["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{source:"iana",compressible:!0},"application/vnd.ms-printing.printticket+xml":{source:"apache",compressible:!0},"application/vnd.ms-printschematicket+xml":{source:"iana",compressible:!0},"application/vnd.ms-project":{source:"iana",extensions:["mpp","mpt"]},"application/vnd.ms-tnef":{source:"iana"},"application/vnd.ms-windows.devicepairing":{source:"iana"},"application/vnd.ms-windows.nwprinting.oob":{source:"iana"},"application/vnd.ms-windows.printerpairing":{source:"iana"},"application/vnd.ms-windows.wsd.oob":{source:"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.lic-resp":{source:"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.meter-resp":{source:"iana"},"application/vnd.ms-word.document.macroenabled.12":{source:"iana",extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{source:"iana",extensions:["dotm"]},"application/vnd.ms-works":{source:"iana",extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{source:"iana",extensions:["wpl"]},"application/vnd.ms-xpsdocument":{source:"iana",compressible:!1,extensions:["xps"]},"application/vnd.msa-disk-image":{source:"iana"},"application/vnd.mseq":{source:"iana",extensions:["mseq"]},"application/vnd.msign":{source:"iana"},"application/vnd.multiad.creator":{source:"iana"},"application/vnd.multiad.creator.cif":{source:"iana"},"application/vnd.music-niff":{source:"iana"},"application/vnd.musician":{source:"iana",extensions:["mus"]},"application/vnd.muvee.style":{source:"iana",extensions:["msty"]},"application/vnd.mynfc":{source:"iana",extensions:["taglet"]},"application/vnd.nacamar.ybrid+json":{source:"iana",compressible:!0},"application/vnd.ncd.control":{source:"iana"},"application/vnd.ncd.reference":{source:"iana"},"application/vnd.nearst.inv+json":{source:"iana",compressible:!0},"application/vnd.nebumind.line":{source:"iana"},"application/vnd.nervana":{source:"iana"},"application/vnd.netfpx":{source:"iana"},"application/vnd.neurolanguage.nlu":{source:"iana",extensions:["nlu"]},"application/vnd.nimn":{source:"iana"},"application/vnd.nintendo.nitro.rom":{source:"iana"},"application/vnd.nintendo.snes.rom":{source:"iana"},"application/vnd.nitf":{source:"iana",extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{source:"iana",extensions:["nnd"]},"application/vnd.noblenet-sealer":{source:"iana",extensions:["nns"]},"application/vnd.noblenet-web":{source:"iana",extensions:["nnw"]},"application/vnd.nokia.catalogs":{source:"iana"},"application/vnd.nokia.conml+wbxml":{source:"iana"},"application/vnd.nokia.conml+xml":{source:"iana",compressible:!0},"application/vnd.nokia.iptv.config+xml":{source:"iana",compressible:!0},"application/vnd.nokia.isds-radio-presets":{source:"iana"},"application/vnd.nokia.landmark+wbxml":{source:"iana"},"application/vnd.nokia.landmark+xml":{source:"iana",compressible:!0},"application/vnd.nokia.landmarkcollection+xml":{source:"iana",compressible:!0},"application/vnd.nokia.n-gage.ac+xml":{source:"iana",compressible:!0,extensions:["ac"]},"application/vnd.nokia.n-gage.data":{source:"iana",extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{source:"iana",extensions:["n-gage"]},"application/vnd.nokia.ncd":{source:"iana"},"application/vnd.nokia.pcd+wbxml":{source:"iana"},"application/vnd.nokia.pcd+xml":{source:"iana",compressible:!0},"application/vnd.nokia.radio-preset":{source:"iana",extensions:["rpst"]},"application/vnd.nokia.radio-presets":{source:"iana",extensions:["rpss"]},"application/vnd.novadigm.edm":{source:"iana",extensions:["edm"]},"application/vnd.novadigm.edx":{source:"iana",extensions:["edx"]},"application/vnd.novadigm.ext":{source:"iana",extensions:["ext"]},"application/vnd.ntt-local.content-share":{source:"iana"},"application/vnd.ntt-local.file-transfer":{source:"iana"},"application/vnd.ntt-local.ogw_remote-access":{source:"iana"},"application/vnd.ntt-local.sip-ta_remote":{source:"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{source:"iana"},"application/vnd.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"iana",extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{source:"iana",extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{source:"iana",extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{source:"iana",compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{source:"iana",extensions:["otg"]},"application/vnd.oasis.opendocument.image":{source:"iana",extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{source:"iana",extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{source:"iana",compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{source:"iana",extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{source:"iana",compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{source:"iana",extensions:["ots"]},"application/vnd.oasis.opendocument.text":{source:"iana",compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{source:"iana",extensions:["odm"]},"application/vnd.oasis.opendocument.text-template":{source:"iana",extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{source:"iana",extensions:["oth"]},"application/vnd.obn":{source:"iana"},"application/vnd.ocf+cbor":{source:"iana"},"application/vnd.oci.image.manifest.v1+json":{source:"iana",compressible:!0},"application/vnd.oftn.l10n+json":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessdownload+xml":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessstreaming+xml":{source:"iana",compressible:!0},"application/vnd.oipf.cspg-hexbinary":{source:"iana"},"application/vnd.oipf.dae.svg+xml":{source:"iana",compressible:!0},"application/vnd.oipf.dae.xhtml+xml":{source:"iana",compressible:!0},"application/vnd.oipf.mippvcontrolmessage+xml":{source:"iana",compressible:!0},"application/vnd.oipf.pae.gem":{source:"iana"},"application/vnd.oipf.spdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.oipf.spdlist+xml":{source:"iana",compressible:!0},"application/vnd.oipf.ueprofile+xml":{source:"iana",compressible:!0},"application/vnd.oipf.userprofile+xml":{source:"iana",compressible:!0},"application/vnd.olpc-sugar":{source:"iana",extensions:["xo"]},"application/vnd.oma-scws-config":{source:"iana"},"application/vnd.oma-scws-http-request":{source:"iana"},"application/vnd.oma-scws-http-response":{source:"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.drm-trigger+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.imd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.ltkm":{source:"iana"},"application/vnd.oma.bcast.notification+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.provisioningtrigger":{source:"iana"},"application/vnd.oma.bcast.sgboot":{source:"iana"},"application/vnd.oma.bcast.sgdd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sgdu":{source:"iana"},"application/vnd.oma.bcast.simple-symbol-container":{source:"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sprov+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.stkm":{source:"iana"},"application/vnd.oma.cab-address-book+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-feature-handler+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-pcc+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-subs-invite+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-user-prefs+xml":{source:"iana",compressible:!0},"application/vnd.oma.dcd":{source:"iana"},"application/vnd.oma.dcdc":{source:"iana"},"application/vnd.oma.dd2+xml":{source:"iana",compressible:!0,extensions:["dd2"]},"application/vnd.oma.drm.risd+xml":{source:"iana",compressible:!0},"application/vnd.oma.group-usage-list+xml":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+cbor":{source:"iana"},"application/vnd.oma.lwm2m+json":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+tlv":{source:"iana"},"application/vnd.oma.pal+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.detailed-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.final-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.groups+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.invocation-descriptor+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.optimized-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.push":{source:"iana"},"application/vnd.oma.scidm.messages+xml":{source:"iana",compressible:!0},"application/vnd.oma.xcap-directory+xml":{source:"iana",compressible:!0},"application/vnd.omads-email+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-file+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-folder+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omaloc-supl-init":{source:"iana"},"application/vnd.onepager":{source:"iana"},"application/vnd.onepagertamp":{source:"iana"},"application/vnd.onepagertamx":{source:"iana"},"application/vnd.onepagertat":{source:"iana"},"application/vnd.onepagertatp":{source:"iana"},"application/vnd.onepagertatx":{source:"iana"},"application/vnd.openblox.game+xml":{source:"iana",compressible:!0,extensions:["obgx"]},"application/vnd.openblox.game-binary":{source:"iana"},"application/vnd.openeye.oeb":{source:"iana"},"application/vnd.openofficeorg.extension":{source:"apache",extensions:["oxt"]},"application/vnd.openstreetmap.data+xml":{source:"iana",compressible:!0,extensions:["osm"]},"application/vnd.opentimestamps.ots":{source:"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawing+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{source:"iana",compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slide":{source:"iana",extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{source:"iana",extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.template":{source:"iana",extensions:["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{source:"iana",compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{source:"iana",extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.theme+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.vmldrawing":{source:"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{source:"iana",compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{source:"iana",extensions:["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.core-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.relationships+xml":{source:"iana",compressible:!0},"application/vnd.oracle.resource+json":{source:"iana",compressible:!0},"application/vnd.orange.indata":{source:"iana"},"application/vnd.osa.netdeploy":{source:"iana"},"application/vnd.osgeo.mapguide.package":{source:"iana",extensions:["mgp"]},"application/vnd.osgi.bundle":{source:"iana"},"application/vnd.osgi.dp":{source:"iana",extensions:["dp"]},"application/vnd.osgi.subsystem":{source:"iana",extensions:["esa"]},"application/vnd.otps.ct-kip+xml":{source:"iana",compressible:!0},"application/vnd.oxli.countgraph":{source:"iana"},"application/vnd.pagerduty+json":{source:"iana",compressible:!0},"application/vnd.palm":{source:"iana",extensions:["pdb","pqa","oprc"]},"application/vnd.panoply":{source:"iana"},"application/vnd.paos.xml":{source:"iana"},"application/vnd.patentdive":{source:"iana"},"application/vnd.patientecommsdoc":{source:"iana"},"application/vnd.pawaafile":{source:"iana",extensions:["paw"]},"application/vnd.pcos":{source:"iana"},"application/vnd.pg.format":{source:"iana",extensions:["str"]},"application/vnd.pg.osasli":{source:"iana",extensions:["ei6"]},"application/vnd.piaccess.application-licence":{source:"iana"},"application/vnd.picsel":{source:"iana",extensions:["efif"]},"application/vnd.pmi.widget":{source:"iana",extensions:["wg"]},"application/vnd.poc.group-advertisement+xml":{source:"iana",compressible:!0},"application/vnd.pocketlearn":{source:"iana",extensions:["plf"]},"application/vnd.powerbuilder6":{source:"iana",extensions:["pbd"]},"application/vnd.powerbuilder6-s":{source:"iana"},"application/vnd.powerbuilder7":{source:"iana"},"application/vnd.powerbuilder7-s":{source:"iana"},"application/vnd.powerbuilder75":{source:"iana"},"application/vnd.powerbuilder75-s":{source:"iana"},"application/vnd.preminet":{source:"iana"},"application/vnd.previewsystems.box":{source:"iana",extensions:["box"]},"application/vnd.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{source:"iana"},"application/vnd.publishare-delta-tree":{source:"iana",extensions:["qps"]},"application/vnd.pvi.ptid1":{source:"iana",extensions:["ptid"]},"application/vnd.pwg-multiplexed":{source:"iana"},"application/vnd.pwg-xhtml-print+xml":{source:"iana",compressible:!0},"application/vnd.qualcomm.brew-app-res":{source:"iana"},"application/vnd.quarantainenet":{source:"iana"},"application/vnd.quark.quarkxpress":{source:"iana",extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{source:"iana"},"application/vnd.radisys.moml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conn+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-stream+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-base+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-detect+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-group+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-speech+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-transform+xml":{source:"iana",compressible:!0},"application/vnd.rainstor.data":{source:"iana"},"application/vnd.rapid":{source:"iana"},"application/vnd.rar":{source:"iana",extensions:["rar"]},"application/vnd.realvnc.bed":{source:"iana",extensions:["bed"]},"application/vnd.recordare.musicxml":{source:"iana",extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{source:"iana",compressible:!0,extensions:["musicxml"]},"application/vnd.renlearn.rlprint":{source:"iana"},"application/vnd.resilient.logic":{source:"iana"},"application/vnd.restful+json":{source:"iana",compressible:!0},"application/vnd.rig.cryptonote":{source:"iana",extensions:["cryptonote"]},"application/vnd.rim.cod":{source:"apache",extensions:["cod"]},"application/vnd.rn-realmedia":{source:"apache",extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{source:"apache",extensions:["rmvb"]},"application/vnd.route66.link66+xml":{source:"iana",compressible:!0,extensions:["link66"]},"application/vnd.rs-274x":{source:"iana"},"application/vnd.ruckus.download":{source:"iana"},"application/vnd.s3sms":{source:"iana"},"application/vnd.sailingtracker.track":{source:"iana",extensions:["st"]},"application/vnd.sar":{source:"iana"},"application/vnd.sbm.cid":{source:"iana"},"application/vnd.sbm.mid2":{source:"iana"},"application/vnd.scribus":{source:"iana"},"application/vnd.sealed.3df":{source:"iana"},"application/vnd.sealed.csf":{source:"iana"},"application/vnd.sealed.doc":{source:"iana"},"application/vnd.sealed.eml":{source:"iana"},"application/vnd.sealed.mht":{source:"iana"},"application/vnd.sealed.net":{source:"iana"},"application/vnd.sealed.ppt":{source:"iana"},"application/vnd.sealed.tiff":{source:"iana"},"application/vnd.sealed.xls":{source:"iana"},"application/vnd.sealedmedia.softseal.html":{source:"iana"},"application/vnd.sealedmedia.softseal.pdf":{source:"iana"},"application/vnd.seemail":{source:"iana",extensions:["see"]},"application/vnd.seis+json":{source:"iana",compressible:!0},"application/vnd.sema":{source:"iana",extensions:["sema"]},"application/vnd.semd":{source:"iana",extensions:["semd"]},"application/vnd.semf":{source:"iana",extensions:["semf"]},"application/vnd.shade-save-file":{source:"iana"},"application/vnd.shana.informed.formdata":{source:"iana",extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{source:"iana",extensions:["itp"]},"application/vnd.shana.informed.interchange":{source:"iana",extensions:["iif"]},"application/vnd.shana.informed.package":{source:"iana",extensions:["ipk"]},"application/vnd.shootproof+json":{source:"iana",compressible:!0},"application/vnd.shopkick+json":{source:"iana",compressible:!0},"application/vnd.shp":{source:"iana"},"application/vnd.shx":{source:"iana"},"application/vnd.sigrok.session":{source:"iana"},"application/vnd.simtech-mindmapper":{source:"iana",extensions:["twd","twds"]},"application/vnd.siren+json":{source:"iana",compressible:!0},"application/vnd.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"application/vnd.snesdev-page-table":{source:"iana"},"application/vnd.software602.filler.form+xml":{source:"iana",compressible:!0,extensions:["fo"]},"application/vnd.software602.filler.form-xml-zip":{source:"iana"},"application/vnd.solent.sdkm+xml":{source:"iana",compressible:!0,extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{source:"iana",extensions:["dxp"]},"application/vnd.spotfire.sfs":{source:"iana",extensions:["sfs"]},"application/vnd.sqlite3":{source:"iana"},"application/vnd.sss-cod":{source:"iana"},"application/vnd.sss-dtf":{source:"iana"},"application/vnd.sss-ntf":{source:"iana"},"application/vnd.stardivision.calc":{source:"apache",extensions:["sdc"]},"application/vnd.stardivision.draw":{source:"apache",extensions:["sda"]},"application/vnd.stardivision.impress":{source:"apache",extensions:["sdd"]},"application/vnd.stardivision.math":{source:"apache",extensions:["smf"]},"application/vnd.stardivision.writer":{source:"apache",extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{source:"apache",extensions:["sgl"]},"application/vnd.stepmania.package":{source:"iana",extensions:["smzip"]},"application/vnd.stepmania.stepchart":{source:"iana",extensions:["sm"]},"application/vnd.street-stream":{source:"iana"},"application/vnd.sun.wadl+xml":{source:"iana",compressible:!0,extensions:["wadl"]},"application/vnd.sun.xml.calc":{source:"apache",extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{source:"apache",extensions:["stc"]},"application/vnd.sun.xml.draw":{source:"apache",extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{source:"apache",extensions:["std"]},"application/vnd.sun.xml.impress":{source:"apache",extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{source:"apache",extensions:["sti"]},"application/vnd.sun.xml.math":{source:"apache",extensions:["sxm"]},"application/vnd.sun.xml.writer":{source:"apache",extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{source:"apache",extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{source:"apache",extensions:["stw"]},"application/vnd.sus-calendar":{source:"iana",extensions:["sus","susp"]},"application/vnd.svd":{source:"iana",extensions:["svd"]},"application/vnd.swiftview-ics":{source:"iana"},"application/vnd.sycle+xml":{source:"iana",compressible:!0},"application/vnd.syft+json":{source:"iana",compressible:!0},"application/vnd.symbian.install":{source:"apache",extensions:["sis","sisx"]},"application/vnd.syncml+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{source:"iana",charset:"UTF-8",extensions:["bdm"]},"application/vnd.syncml.dm+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xdm"]},"application/vnd.syncml.dm.notification":{source:"iana"},"application/vnd.syncml.dmddf+wbxml":{source:"iana"},"application/vnd.syncml.dmddf+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{source:"iana"},"application/vnd.syncml.dmtnds+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.syncml.ds.notification":{source:"iana"},"application/vnd.tableschema+json":{source:"iana",compressible:!0},"application/vnd.tao.intent-module-archive":{source:"iana",extensions:["tao"]},"application/vnd.tcpdump.pcap":{source:"iana",extensions:["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{source:"iana",compressible:!0},"application/vnd.tmd.mediaflex.api+xml":{source:"iana",compressible:!0},"application/vnd.tml":{source:"iana"},"application/vnd.tmobile-livetv":{source:"iana",extensions:["tmo"]},"application/vnd.tri.onesource":{source:"iana"},"application/vnd.trid.tpt":{source:"iana",extensions:["tpt"]},"application/vnd.triscape.mxs":{source:"iana",extensions:["mxs"]},"application/vnd.trueapp":{source:"iana",extensions:["tra"]},"application/vnd.truedoc":{source:"iana"},"application/vnd.ubisoft.webplayer":{source:"iana"},"application/vnd.ufdl":{source:"iana",extensions:["ufd","ufdl"]},"application/vnd.uiq.theme":{source:"iana",extensions:["utz"]},"application/vnd.umajin":{source:"iana",extensions:["umj"]},"application/vnd.unity":{source:"iana",extensions:["unityweb"]},"application/vnd.uoml+xml":{source:"iana",compressible:!0,extensions:["uoml"]},"application/vnd.uplanet.alert":{source:"iana"},"application/vnd.uplanet.alert-wbxml":{source:"iana"},"application/vnd.uplanet.bearer-choice":{source:"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{source:"iana"},"application/vnd.uplanet.cacheop":{source:"iana"},"application/vnd.uplanet.cacheop-wbxml":{source:"iana"},"application/vnd.uplanet.channel":{source:"iana"},"application/vnd.uplanet.channel-wbxml":{source:"iana"},"application/vnd.uplanet.list":{source:"iana"},"application/vnd.uplanet.list-wbxml":{source:"iana"},"application/vnd.uplanet.listcmd":{source:"iana"},"application/vnd.uplanet.listcmd-wbxml":{source:"iana"},"application/vnd.uplanet.signal":{source:"iana"},"application/vnd.uri-map":{source:"iana"},"application/vnd.valve.source.material":{source:"iana"},"application/vnd.vcx":{source:"iana",extensions:["vcx"]},"application/vnd.vd-study":{source:"iana"},"application/vnd.vectorworks":{source:"iana"},"application/vnd.vel+json":{source:"iana",compressible:!0},"application/vnd.verimatrix.vcas":{source:"iana"},"application/vnd.veritone.aion+json":{source:"iana",compressible:!0},"application/vnd.veryant.thin":{source:"iana"},"application/vnd.ves.encrypted":{source:"iana"},"application/vnd.vidsoft.vidconference":{source:"iana"},"application/vnd.visio":{source:"iana",extensions:["vsd","vst","vss","vsw"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{source:"iana"},"application/vnd.vsf":{source:"iana",extensions:["vsf"]},"application/vnd.wap.sic":{source:"iana"},"application/vnd.wap.slc":{source:"iana"},"application/vnd.wap.wbxml":{source:"iana",charset:"UTF-8",extensions:["wbxml"]},"application/vnd.wap.wmlc":{source:"iana",extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{source:"iana",extensions:["wmlsc"]},"application/vnd.webturbo":{source:"iana",extensions:["wtb"]},"application/vnd.wfa.dpp":{source:"iana"},"application/vnd.wfa.p2p":{source:"iana"},"application/vnd.wfa.wsc":{source:"iana"},"application/vnd.windows.devicepairing":{source:"iana"},"application/vnd.wmc":{source:"iana"},"application/vnd.wmf.bootstrap":{source:"iana"},"application/vnd.wolfram.mathematica":{source:"iana"},"application/vnd.wolfram.mathematica.package":{source:"iana"},"application/vnd.wolfram.player":{source:"iana",extensions:["nbp"]},"application/vnd.wordperfect":{source:"iana",extensions:["wpd"]},"application/vnd.wqd":{source:"iana",extensions:["wqd"]},"application/vnd.wrq-hp3000-labelled":{source:"iana"},"application/vnd.wt.stf":{source:"iana",extensions:["stf"]},"application/vnd.wv.csp+wbxml":{source:"iana"},"application/vnd.wv.csp+xml":{source:"iana",compressible:!0},"application/vnd.wv.ssp+xml":{source:"iana",compressible:!0},"application/vnd.xacml+json":{source:"iana",compressible:!0},"application/vnd.xara":{source:"iana",extensions:["xar"]},"application/vnd.xfdl":{source:"iana",extensions:["xfdl"]},"application/vnd.xfdl.webform":{source:"iana"},"application/vnd.xmi+xml":{source:"iana",compressible:!0},"application/vnd.xmpie.cpkg":{source:"iana"},"application/vnd.xmpie.dpkg":{source:"iana"},"application/vnd.xmpie.plan":{source:"iana"},"application/vnd.xmpie.ppkg":{source:"iana"},"application/vnd.xmpie.xlim":{source:"iana"},"application/vnd.yamaha.hv-dic":{source:"iana",extensions:["hvd"]},"application/vnd.yamaha.hv-script":{source:"iana",extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{source:"iana",extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{source:"iana",extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{source:"iana",compressible:!0,extensions:["osfpvg"]},"application/vnd.yamaha.remote-setup":{source:"iana"},"application/vnd.yamaha.smaf-audio":{source:"iana",extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{source:"iana",extensions:["spf"]},"application/vnd.yamaha.through-ngn":{source:"iana"},"application/vnd.yamaha.tunnel-udpencap":{source:"iana"},"application/vnd.yaoweme":{source:"iana"},"application/vnd.yellowriver-custom-menu":{source:"iana",extensions:["cmp"]},"application/vnd.youtube.yt":{source:"iana"},"application/vnd.zul":{source:"iana",extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{source:"iana",compressible:!0,extensions:["zaz"]},"application/voicexml+xml":{source:"iana",compressible:!0,extensions:["vxml"]},"application/voucher-cms+json":{source:"iana",compressible:!0},"application/vq-rtcpxr":{source:"iana"},"application/wasm":{source:"iana",compressible:!0,extensions:["wasm"]},"application/watcherinfo+xml":{source:"iana",compressible:!0,extensions:["wif"]},"application/webpush-options+json":{source:"iana",compressible:!0},"application/whoispp-query":{source:"iana"},"application/whoispp-response":{source:"iana"},"application/widget":{source:"iana",extensions:["wgt"]},"application/winhlp":{source:"apache",extensions:["hlp"]},"application/wita":{source:"iana"},"application/wordperfect5.1":{source:"iana"},"application/wsdl+xml":{source:"iana",compressible:!0,extensions:["wsdl"]},"application/wspolicy+xml":{source:"iana",compressible:!0,extensions:["wspolicy"]},"application/x-7z-compressed":{source:"apache",compressible:!1,extensions:["7z"]},"application/x-abiword":{source:"apache",extensions:["abw"]},"application/x-ace-compressed":{source:"apache",extensions:["ace"]},"application/x-amf":{source:"apache"},"application/x-apple-diskimage":{source:"apache",extensions:["dmg"]},"application/x-arj":{compressible:!1,extensions:["arj"]},"application/x-authorware-bin":{source:"apache",extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{source:"apache",extensions:["aam"]},"application/x-authorware-seg":{source:"apache",extensions:["aas"]},"application/x-bcpio":{source:"apache",extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{source:"apache",extensions:["torrent"]},"application/x-blorb":{source:"apache",extensions:["blb","blorb"]},"application/x-bzip":{source:"apache",compressible:!1,extensions:["bz"]},"application/x-bzip2":{source:"apache",compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{source:"apache",extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{source:"apache",extensions:["vcd"]},"application/x-cfs-compressed":{source:"apache",extensions:["cfs"]},"application/x-chat":{source:"apache",extensions:["chat"]},"application/x-chess-pgn":{source:"apache",extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-compress":{source:"apache"},"application/x-conference":{source:"apache",extensions:["nsc"]},"application/x-cpio":{source:"apache",extensions:["cpio"]},"application/x-csh":{source:"apache",extensions:["csh"]},"application/x-deb":{compressible:!1},"application/x-debian-package":{source:"apache",extensions:["deb","udeb"]},"application/x-dgc-compressed":{source:"apache",extensions:["dgc"]},"application/x-director":{source:"apache",extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{source:"apache",extensions:["wad"]},"application/x-dtbncx+xml":{source:"apache",compressible:!0,extensions:["ncx"]},"application/x-dtbook+xml":{source:"apache",compressible:!0,extensions:["dtb"]},"application/x-dtbresource+xml":{source:"apache",compressible:!0,extensions:["res"]},"application/x-dvi":{source:"apache",compressible:!1,extensions:["dvi"]},"application/x-envoy":{source:"apache",extensions:["evy"]},"application/x-eva":{source:"apache",extensions:["eva"]},"application/x-font-bdf":{source:"apache",extensions:["bdf"]},"application/x-font-dos":{source:"apache"},"application/x-font-framemaker":{source:"apache"},"application/x-font-ghostscript":{source:"apache",extensions:["gsf"]},"application/x-font-libgrx":{source:"apache"},"application/x-font-linux-psf":{source:"apache",extensions:["psf"]},"application/x-font-pcf":{source:"apache",extensions:["pcf"]},"application/x-font-snf":{source:"apache",extensions:["snf"]},"application/x-font-speedo":{source:"apache"},"application/x-font-sunos-news":{source:"apache"},"application/x-font-type1":{source:"apache",extensions:["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{source:"apache"},"application/x-freearc":{source:"apache",extensions:["arc"]},"application/x-futuresplash":{source:"apache",extensions:["spl"]},"application/x-gca-compressed":{source:"apache",extensions:["gca"]},"application/x-glulx":{source:"apache",extensions:["ulx"]},"application/x-gnumeric":{source:"apache",extensions:["gnumeric"]},"application/x-gramps-xml":{source:"apache",extensions:["gramps"]},"application/x-gtar":{source:"apache",extensions:["gtar"]},"application/x-gzip":{source:"apache"},"application/x-hdf":{source:"apache",extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{source:"apache",extensions:["install"]},"application/x-iso9660-image":{source:"apache",extensions:["iso"]},"application/x-iwork-keynote-sffkey":{extensions:["key"]},"application/x-iwork-numbers-sffnumbers":{extensions:["numbers"]},"application/x-iwork-pages-sffpages":{extensions:["pages"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{source:"apache",compressible:!1,extensions:["jnlp"]},"application/x-javascript":{compressible:!0},"application/x-keepass2":{extensions:["kdbx"]},"application/x-latex":{source:"apache",compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{source:"apache",extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{source:"apache",extensions:["mie"]},"application/x-mobipocket-ebook":{source:"apache",extensions:["prc","mobi"]},"application/x-mpegurl":{compressible:!1},"application/x-ms-application":{source:"apache",extensions:["application"]},"application/x-ms-shortcut":{source:"apache",extensions:["lnk"]},"application/x-ms-wmd":{source:"apache",extensions:["wmd"]},"application/x-ms-wmz":{source:"apache",extensions:["wmz"]},"application/x-ms-xbap":{source:"apache",extensions:["xbap"]},"application/x-msaccess":{source:"apache",extensions:["mdb"]},"application/x-msbinder":{source:"apache",extensions:["obd"]},"application/x-mscardfile":{source:"apache",extensions:["crd"]},"application/x-msclip":{source:"apache",extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{source:"apache",extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{source:"apache",extensions:["mvb","m13","m14"]},"application/x-msmetafile":{source:"apache",extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{source:"apache",extensions:["mny"]},"application/x-mspublisher":{source:"apache",extensions:["pub"]},"application/x-msschedule":{source:"apache",extensions:["scd"]},"application/x-msterminal":{source:"apache",extensions:["trm"]},"application/x-mswrite":{source:"apache",extensions:["wri"]},"application/x-netcdf":{source:"apache",extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{source:"apache",extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{source:"apache",compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{source:"apache",extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{source:"apache",extensions:["p7r"]},"application/x-pki-message":{source:"iana"},"application/x-rar-compressed":{source:"apache",compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{source:"apache",extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{source:"apache",compressible:!0,extensions:["sh"]},"application/x-shar":{source:"apache",extensions:["shar"]},"application/x-shockwave-flash":{source:"apache",compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{source:"apache",extensions:["xap"]},"application/x-sql":{source:"apache",extensions:["sql"]},"application/x-stuffit":{source:"apache",compressible:!1,extensions:["sit"]},"application/x-stuffitx":{source:"apache",extensions:["sitx"]},"application/x-subrip":{source:"apache",extensions:["srt"]},"application/x-sv4cpio":{source:"apache",extensions:["sv4cpio"]},"application/x-sv4crc":{source:"apache",extensions:["sv4crc"]},"application/x-t3vm-image":{source:"apache",extensions:["t3"]},"application/x-tads":{source:"apache",extensions:["gam"]},"application/x-tar":{source:"apache",compressible:!0,extensions:["tar"]},"application/x-tcl":{source:"apache",extensions:["tcl","tk"]},"application/x-tex":{source:"apache",extensions:["tex"]},"application/x-tex-tfm":{source:"apache",extensions:["tfm"]},"application/x-texinfo":{source:"apache",extensions:["texinfo","texi"]},"application/x-tgif":{source:"apache",extensions:["obj"]},"application/x-ustar":{source:"apache",extensions:["ustar"]},"application/x-virtualbox-hdd":{compressible:!0,extensions:["hdd"]},"application/x-virtualbox-ova":{compressible:!0,extensions:["ova"]},"application/x-virtualbox-ovf":{compressible:!0,extensions:["ovf"]},"application/x-virtualbox-vbox":{compressible:!0,extensions:["vbox"]},"application/x-virtualbox-vbox-extpack":{compressible:!1,extensions:["vbox-extpack"]},"application/x-virtualbox-vdi":{compressible:!0,extensions:["vdi"]},"application/x-virtualbox-vhd":{compressible:!0,extensions:["vhd"]},"application/x-virtualbox-vmdk":{compressible:!0,extensions:["vmdk"]},"application/x-wais-source":{source:"apache",extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-www-form-urlencoded":{source:"iana",compressible:!0},"application/x-x509-ca-cert":{source:"iana",extensions:["der","crt","pem"]},"application/x-x509-ca-ra-cert":{source:"iana"},"application/x-x509-next-ca-cert":{source:"iana"},"application/x-xfig":{source:"apache",extensions:["fig"]},"application/x-xliff+xml":{source:"apache",compressible:!0,extensions:["xlf"]},"application/x-xpinstall":{source:"apache",compressible:!1,extensions:["xpi"]},"application/x-xz":{source:"apache",extensions:["xz"]},"application/x-zmachine":{source:"apache",extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{source:"iana"},"application/xacml+xml":{source:"iana",compressible:!0},"application/xaml+xml":{source:"apache",compressible:!0,extensions:["xaml"]},"application/xcap-att+xml":{source:"iana",compressible:!0,extensions:["xav"]},"application/xcap-caps+xml":{source:"iana",compressible:!0,extensions:["xca"]},"application/xcap-diff+xml":{source:"iana",compressible:!0,extensions:["xdf"]},"application/xcap-el+xml":{source:"iana",compressible:!0,extensions:["xel"]},"application/xcap-error+xml":{source:"iana",compressible:!0},"application/xcap-ns+xml":{source:"iana",compressible:!0,extensions:["xns"]},"application/xcon-conference-info+xml":{source:"iana",compressible:!0},"application/xcon-conference-info-diff+xml":{source:"iana",compressible:!0},"application/xenc+xml":{source:"iana",compressible:!0,extensions:["xenc"]},"application/xhtml+xml":{source:"iana",compressible:!0,extensions:["xhtml","xht"]},"application/xhtml-voice+xml":{source:"apache",compressible:!0},"application/xliff+xml":{source:"iana",compressible:!0,extensions:["xlf"]},"application/xml":{source:"iana",compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{source:"iana",compressible:!0,extensions:["dtd"]},"application/xml-external-parsed-entity":{source:"iana"},"application/xml-patch+xml":{source:"iana",compressible:!0},"application/xmpp+xml":{source:"iana",compressible:!0},"application/xop+xml":{source:"iana",compressible:!0,extensions:["xop"]},"application/xproc+xml":{source:"apache",compressible:!0,extensions:["xpl"]},"application/xslt+xml":{source:"iana",compressible:!0,extensions:["xsl","xslt"]},"application/xspf+xml":{source:"apache",compressible:!0,extensions:["xspf"]},"application/xv+xml":{source:"iana",compressible:!0,extensions:["mxml","xhvml","xvml","xvm"]},"application/yang":{source:"iana",extensions:["yang"]},"application/yang-data+json":{source:"iana",compressible:!0},"application/yang-data+xml":{source:"iana",compressible:!0},"application/yang-patch+json":{source:"iana",compressible:!0},"application/yang-patch+xml":{source:"iana",compressible:!0},"application/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"application/zlib":{source:"iana"},"application/zstd":{source:"iana"},"audio/1d-interleaved-parityfec":{source:"iana"},"audio/32kadpcm":{source:"iana"},"audio/3gpp":{source:"iana",compressible:!1,extensions:["3gpp"]},"audio/3gpp2":{source:"iana"},"audio/aac":{source:"iana"},"audio/ac3":{source:"iana"},"audio/adpcm":{source:"apache",extensions:["adp"]},"audio/amr":{source:"iana",extensions:["amr"]},"audio/amr-wb":{source:"iana"},"audio/amr-wb+":{source:"iana"},"audio/aptx":{source:"iana"},"audio/asc":{source:"iana"},"audio/atrac-advanced-lossless":{source:"iana"},"audio/atrac-x":{source:"iana"},"audio/atrac3":{source:"iana"},"audio/basic":{source:"iana",compressible:!1,extensions:["au","snd"]},"audio/bv16":{source:"iana"},"audio/bv32":{source:"iana"},"audio/clearmode":{source:"iana"},"audio/cn":{source:"iana"},"audio/dat12":{source:"iana"},"audio/dls":{source:"iana"},"audio/dsr-es201108":{source:"iana"},"audio/dsr-es202050":{source:"iana"},"audio/dsr-es202211":{source:"iana"},"audio/dsr-es202212":{source:"iana"},"audio/dv":{source:"iana"},"audio/dvi4":{source:"iana"},"audio/eac3":{source:"iana"},"audio/encaprtp":{source:"iana"},"audio/evrc":{source:"iana"},"audio/evrc-qcp":{source:"iana"},"audio/evrc0":{source:"iana"},"audio/evrc1":{source:"iana"},"audio/evrcb":{source:"iana"},"audio/evrcb0":{source:"iana"},"audio/evrcb1":{source:"iana"},"audio/evrcnw":{source:"iana"},"audio/evrcnw0":{source:"iana"},"audio/evrcnw1":{source:"iana"},"audio/evrcwb":{source:"iana"},"audio/evrcwb0":{source:"iana"},"audio/evrcwb1":{source:"iana"},"audio/evs":{source:"iana"},"audio/flexfec":{source:"iana"},"audio/fwdred":{source:"iana"},"audio/g711-0":{source:"iana"},"audio/g719":{source:"iana"},"audio/g722":{source:"iana"},"audio/g7221":{source:"iana"},"audio/g723":{source:"iana"},"audio/g726-16":{source:"iana"},"audio/g726-24":{source:"iana"},"audio/g726-32":{source:"iana"},"audio/g726-40":{source:"iana"},"audio/g728":{source:"iana"},"audio/g729":{source:"iana"},"audio/g7291":{source:"iana"},"audio/g729d":{source:"iana"},"audio/g729e":{source:"iana"},"audio/gsm":{source:"iana"},"audio/gsm-efr":{source:"iana"},"audio/gsm-hr-08":{source:"iana"},"audio/ilbc":{source:"iana"},"audio/ip-mr_v2.5":{source:"iana"},"audio/isac":{source:"apache"},"audio/l16":{source:"iana"},"audio/l20":{source:"iana"},"audio/l24":{source:"iana",compressible:!1},"audio/l8":{source:"iana"},"audio/lpc":{source:"iana"},"audio/melp":{source:"iana"},"audio/melp1200":{source:"iana"},"audio/melp2400":{source:"iana"},"audio/melp600":{source:"iana"},"audio/mhas":{source:"iana"},"audio/midi":{source:"apache",extensions:["mid","midi","kar","rmi"]},"audio/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a"]},"audio/mp4a-latm":{source:"iana"},"audio/mpa":{source:"iana"},"audio/mpa-robust":{source:"iana"},"audio/mpeg":{source:"iana",compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{source:"iana"},"audio/musepack":{source:"apache"},"audio/ogg":{source:"iana",compressible:!1,extensions:["oga","ogg","spx","opus"]},"audio/opus":{source:"iana"},"audio/parityfec":{source:"iana"},"audio/pcma":{source:"iana"},"audio/pcma-wb":{source:"iana"},"audio/pcmu":{source:"iana"},"audio/pcmu-wb":{source:"iana"},"audio/prs.sid":{source:"iana"},"audio/qcelp":{source:"iana"},"audio/raptorfec":{source:"iana"},"audio/red":{source:"iana"},"audio/rtp-enc-aescm128":{source:"iana"},"audio/rtp-midi":{source:"iana"},"audio/rtploopback":{source:"iana"},"audio/rtx":{source:"iana"},"audio/s3m":{source:"apache",extensions:["s3m"]},"audio/scip":{source:"iana"},"audio/silk":{source:"apache",extensions:["sil"]},"audio/smv":{source:"iana"},"audio/smv-qcp":{source:"iana"},"audio/smv0":{source:"iana"},"audio/sofa":{source:"iana"},"audio/sp-midi":{source:"iana"},"audio/speex":{source:"iana"},"audio/t140c":{source:"iana"},"audio/t38":{source:"iana"},"audio/telephone-event":{source:"iana"},"audio/tetra_acelp":{source:"iana"},"audio/tetra_acelp_bb":{source:"iana"},"audio/tone":{source:"iana"},"audio/tsvcis":{source:"iana"},"audio/uemclip":{source:"iana"},"audio/ulpfec":{source:"iana"},"audio/usac":{source:"iana"},"audio/vdvi":{source:"iana"},"audio/vmr-wb":{source:"iana"},"audio/vnd.3gpp.iufp":{source:"iana"},"audio/vnd.4sb":{source:"iana"},"audio/vnd.audiokoz":{source:"iana"},"audio/vnd.celp":{source:"iana"},"audio/vnd.cisco.nse":{source:"iana"},"audio/vnd.cmles.radio-events":{source:"iana"},"audio/vnd.cns.anp1":{source:"iana"},"audio/vnd.cns.inf1":{source:"iana"},"audio/vnd.dece.audio":{source:"iana",extensions:["uva","uvva"]},"audio/vnd.digital-winds":{source:"iana",extensions:["eol"]},"audio/vnd.dlna.adts":{source:"iana"},"audio/vnd.dolby.heaac.1":{source:"iana"},"audio/vnd.dolby.heaac.2":{source:"iana"},"audio/vnd.dolby.mlp":{source:"iana"},"audio/vnd.dolby.mps":{source:"iana"},"audio/vnd.dolby.pl2":{source:"iana"},"audio/vnd.dolby.pl2x":{source:"iana"},"audio/vnd.dolby.pl2z":{source:"iana"},"audio/vnd.dolby.pulse.1":{source:"iana"},"audio/vnd.dra":{source:"iana",extensions:["dra"]},"audio/vnd.dts":{source:"iana",extensions:["dts"]},"audio/vnd.dts.hd":{source:"iana",extensions:["dtshd"]},"audio/vnd.dts.uhd":{source:"iana"},"audio/vnd.dvb.file":{source:"iana"},"audio/vnd.everad.plj":{source:"iana"},"audio/vnd.hns.audio":{source:"iana"},"audio/vnd.lucent.voice":{source:"iana",extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{source:"iana",extensions:["pya"]},"audio/vnd.nokia.mobile-xmf":{source:"iana"},"audio/vnd.nortel.vbk":{source:"iana"},"audio/vnd.nuera.ecelp4800":{source:"iana",extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{source:"iana",extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{source:"iana",extensions:["ecelp9600"]},"audio/vnd.octel.sbc":{source:"iana"},"audio/vnd.presonus.multitrack":{source:"iana"},"audio/vnd.qcelp":{source:"iana"},"audio/vnd.rhetorex.32kadpcm":{source:"iana"},"audio/vnd.rip":{source:"iana",extensions:["rip"]},"audio/vnd.rn-realaudio":{compressible:!1},"audio/vnd.sealedmedia.softseal.mpeg":{source:"iana"},"audio/vnd.vmx.cvsd":{source:"iana"},"audio/vnd.wave":{compressible:!1},"audio/vorbis":{source:"iana",compressible:!1},"audio/vorbis-config":{source:"iana"},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{source:"apache",compressible:!1,extensions:["weba"]},"audio/x-aac":{source:"apache",compressible:!1,extensions:["aac"]},"audio/x-aiff":{source:"apache",extensions:["aif","aiff","aifc"]},"audio/x-caf":{source:"apache",compressible:!1,extensions:["caf"]},"audio/x-flac":{source:"apache",extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{source:"apache",extensions:["mka"]},"audio/x-mpegurl":{source:"apache",extensions:["m3u"]},"audio/x-ms-wax":{source:"apache",extensions:["wax"]},"audio/x-ms-wma":{source:"apache",extensions:["wma"]},"audio/x-pn-realaudio":{source:"apache",extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{source:"apache",extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-tta":{source:"apache"},"audio/x-wav":{source:"apache",extensions:["wav"]},"audio/xm":{source:"apache",extensions:["xm"]},"chemical/x-cdx":{source:"apache",extensions:["cdx"]},"chemical/x-cif":{source:"apache",extensions:["cif"]},"chemical/x-cmdf":{source:"apache",extensions:["cmdf"]},"chemical/x-cml":{source:"apache",extensions:["cml"]},"chemical/x-csml":{source:"apache",extensions:["csml"]},"chemical/x-pdb":{source:"apache"},"chemical/x-xyz":{source:"apache",extensions:["xyz"]},"font/collection":{source:"iana",extensions:["ttc"]},"font/otf":{source:"iana",compressible:!0,extensions:["otf"]},"font/sfnt":{source:"iana"},"font/ttf":{source:"iana",compressible:!0,extensions:["ttf"]},"font/woff":{source:"iana",extensions:["woff"]},"font/woff2":{source:"iana",extensions:["woff2"]},"image/aces":{source:"iana",extensions:["exr"]},"image/apng":{compressible:!1,extensions:["apng"]},"image/avci":{source:"iana",extensions:["avci"]},"image/avcs":{source:"iana",extensions:["avcs"]},"image/avif":{source:"iana",compressible:!1,extensions:["avif"]},"image/bmp":{source:"iana",compressible:!0,extensions:["bmp"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"image/emf":{source:"iana",extensions:["emf"]},"image/fits":{source:"iana",extensions:["fits"]},"image/g3fax":{source:"iana",extensions:["g3"]},"image/gif":{source:"iana",compressible:!1,extensions:["gif"]},"image/heic":{source:"iana",extensions:["heic"]},"image/heic-sequence":{source:"iana",extensions:["heics"]},"image/heif":{source:"iana",extensions:["heif"]},"image/heif-sequence":{source:"iana",extensions:["heifs"]},"image/hej2k":{source:"iana",extensions:["hej2"]},"image/hsj2":{source:"iana",extensions:["hsj2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"image/jxr":{source:"iana",extensions:["jxr"]},"image/jxra":{source:"iana",extensions:["jxra"]},"image/jxrs":{source:"iana",extensions:["jxrs"]},"image/jxs":{source:"iana",extensions:["jxs"]},"image/jxsc":{source:"iana",extensions:["jxsc"]},"image/jxsi":{source:"iana",extensions:["jxsi"]},"image/jxss":{source:"iana",extensions:["jxss"]},"image/ktx":{source:"iana",extensions:["ktx"]},"image/ktx2":{source:"iana",extensions:["ktx2"]},"image/naplps":{source:"iana"},"image/pjpeg":{compressible:!1},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif"]},"image/prs.pti":{source:"iana",extensions:["pti"]},"image/pwg-raster":{source:"iana"},"image/sgi":{source:"apache",extensions:["sgi"]},"image/svg+xml":{source:"iana",compressible:!0,extensions:["svg","svgz"]},"image/t38":{source:"iana",extensions:["t38"]},"image/tiff":{source:"iana",compressible:!1,extensions:["tif","tiff"]},"image/tiff-fx":{source:"iana",extensions:["tfx"]},"image/vnd.adobe.photoshop":{source:"iana",compressible:!0,extensions:["psd"]},"image/vnd.airzip.accelerator.azv":{source:"iana",extensions:["azv"]},"image/vnd.cns.inf2":{source:"iana"},"image/vnd.dece.graphic":{source:"iana",extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{source:"iana",extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"image/vnd.dwg":{source:"iana",extensions:["dwg"]},"image/vnd.dxf":{source:"iana",extensions:["dxf"]},"image/vnd.fastbidsheet":{source:"iana",extensions:["fbs"]},"image/vnd.fpx":{source:"iana",extensions:["fpx"]},"image/vnd.fst":{source:"iana",extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{source:"iana",extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{source:"iana",extensions:["rlc"]},"image/vnd.globalgraphics.pgb":{source:"iana"},"image/vnd.microsoft.icon":{source:"iana",compressible:!0,extensions:["ico"]},"image/vnd.mix":{source:"iana"},"image/vnd.mozilla.apng":{source:"iana"},"image/vnd.ms-dds":{compressible:!0,extensions:["dds"]},"image/vnd.ms-modi":{source:"iana",extensions:["mdi"]},"image/vnd.ms-photo":{source:"apache",extensions:["wdp"]},"image/vnd.net-fpx":{source:"iana",extensions:["npx"]},"image/vnd.pco.b16":{source:"iana",extensions:["b16"]},"image/vnd.radiance":{source:"iana"},"image/vnd.sealed.png":{source:"iana"},"image/vnd.sealedmedia.softseal.gif":{source:"iana"},"image/vnd.sealedmedia.softseal.jpg":{source:"iana"},"image/vnd.svf":{source:"iana"},"image/vnd.tencent.tap":{source:"iana",extensions:["tap"]},"image/vnd.valve.source.texture":{source:"iana",extensions:["vtf"]},"image/vnd.wap.wbmp":{source:"iana",extensions:["wbmp"]},"image/vnd.xiff":{source:"iana",extensions:["xif"]},"image/vnd.zbrush.pcx":{source:"iana",extensions:["pcx"]},"image/webp":{source:"apache",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"image/x-freehand":{source:"apache",extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{source:"apache",compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{source:"apache",extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{source:"apache",extensions:["pcx"]},"image/x-pict":{source:"apache",extensions:["pic","pct"]},"image/x-portable-anymap":{source:"apache",extensions:["pnm"]},"image/x-portable-bitmap":{source:"apache",extensions:["pbm"]},"image/x-portable-graymap":{source:"apache",extensions:["pgm"]},"image/x-portable-pixmap":{source:"apache",extensions:["ppm"]},"image/x-rgb":{source:"apache",extensions:["rgb"]},"image/x-tga":{source:"apache",extensions:["tga"]},"image/x-xbitmap":{source:"apache",extensions:["xbm"]},"image/x-xcf":{compressible:!1},"image/x-xpixmap":{source:"apache",extensions:["xpm"]},"image/x-xwindowdump":{source:"apache",extensions:["xwd"]},"message/cpim":{source:"iana"},"message/delivery-status":{source:"iana"},"message/disposition-notification":{source:"iana",extensions:["disposition-notification"]},"message/external-body":{source:"iana"},"message/feedback-report":{source:"iana"},"message/global":{source:"iana",extensions:["u8msg"]},"message/global-delivery-status":{source:"iana",extensions:["u8dsn"]},"message/global-disposition-notification":{source:"iana",extensions:["u8mdn"]},"message/global-headers":{source:"iana",extensions:["u8hdr"]},"message/http":{source:"iana",compressible:!1},"message/imdn+xml":{source:"iana",compressible:!0},"message/news":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime"]},"message/s-http":{source:"iana"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"iana"},"message/vnd.wfa.wsc":{source:"iana",extensions:["wsc"]},"model/3mf":{source:"iana",extensions:["3mf"]},"model/e57":{source:"iana"},"model/gltf+json":{source:"iana",compressible:!0,extensions:["gltf"]},"model/gltf-binary":{source:"iana",compressible:!0,extensions:["glb"]},"model/iges":{source:"iana",compressible:!1,extensions:["igs","iges"]},"model/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/step":{source:"iana"},"model/step+xml":{source:"iana",compressible:!0,extensions:["stpx"]},"model/step+zip":{source:"iana",compressible:!1,extensions:["stpz"]},"model/step-xml+zip":{source:"iana",compressible:!1,extensions:["stpxz"]},"model/stl":{source:"iana",extensions:["stl"]},"model/vnd.collada+xml":{source:"iana",compressible:!0,extensions:["dae"]},"model/vnd.dwf":{source:"iana",extensions:["dwf"]},"model/vnd.flatland.3dml":{source:"iana"},"model/vnd.gdl":{source:"iana",extensions:["gdl"]},"model/vnd.gs-gdl":{source:"apache"},"model/vnd.gs.gdl":{source:"iana"},"model/vnd.gtw":{source:"iana",extensions:["gtw"]},"model/vnd.moml+xml":{source:"iana",compressible:!0},"model/vnd.mts":{source:"iana",extensions:["mts"]},"model/vnd.opengex":{source:"iana",extensions:["ogex"]},"model/vnd.parasolid.transmit.binary":{source:"iana",extensions:["x_b"]},"model/vnd.parasolid.transmit.text":{source:"iana",extensions:["x_t"]},"model/vnd.pytha.pyox":{source:"iana"},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"model/vnd.usdz+zip":{source:"iana",compressible:!1,extensions:["usdz"]},"model/vnd.valve.source.compiled-map":{source:"iana",extensions:["bsp"]},"model/vnd.vtu":{source:"iana",extensions:["vtu"]},"model/vrml":{source:"iana",compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{source:"apache",compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+fastinfoset":{source:"iana",extensions:["x3db"]},"model/x3d+vrml":{source:"apache",compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{source:"iana",compressible:!0,extensions:["x3d","x3dz"]},"model/x3d-vrml":{source:"iana",extensions:["x3dv"]},"multipart/alternative":{source:"iana",compressible:!1},"multipart/appledouble":{source:"iana"},"multipart/byteranges":{source:"iana"},"multipart/digest":{source:"iana"},"multipart/encrypted":{source:"iana",compressible:!1},"multipart/form-data":{source:"iana",compressible:!1},"multipart/header-set":{source:"iana"},"multipart/mixed":{source:"iana"},"multipart/multilingual":{source:"iana"},"multipart/parallel":{source:"iana"},"multipart/related":{source:"iana",compressible:!1},"multipart/report":{source:"iana"},"multipart/signed":{source:"iana",compressible:!1},"multipart/vnd.bint.med-plus":{source:"iana"},"multipart/voice-message":{source:"iana"},"multipart/x-mixed-replace":{source:"iana"},"text/1d-interleaved-parityfec":{source:"iana"},"text/cache-manifest":{source:"iana",compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{source:"iana",extensions:["ics","ifb"]},"text/calender":{compressible:!0},"text/cmd":{compressible:!0},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/cql":{source:"iana"},"text/cql-expression":{source:"iana"},"text/cql-identifier":{source:"iana"},"text/css":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["css"]},"text/csv":{source:"iana",compressible:!0,extensions:["csv"]},"text/csv-schema":{source:"iana"},"text/directory":{source:"iana"},"text/dns":{source:"iana"},"text/ecmascript":{source:"iana"},"text/encaprtp":{source:"iana"},"text/enriched":{source:"iana"},"text/fhirpath":{source:"iana"},"text/flexfec":{source:"iana"},"text/fwdred":{source:"iana"},"text/gff3":{source:"iana"},"text/grammar-ref-list":{source:"iana"},"text/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",compressible:!0},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["markdown","md"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/mdx":{compressible:!0,extensions:["mdx"]},"text/mizar":{source:"iana"},"text/n3":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["n3"]},"text/parameters":{source:"iana",charset:"UTF-8"},"text/parityfec":{source:"iana"},"text/plain":{source:"iana",compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{source:"iana",charset:"UTF-8"},"text/prs.fallenstein.rst":{source:"iana"},"text/prs.lines.tag":{source:"iana",extensions:["dsc"]},"text/prs.prop.logic":{source:"iana"},"text/raptorfec":{source:"iana"},"text/red":{source:"iana"},"text/rfc822-headers":{source:"iana"},"text/richtext":{source:"iana",compressible:!0,extensions:["rtx"]},"text/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"text/rtp-enc-aescm128":{source:"iana"},"text/rtploopback":{source:"iana"},"text/rtx":{source:"iana"},"text/sgml":{source:"iana",extensions:["sgml","sgm"]},"text/shaclc":{source:"iana"},"text/shex":{source:"iana",extensions:["shex"]},"text/slim":{extensions:["slim","slm"]},"text/spdx":{source:"iana",extensions:["spdx"]},"text/strings":{source:"iana"},"text/stylus":{extensions:["stylus","styl"]},"text/t140":{source:"iana"},"text/tab-separated-values":{source:"iana",compressible:!0,extensions:["tsv"]},"text/troff":{source:"iana",extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{source:"iana",charset:"UTF-8",extensions:["ttl"]},"text/ulpfec":{source:"iana"},"text/uri-list":{source:"iana",compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{source:"iana",compressible:!0,extensions:["vcard"]},"text/vnd.a":{source:"iana"},"text/vnd.abc":{source:"iana"},"text/vnd.ascii-art":{source:"iana"},"text/vnd.curl":{source:"iana",extensions:["curl"]},"text/vnd.curl.dcurl":{source:"apache",extensions:["dcurl"]},"text/vnd.curl.mcurl":{source:"apache",extensions:["mcurl"]},"text/vnd.curl.scurl":{source:"apache",extensions:["scurl"]},"text/vnd.debian.copyright":{source:"iana",charset:"UTF-8"},"text/vnd.dmclientscript":{source:"iana"},"text/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"text/vnd.esmertec.theme-descriptor":{source:"iana",charset:"UTF-8"},"text/vnd.familysearch.gedcom":{source:"iana",extensions:["ged"]},"text/vnd.ficlab.flt":{source:"iana"},"text/vnd.fly":{source:"iana",extensions:["fly"]},"text/vnd.fmi.flexstor":{source:"iana",extensions:["flx"]},"text/vnd.gml":{source:"iana"},"text/vnd.graphviz":{source:"iana",extensions:["gv"]},"text/vnd.hans":{source:"iana"},"text/vnd.hgl":{source:"iana"},"text/vnd.in3d.3dml":{source:"iana",extensions:["3dml"]},"text/vnd.in3d.spot":{source:"iana",extensions:["spot"]},"text/vnd.iptc.newsml":{source:"iana"},"text/vnd.iptc.nitf":{source:"iana"},"text/vnd.latex-z":{source:"iana"},"text/vnd.motorola.reflex":{source:"iana"},"text/vnd.ms-mediapackage":{source:"iana"},"text/vnd.net2phone.commcenter.command":{source:"iana"},"text/vnd.radisys.msml-basic-layout":{source:"iana"},"text/vnd.senx.warpscript":{source:"iana"},"text/vnd.si.uricatalogue":{source:"iana"},"text/vnd.sosi":{source:"iana"},"text/vnd.sun.j2me.app-descriptor":{source:"iana",charset:"UTF-8",extensions:["jad"]},"text/vnd.trolltech.linguist":{source:"iana",charset:"UTF-8"},"text/vnd.wap.si":{source:"iana"},"text/vnd.wap.sl":{source:"iana"},"text/vnd.wap.wml":{source:"iana",extensions:["wml"]},"text/vnd.wap.wmlscript":{source:"iana",extensions:["wmls"]},"text/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/x-asm":{source:"apache",extensions:["s","asm"]},"text/x-c":{source:"apache",extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{source:"apache",extensions:["f","for","f77","f90"]},"text/x-gwt-rpc":{compressible:!0},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{source:"apache",extensions:["java"]},"text/x-jquery-tmpl":{compressible:!0},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["mkd"]},"text/x-nfo":{source:"apache",extensions:["nfo"]},"text/x-opml":{source:"apache",extensions:["opml"]},"text/x-org":{compressible:!0,extensions:["org"]},"text/x-pascal":{source:"apache",extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{source:"apache",extensions:["etx"]},"text/x-sfv":{source:"apache",extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{source:"apache",extensions:["uu"]},"text/x-vcalendar":{source:"apache",extensions:["vcs"]},"text/x-vcard":{source:"apache",extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/xml-external-parsed-entity":{source:"iana"},"text/yaml":{compressible:!0,extensions:["yaml","yml"]},"video/1d-interleaved-parityfec":{source:"iana"},"video/3gpp":{source:"iana",extensions:["3gp","3gpp"]},"video/3gpp-tt":{source:"iana"},"video/3gpp2":{source:"iana",extensions:["3g2"]},"video/av1":{source:"iana"},"video/bmpeg":{source:"iana"},"video/bt656":{source:"iana"},"video/celb":{source:"iana"},"video/dv":{source:"iana"},"video/encaprtp":{source:"iana"},"video/ffv1":{source:"iana"},"video/flexfec":{source:"iana"},"video/h261":{source:"iana",extensions:["h261"]},"video/h263":{source:"iana",extensions:["h263"]},"video/h263-1998":{source:"iana"},"video/h263-2000":{source:"iana"},"video/h264":{source:"iana",extensions:["h264"]},"video/h264-rcdo":{source:"iana"},"video/h264-svc":{source:"iana"},"video/h265":{source:"iana"},"video/iso.segment":{source:"iana",extensions:["m4s"]},"video/jpeg":{source:"iana",extensions:["jpgv"]},"video/jpeg2000":{source:"iana"},"video/jpm":{source:"apache",extensions:["jpm","jpgm"]},"video/jxsv":{source:"iana"},"video/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts"]},"video/mp4":{source:"iana",compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mp4v-es":{source:"iana"},"video/mpeg":{source:"iana",compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{source:"iana"},"video/mpv":{source:"iana"},"video/nv":{source:"iana"},"video/ogg":{source:"iana",compressible:!1,extensions:["ogv"]},"video/parityfec":{source:"iana"},"video/pointer":{source:"iana"},"video/quicktime":{source:"iana",compressible:!1,extensions:["qt","mov"]},"video/raptorfec":{source:"iana"},"video/raw":{source:"iana"},"video/rtp-enc-aescm128":{source:"iana"},"video/rtploopback":{source:"iana"},"video/rtx":{source:"iana"},"video/scip":{source:"iana"},"video/smpte291":{source:"iana"},"video/smpte292m":{source:"iana"},"video/ulpfec":{source:"iana"},"video/vc1":{source:"iana"},"video/vc2":{source:"iana"},"video/vnd.cctv":{source:"iana"},"video/vnd.dece.hd":{source:"iana",extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{source:"iana",extensions:["uvm","uvvm"]},"video/vnd.dece.mp4":{source:"iana"},"video/vnd.dece.pd":{source:"iana",extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{source:"iana",extensions:["uvs","uvvs"]},"video/vnd.dece.video":{source:"iana",extensions:["uvv","uvvv"]},"video/vnd.directv.mpeg":{source:"iana"},"video/vnd.directv.mpeg-tts":{source:"iana"},"video/vnd.dlna.mpeg-tts":{source:"iana"},"video/vnd.dvb.file":{source:"iana",extensions:["dvb"]},"video/vnd.fvt":{source:"iana",extensions:["fvt"]},"video/vnd.hns.video":{source:"iana"},"video/vnd.iptvforum.1dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.1dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.2dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.2dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.ttsavc":{source:"iana"},"video/vnd.iptvforum.ttsmpeg2":{source:"iana"},"video/vnd.motorola.video":{source:"iana"},"video/vnd.motorola.videop":{source:"iana"},"video/vnd.mpegurl":{source:"iana",extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{source:"iana",extensions:["pyv"]},"video/vnd.nokia.interleaved-multimedia":{source:"iana"},"video/vnd.nokia.mp4vr":{source:"iana"},"video/vnd.nokia.videovoip":{source:"iana"},"video/vnd.objectvideo":{source:"iana"},"video/vnd.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"iana"},"video/vnd.sealed.mpeg1":{source:"iana"},"video/vnd.sealed.mpeg4":{source:"iana"},"video/vnd.sealed.swf":{source:"iana"},"video/vnd.sealedmedia.softseal.mov":{source:"iana"},"video/vnd.uvvu.mp4":{source:"iana",extensions:["uvu","uvvu"]},"video/vnd.vivo":{source:"iana",extensions:["viv"]},"video/vnd.youtube.yt":{source:"iana"},"video/vp8":{source:"iana"},"video/vp9":{source:"iana"},"video/webm":{source:"apache",compressible:!1,extensions:["webm"]},"video/x-f4v":{source:"apache",extensions:["f4v"]},"video/x-fli":{source:"apache",extensions:["fli"]},"video/x-flv":{source:"apache",compressible:!1,extensions:["flv"]},"video/x-m4v":{source:"apache",extensions:["m4v"]},"video/x-matroska":{source:"apache",compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{source:"apache",extensions:["mng"]},"video/x-ms-asf":{source:"apache",extensions:["asf","asx"]},"video/x-ms-vob":{source:"apache",extensions:["vob"]},"video/x-ms-wm":{source:"apache",extensions:["wm"]},"video/x-ms-wmv":{source:"apache",compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{source:"apache",extensions:["wmx"]},"video/x-ms-wvx":{source:"apache",extensions:["wvx"]},"video/x-msvideo":{source:"apache",extensions:["avi"]},"video/x-sgi-movie":{source:"apache",extensions:["movie"]},"video/x-smv":{source:"apache",extensions:["smv"]},"x-conference/x-cooltalk":{source:"apache",extensions:["ice"]},"x-shader/x-fragment":{compressible:!0},"x-shader/x-vertex":{compressible:!0}}});var fp=P((pq,mp)=>{"use strict";p();mp.exports=pp()});var yp=P(rt=>{"use strict";p();var Ri=fp(),Ww=ne("path").extname,gp=/^\s*([^;\s]*)(?:;|\s|$)/,Jw=/^text\//i;rt.charset=hp;rt.charsets={lookup:hp};rt.contentType=Kw;rt.extension=Yw;rt.extensions=Object.create(null);rt.lookup=zw;rt.types=Object.create(null);Xw(rt.extensions,rt.types);function hp(e){if(!e||typeof e!="string")return!1;var t=gp.exec(e),r=t&&Ri[t[1].toLowerCase()];return r&&r.charset?r.charset:t&&Jw.test(t[1])?"UTF-8":!1}function Kw(e){if(!e||typeof e!="string")return!1;var t=e.indexOf("/")===-1?rt.lookup(e):e;if(!t)return!1;if(t.indexOf("charset")===-1){var r=rt.charset(t);r&&(t+="; charset="+r.toLowerCase())}return t}function Yw(e){if(!e||typeof e!="string")return!1;var t=gp.exec(e),r=t&&rt.extensions[t[1].toLowerCase()];return!r||!r.length?!1:r[0]}function zw(e){if(!e||typeof e!="string")return!1;var t=Ww("x."+e).toLowerCase().substr(1);return t&&rt.types[t]||!1}function Xw(e,t){var r=["nginx","apache",void 0,"iana"];Object.keys(Ri).forEach(function(s){var i=Ri[s],a=i.extensions;if(!(!a||!a.length)){e[s]=a;for(var o=0;o<a.length;o++){var c=a[o];if(t[c]){var u=r.indexOf(Ri[t[c]].source),l=r.indexOf(i.source);if(t[c]!=="application/octet-stream"&&(u>l||u===l&&t[c].substr(0,12)==="application/"))continue}t[c]=s}}})}});var Ep=P((hq,_p)=>{"use strict";p();_p.exports=Qw;function Qw(e){var t=typeof setImmediate=="function"?setImmediate:typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:null;t?t(e):setTimeout(e,0)}});var Ko=P((_q,bp)=>{"use strict";p();var Tp=Ep();bp.exports=Zw;function Zw(e){var t=!1;return Tp(function(){t=!0}),function(n,s){t?e(n,s):Tp(function(){e(n,s)})}}});var Yo=P((Tq,vp)=>{"use strict";p();vp.exports=eS;function eS(e){Object.keys(e.jobs).forEach(tS.bind(e)),e.jobs={}}function tS(e){typeof this.jobs[e]=="function"&&this.jobs[e]()}});var zo=P((vq,Rp)=>{"use strict";p();var xp=Ko(),rS=Yo();Rp.exports=nS;function nS(e,t,r,n){var s=r.keyedList?r.keyedList[r.index]:r.index;r.jobs[s]=sS(t,s,e[s],function(i,a){s in r.jobs&&(delete r.jobs[s],i?rS(r):r.results[s]=a,n(i,r.results))})}function sS(e,t,r,n){var s;return e.length==2?s=e(r,xp(n)):s=e(r,t,xp(n)),s}});var Xo=P((Rq,Ap)=>{"use strict";p();Ap.exports=iS;function iS(e,t){var r=!Array.isArray(e),n={index:0,keyedList:r||t?Object.keys(e):null,jobs:{},results:r?{}:[],size:r?Object.keys(e).length:e.length};return t&&n.keyedList.sort(r?t:function(s,i){return t(e[s],e[i])}),n}});var Qo=P((wq,wp)=>{"use strict";p();var aS=Yo(),oS=Ko();wp.exports=cS;function cS(e){Object.keys(this.jobs).length&&(this.index=this.size,aS(this),oS(e)(null,this.results))}});var Ip=P((Iq,Sp)=>{"use strict";p();var lS=zo(),uS=Xo(),dS=Qo();Sp.exports=pS;function pS(e,t,r){for(var n=uS(e);n.index<(n.keyedList||e).length;)lS(e,t,n,function(s,i){if(s){r(s,i);return}if(Object.keys(n.jobs).length===0){r(null,n.results);return}}),n.index++;return dS.bind(n,r)}});var Zo=P((Dq,Ai)=>{"use strict";p();var Pp=zo(),mS=Xo(),fS=Qo();Ai.exports=gS;Ai.exports.ascending=Dp;Ai.exports.descending=hS;function gS(e,t,r,n){var s=mS(e,r);return Pp(e,t,s,function i(a,o){if(a){n(a,o);return}if(s.index++,s.index<(s.keyedList||e).length){Pp(e,t,s,i);return}n(null,s.results)}),fS.bind(s,n)}function Dp(e,t){return e<t?-1:e>t?1:0}function hS(e,t){return-1*Dp(e,t)}});var Cp=P((Cq,Op)=>{"use strict";p();var yS=Zo();Op.exports=_S;function _S(e,t,r){return yS(e,t,null,r)}});var Lp=P((Lq,Np)=>{"use strict";p();Np.exports={parallel:Ip(),serial:Cp(),serialOrdered:Zo()}});var ec=P((Mq,kp)=>{"use strict";p();kp.exports=Object});var Up=P((Fq,Mp)=>{"use strict";p();Mp.exports=Error});var jp=P((qq,Fp)=>{"use strict";p();Fp.exports=EvalError});var Bp=P((Vq,qp)=>{"use strict";p();qp.exports=RangeError});var Gp=P((Hq,Vp)=>{"use strict";p();Vp.exports=ReferenceError});var $p=P((Wq,Hp)=>{"use strict";p();Hp.exports=SyntaxError});var wi=P((Kq,Wp)=>{"use strict";p();Wp.exports=TypeError});var Kp=P((zq,Jp)=>{"use strict";p();Jp.exports=URIError});var zp=P((Qq,Yp)=>{"use strict";p();Yp.exports=Math.abs});var Qp=P((eB,Xp)=>{"use strict";p();Xp.exports=Math.floor});var em=P((rB,Zp)=>{"use strict";p();Zp.exports=Math.max});var rm=P((sB,tm)=>{"use strict";p();tm.exports=Math.min});var sm=P((aB,nm)=>{"use strict";p();nm.exports=Math.pow});var am=P((cB,im)=>{"use strict";p();im.exports=Math.round});var cm=P((uB,om)=>{"use strict";p();om.exports=Number.isNaN||function(t){return t!==t}});var um=P((pB,lm)=>{"use strict";p();var ES=cm();lm.exports=function(t){return ES(t)||t===0?t:t<0?-1:1}});var pm=P((fB,dm)=>{"use strict";p();dm.exports=Object.getOwnPropertyDescriptor});var tc=P((hB,mm)=>{"use strict";p();var Si=pm();if(Si)try{Si([],"length")}catch{Si=null}mm.exports=Si});var gm=P((_B,fm)=>{"use strict";p();var Ii=Object.defineProperty||!1;if(Ii)try{Ii({},"a",{value:1})}catch{Ii=!1}fm.exports=Ii});var rc=P((TB,hm)=>{"use strict";p();hm.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var s=42;t[r]=s;for(var i in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var a=Object.getOwnPropertySymbols(t);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(t,r);if(o.value!==s||o.enumerable!==!0)return!1}return!0}});var Em=P((vB,_m)=>{"use strict";p();var ym=typeof Symbol<"u"&&Symbol,TS=rc();_m.exports=function(){return typeof ym!="function"||typeof Symbol!="function"||typeof ym("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:TS()}});var nc=P((RB,Tm)=>{"use strict";p();Tm.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var sc=P((wB,bm)=>{"use strict";p();var bS=ec();bm.exports=bS.getPrototypeOf||null});var Rm=P((IB,xm)=>{"use strict";p();var vS="Function.prototype.bind called on incompatible ",xS=Object.prototype.toString,RS=Math.max,AS="[object Function]",vm=function(t,r){for(var n=[],s=0;s<t.length;s+=1)n[s]=t[s];for(var i=0;i<r.length;i+=1)n[i+t.length]=r[i];return n},wS=function(t,r){for(var n=[],s=r||0,i=0;s<t.length;s+=1,i+=1)n[i]=t[s];return n},SS=function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r};xm.exports=function(t){var r=this;if(typeof r!="function"||xS.apply(r)!==AS)throw new TypeError(vS+r);for(var n=wS(arguments,1),s,i=function(){if(this instanceof s){var l=r.apply(this,vm(n,arguments));return Object(l)===l?l:this}return r.apply(t,vm(n,arguments))},a=RS(0,r.length-n.length),o=[],c=0;c<a;c++)o[c]="$"+c;if(s=Function("binder","return function ("+SS(o,",")+"){ return binder.apply(this,arguments); }")(i),r.prototype){var u=function(){};u.prototype=r.prototype,s.prototype=new u,u.prototype=null}return s}});var ts=P((DB,Am)=>{"use strict";p();var IS=Rm();Am.exports=Function.prototype.bind||IS});var Pi=P((CB,wm)=>{"use strict";p();wm.exports=Function.prototype.call});var ic=P((LB,Sm)=>{"use strict";p();Sm.exports=Function.prototype.apply});var Pm=P((MB,Im)=>{"use strict";p();Im.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply});var Om=P((FB,Dm)=>{"use strict";p();var PS=ts(),DS=ic(),OS=Pi(),CS=Pm();Dm.exports=CS||PS.call(OS,DS)});var Nm=P((qB,Cm)=>{"use strict";p();var NS=ts(),LS=wi(),kS=Pi(),MS=Om();Cm.exports=function(t){if(t.length<1||typeof t[0]!="function")throw new LS("a function is required");return MS(NS,kS,t)}});var jm=P((VB,Fm)=>{"use strict";p();var US=Nm(),Lm=tc(),Mm;try{Mm=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!="object"||!("code"in e)||e.code!=="ERR_PROTO_ACCESS")throw e}var ac=!!Mm&&Lm&&Lm(Object.prototype,"__proto__"),Um=Object,km=Um.getPrototypeOf;Fm.exports=ac&&typeof ac.get=="function"?US([ac.get]):typeof km=="function"?function(t){return km(t==null?t:Um(t))}:!1});var Hm=P((HB,Gm)=>{"use strict";p();var qm=nc(),Bm=sc(),Vm=jm();Gm.exports=qm?function(t){return qm(t)}:Bm?function(t){if(!t||typeof t!="object"&&typeof t!="function")throw new TypeError("getProto: not an object");return Bm(t)}:Vm?function(t){return Vm(t)}:null});var Di=P((WB,$m)=>{"use strict";p();var FS=Function.prototype.call,jS=Object.prototype.hasOwnProperty,qS=ts();$m.exports=qS.call(FS,jS)});var Qm=P((KB,Xm)=>{"use strict";p();var te,BS=ec(),VS=Up(),GS=jp(),HS=Bp(),$S=Gp(),dn=$p(),un=wi(),WS=Kp(),JS=zp(),KS=Qp(),YS=em(),zS=rm(),XS=sm(),QS=am(),ZS=um(),Ym=Function,oc=function(e){try{return Ym('"use strict"; return ('+e+").constructor;")()}catch{}},rs=tc(),eI=gm(),cc=function(){throw new un},tI=rs?(function(){try{return arguments.callee,cc}catch{try{return rs(arguments,"callee").get}catch{return cc}}})():cc,cn=Em()(),je=Hm(),rI=sc(),nI=nc(),zm=ic(),ns=Pi(),ln={},sI=typeof Uint8Array>"u"||!je?te:je(Uint8Array),Or={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?te:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?te:ArrayBuffer,"%ArrayIteratorPrototype%":cn&&je?je([][Symbol.iterator]()):te,"%AsyncFromSyncIteratorPrototype%":te,"%AsyncFunction%":ln,"%AsyncGenerator%":ln,"%AsyncGeneratorFunction%":ln,"%AsyncIteratorPrototype%":ln,"%Atomics%":typeof Atomics>"u"?te:Atomics,"%BigInt%":typeof BigInt>"u"?te:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?te:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?te:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?te:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":VS,"%eval%":eval,"%EvalError%":GS,"%Float16Array%":typeof Float16Array>"u"?te:Float16Array,"%Float32Array%":typeof Float32Array>"u"?te:Float32Array,"%Float64Array%":typeof Float64Array>"u"?te:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?te:FinalizationRegistry,"%Function%":Ym,"%GeneratorFunction%":ln,"%Int8Array%":typeof Int8Array>"u"?te:Int8Array,"%Int16Array%":typeof Int16Array>"u"?te:Int16Array,"%Int32Array%":typeof Int32Array>"u"?te:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":cn&&je?je(je([][Symbol.iterator]())):te,"%JSON%":typeof JSON=="object"?JSON:te,"%Map%":typeof Map>"u"?te:Map,"%MapIteratorPrototype%":typeof Map>"u"||!cn||!je?te:je(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":BS,"%Object.getOwnPropertyDescriptor%":rs,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?te:Promise,"%Proxy%":typeof Proxy>"u"?te:Proxy,"%RangeError%":HS,"%ReferenceError%":$S,"%Reflect%":typeof Reflect>"u"?te:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?te:Set,"%SetIteratorPrototype%":typeof Set>"u"||!cn||!je?te:je(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?te:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":cn&&je?je(""[Symbol.iterator]()):te,"%Symbol%":cn?Symbol:te,"%SyntaxError%":dn,"%ThrowTypeError%":tI,"%TypedArray%":sI,"%TypeError%":un,"%Uint8Array%":typeof Uint8Array>"u"?te:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?te:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?te:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?te:Uint32Array,"%URIError%":WS,"%WeakMap%":typeof WeakMap>"u"?te:WeakMap,"%WeakRef%":typeof WeakRef>"u"?te:WeakRef,"%WeakSet%":typeof WeakSet>"u"?te:WeakSet,"%Function.prototype.call%":ns,"%Function.prototype.apply%":zm,"%Object.defineProperty%":eI,"%Object.getPrototypeOf%":rI,"%Math.abs%":JS,"%Math.floor%":KS,"%Math.max%":YS,"%Math.min%":zS,"%Math.pow%":XS,"%Math.round%":QS,"%Math.sign%":ZS,"%Reflect.getPrototypeOf%":nI};if(je)try{null.error}catch(e){Wm=je(je(e)),Or["%Error.prototype%"]=Wm}var Wm,iI=function e(t){var r;if(t==="%AsyncFunction%")r=oc("async function () {}");else if(t==="%GeneratorFunction%")r=oc("function* () {}");else if(t==="%AsyncGeneratorFunction%")r=oc("async function* () {}");else if(t==="%AsyncGenerator%"){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(t==="%AsyncIteratorPrototype%"){var s=e("%AsyncGenerator%");s&&je&&(r=je(s.prototype))}return Or[t]=r,r},Jm={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},ss=ts(),Oi=Di(),aI=ss.call(ns,Array.prototype.concat),oI=ss.call(zm,Array.prototype.splice),Km=ss.call(ns,String.prototype.replace),Ci=ss.call(ns,String.prototype.slice),cI=ss.call(ns,RegExp.prototype.exec),lI=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,uI=/\\(\\)?/g,dI=function(t){var r=Ci(t,0,1),n=Ci(t,-1);if(r==="%"&&n!=="%")throw new dn("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new dn("invalid intrinsic syntax, expected opening `%`");var s=[];return Km(t,lI,function(i,a,o,c){s[s.length]=o?Km(c,uI,"$1"):a||i}),s},pI=function(t,r){var n=t,s;if(Oi(Jm,n)&&(s=Jm[n],n="%"+s[0]+"%"),Oi(Or,n)){var i=Or[n];if(i===ln&&(i=iI(n)),typeof i>"u"&&!r)throw new un("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:s,name:n,value:i}}throw new dn("intrinsic "+t+" does not exist!")};Xm.exports=function(t,r){if(typeof t!="string"||t.length===0)throw new un("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new un('"allowMissing" argument must be a boolean');if(cI(/^%?[^%]*%?$/,t)===null)throw new dn("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=dI(t),s=n.length>0?n[0]:"",i=pI("%"+s+"%",r),a=i.name,o=i.value,c=!1,u=i.alias;u&&(s=u[0],oI(n,aI([0,1],u)));for(var l=1,d=!0;l<n.length;l+=1){var m=n[l],f=Ci(m,0,1),g=Ci(m,-1);if((f==='"'||f==="'"||f==="`"||g==='"'||g==="'"||g==="`")&&f!==g)throw new dn("property names with quotes must have matching quotes");if((m==="constructor"||!d)&&(c=!0),s+="."+m,a="%"+s+"%",Oi(Or,a))o=Or[a];else if(o!=null){if(!(m in o)){if(!r)throw new un("base intrinsic for "+t+" exists, but the property is not available.");return}if(rs&&l+1>=n.length){var _=rs(o,m);d=!!_,d&&"get"in _&&!("originalValue"in _.get)?o=_.get:o=o[m]}else d=Oi(o,m),o=o[m];d&&!c&&(Or[a]=o)}}return o}});var ef=P((zB,Zm)=>{"use strict";p();var mI=rc();Zm.exports=function(){return mI()&&!!Symbol.toStringTag}});var nf=P((QB,rf)=>{"use strict";p();var fI=Qm(),tf=fI("%Object.defineProperty%",!0),gI=ef()(),hI=Di(),yI=wi(),Ni=gI?Symbol.toStringTag:null;rf.exports=function(t,r){var n=arguments.length>2&&!!arguments[2]&&arguments[2].force,s=arguments.length>2&&!!arguments[2]&&arguments[2].nonConfigurable;if(typeof n<"u"&&typeof n!="boolean"||typeof s<"u"&&typeof s!="boolean")throw new yI("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");Ni&&(n||!hI(t,Ni))&&(tf?tf(t,Ni,{configurable:!s,enumerable:!1,value:r,writable:!1}):t[Ni]=r)}});var af=P((eV,sf)=>{"use strict";p();sf.exports=function(e,t){return Object.keys(t).forEach(function(r){e[r]=e[r]||t[r]}),e}});var lf=P((rV,cf)=>{"use strict";p();var pc=dp(),_I=ne("util"),lc=ne("path"),EI=ne("http"),TI=ne("https"),bI=ne("url").parse,vI=ne("fs"),xI=ne("stream").Stream,RI=ne("crypto"),uc=yp(),AI=Lp(),wI=nf(),dr=Di(),dc=af();function of(e){return String(e).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22")}function oe(e){if(!(this instanceof oe))return new oe(e);this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],pc.call(this),e=e||{};for(var t in e)this[t]=e[t]}_I.inherits(oe,pc);oe.LINE_BREAK=`\r
4
+ `;oe.DEFAULT_CONTENT_TYPE="application/octet-stream";oe.prototype.append=function(e,t,r){r=r||{},typeof r=="string"&&(r={filename:r});var n=pc.prototype.append.bind(this);if((typeof t=="number"||t==null)&&(t=String(t)),Array.isArray(t)){this._error(new Error("Arrays are not supported."));return}var s=this._multiPartHeader(e,t,r),i=this._multiPartFooter();n(s),n(t),n(i),this._trackLength(s,t,r)};oe.prototype._trackLength=function(e,t,r){var n=0;r.knownLength!=null?n+=Number(r.knownLength):Buffer.isBuffer(t)?n=t.length:typeof t=="string"&&(n=Buffer.byteLength(t)),this._valueLength+=n,this._overheadLength+=Buffer.byteLength(e)+oe.LINE_BREAK.length,!(!t||!t.path&&!(t.readable&&dr(t,"httpVersion"))&&!(t instanceof xI))&&(r.knownLength||this._valuesToMeasure.push(t))};oe.prototype._lengthRetriever=function(e,t){dr(e,"fd")?e.end!=null&&e.end!=1/0&&e.start!=null?t(null,e.end+1-(e.start?e.start:0)):vI.stat(e.path,function(r,n){if(r){t(r);return}var s=n.size-(e.start?e.start:0);t(null,s)}):dr(e,"httpVersion")?t(null,Number(e.headers["content-length"])):dr(e,"httpModule")?(e.on("response",function(r){e.pause(),t(null,Number(r.headers["content-length"]))}),e.resume()):t("Unknown stream")};oe.prototype._multiPartHeader=function(e,t,r){if(typeof r.header=="string")return r.header;var n=this._getContentDisposition(t,r),s=this._getContentType(t,r),i="",a={"Content-Disposition":["form-data",'name="'+of(e)+'"'].concat(n||[]),"Content-Type":[].concat(s||[])};typeof r.header=="object"&&dc(a,r.header);var o;for(var c in a)if(dr(a,c)){if(o=a[c],o==null)continue;Array.isArray(o)||(o=[o]),o.length&&(i+=c+": "+o.join("; ")+oe.LINE_BREAK)}return"--"+this.getBoundary()+oe.LINE_BREAK+i+oe.LINE_BREAK};oe.prototype._getContentDisposition=function(e,t){var r;if(typeof t.filepath=="string"?r=lc.normalize(t.filepath).replace(/\\/g,"/"):t.filename||e&&(e.name||e.path)?r=lc.basename(t.filename||e&&(e.name||e.path)):e&&e.readable&&dr(e,"httpVersion")&&(r=lc.basename(e.client._httpMessage.path||"")),r)return'filename="'+of(r)+'"'};oe.prototype._getContentType=function(e,t){var r=t.contentType;return!r&&e&&e.name&&(r=uc.lookup(e.name)),!r&&e&&e.path&&(r=uc.lookup(e.path)),!r&&e&&e.readable&&dr(e,"httpVersion")&&(r=e.headers["content-type"]),!r&&(t.filepath||t.filename)&&(r=uc.lookup(t.filepath||t.filename)),!r&&e&&typeof e=="object"&&(r=oe.DEFAULT_CONTENT_TYPE),r};oe.prototype._multiPartFooter=function(){return function(e){var t=oe.LINE_BREAK,r=this._streams.length===0;r&&(t+=this._lastBoundary()),e(t)}.bind(this)};oe.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+oe.LINE_BREAK};oe.prototype.getHeaders=function(e){var t,r={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in e)dr(e,t)&&(r[t.toLowerCase()]=e[t]);return r};oe.prototype.setBoundary=function(e){if(typeof e!="string")throw new TypeError("FormData boundary must be a string");this._boundary=e};oe.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary};oe.prototype.getBuffer=function(){for(var e=new Buffer.alloc(0),t=this.getBoundary(),r=0,n=this._streams.length;r<n;r++)typeof this._streams[r]!="function"&&(Buffer.isBuffer(this._streams[r])?e=Buffer.concat([e,this._streams[r]]):e=Buffer.concat([e,Buffer.from(this._streams[r])]),(typeof this._streams[r]!="string"||this._streams[r].substring(2,t.length+2)!==t)&&(e=Buffer.concat([e,Buffer.from(oe.LINE_BREAK)])));return Buffer.concat([e,Buffer.from(this._lastBoundary())])};oe.prototype._generateBoundary=function(){this._boundary="--------------------------"+RI.randomBytes(12).toString("hex")};oe.prototype.getLengthSync=function(){var e=this._overheadLength+this._valueLength;return this._streams.length&&(e+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),e};oe.prototype.hasKnownLength=function(){var e=!0;return this._valuesToMeasure.length&&(e=!1),e};oe.prototype.getLength=function(e){var t=this._overheadLength+this._valueLength;if(this._streams.length&&(t+=this._lastBoundary().length),!this._valuesToMeasure.length){process.nextTick(e.bind(this,null,t));return}AI.parallel(this._valuesToMeasure,this._lengthRetriever,function(r,n){if(r){e(r);return}n.forEach(function(s){t+=s}),e(null,t)})};oe.prototype.submit=function(e,t){var r,n,s={method:"post"};return typeof e=="string"?(e=bI(e),n=dc({port:e.port,path:e.pathname,host:e.hostname,protocol:e.protocol},s)):(n=dc(e,s),n.port||(n.port=n.protocol==="https:"?443:80)),n.headers=this.getHeaders(e.headers),n.protocol==="https:"?r=TI.request(n):r=EI.request(n),this.getLength(function(i,a){if(i&&i!=="Unknown stream"){this._error(i);return}if(a&&r.setHeader("Content-Length",a),this.pipe(r),t){var o,c=function(u,l){return r.removeListener("error",c),r.removeListener("response",o),t.call(this,u,l)};o=c.bind(this,null),r.on("error",c),r.on("response",o)}}.bind(this)),r};oe.prototype._error=function(e){this.error||(this.error=e,this.pause(),this.emit("error",e))};oe.prototype.toString=function(){return"[object FormData]"};wI(oe.prototype,"FormData");cf.exports=oe});var df=P((sV,uf)=>{"use strict";p();var pn=1e3,mn=pn*60,fn=mn*60,Cr=fn*24,SI=Cr*7,II=Cr*365.25;uf.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return PI(e);if(r==="number"&&isFinite(e))return t.long?OI(e):DI(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function PI(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*II;case"weeks":case"week":case"w":return r*SI;case"days":case"day":case"d":return r*Cr;case"hours":case"hour":case"hrs":case"hr":case"h":return r*fn;case"minutes":case"minute":case"mins":case"min":case"m":return r*mn;case"seconds":case"second":case"secs":case"sec":case"s":return r*pn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function DI(e){var t=Math.abs(e);return t>=Cr?Math.round(e/Cr)+"d":t>=fn?Math.round(e/fn)+"h":t>=mn?Math.round(e/mn)+"m":t>=pn?Math.round(e/pn)+"s":e+"ms"}function OI(e){var t=Math.abs(e);return t>=Cr?Li(e,t,Cr,"day"):t>=fn?Li(e,t,fn,"hour"):t>=mn?Li(e,t,mn,"minute"):t>=pn?Li(e,t,pn,"second"):e+" ms"}function Li(e,t,r,n){var s=t>=r*1.5;return Math.round(e/r)+" "+n+(s?"s":"")}});var mc=P((aV,pf)=>{"use strict";p();function CI(e){r.debug=r,r.default=r,r.coerce=c,r.disable=a,r.enable=s,r.enabled=o,r.humanize=df(),r.destroy=u,Object.keys(e).forEach(l=>{r[l]=e[l]}),r.names=[],r.skips=[],r.formatters={};function t(l){let d=0;for(let m=0;m<l.length;m++)d=(d<<5)-d+l.charCodeAt(m),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=t;function r(l){let d,m=null,f,g;function _(...E){if(!_.enabled)return;let T=_,x=Number(new Date),R=x-(d||x);T.diff=R,T.prev=d,T.curr=x,d=x,E[0]=r.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let I=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(k,B)=>{if(k==="%%")return"%";I++;let Y=r.formatters[B];if(typeof Y=="function"){let re=E[I];k=Y.call(T,re),E.splice(I,1),I--}return k}),r.formatArgs.call(T,E),(T.log||r.log).apply(T,E)}return _.namespace=l,_.useColors=r.useColors(),_.color=r.selectColor(l),_.extend=n,_.destroy=r.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(f!==r.namespaces&&(f=r.namespaces,g=r.enabled(l)),g),set:E=>{m=E}}),typeof r.init=="function"&&r.init(_),_}function n(l,d){let m=r(this.namespace+(typeof d>"u"?":":d)+l);return m.log=this.log,m}function s(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let d=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of d)m[0]==="-"?r.skips.push(m.slice(1)):r.names.push(m)}function i(l,d){let m=0,f=0,g=-1,_=0;for(;m<l.length;)if(f<d.length&&(d[f]===l[m]||d[f]==="*"))d[f]==="*"?(g=f,_=m,f++):(m++,f++);else if(g!==-1)f=g+1,_++,m=_;else return!1;for(;f<d.length&&d[f]==="*";)f++;return f===d.length}function a(){let l=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),l}function o(l){for(let d of r.skips)if(i(l,d))return!1;for(let d of r.names)if(i(l,d))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}pf.exports=CI});var mf=P((nt,ki)=>{"use strict";p();nt.formatArgs=LI;nt.save=kI;nt.load=MI;nt.useColors=NI;nt.storage=UI();nt.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();nt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function NI(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function LI(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+ki.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),e.splice(n,0,t)}nt.log=console.debug||console.log||(()=>{});function kI(e){try{e?nt.storage.setItem("debug",e):nt.storage.removeItem("debug")}catch{}}function MI(){let e;try{e=nt.storage.getItem("debug")||nt.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function UI(){try{return localStorage}catch{}}ki.exports=mc()(nt);var{formatters:FI}=ki.exports;FI.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var gf=P((qe,Ui)=>{"use strict";p();var jI=ne("tty"),Mi=ne("util");qe.init=WI;qe.log=GI;qe.formatArgs=BI;qe.save=HI;qe.load=$I;qe.useColors=qI;qe.destroy=Mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");qe.colors=[6,2,3,4,5,1];try{let e=ne("supports-color");e&&(e.stderr||e).level>=2&&(qe.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}qe.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[t];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),e[r]=n,e},{});function qI(){return"colors"in qe.inspectOpts?!!qe.inspectOpts.colors:jI.isatty(process.stderr.fd)}function BI(e){let{namespace:t,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${t} \x1B[0m`;e[0]=i+e[0].split(`
5
+ `).join(`
6
+ `+i),e.push(s+"m+"+Ui.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=VI()+t+" "+e[0]}function VI(){return qe.inspectOpts.hideDate?"":new Date().toISOString()+" "}function GI(...e){return process.stderr.write(Mi.formatWithOptions(qe.inspectOpts,...e)+`
7
+ `)}function HI(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function $I(){return process.env.DEBUG}function WI(e){e.inspectOpts={};let t=Object.keys(qe.inspectOpts);for(let r=0;r<t.length;r++)e.inspectOpts[t[r]]=qe.inspectOpts[t[r]]}Ui.exports=mc()(qe);var{formatters:ff}=Ui.exports;ff.o=function(e){return this.inspectOpts.colors=this.useColors,Mi.inspect(e,this.inspectOpts).split(`
8
+ `).map(t=>t.trim()).join(" ")};ff.O=function(e){return this.inspectOpts.colors=this.useColors,Mi.inspect(e,this.inspectOpts)}});var gn=P((uV,fc)=>{"use strict";p();typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?fc.exports=mf():fc.exports=gf()});var hf=P(gc=>{"use strict";p();Object.defineProperty(gc,"__esModule",{value:!0});function JI(e){return function(t,r){return new Promise((n,s)=>{e.call(this,t,r,(i,a)=>{i?s(i):n(a)})})}}gc.default=JI});var Ef=P((yc,_f)=>{"use strict";p();var yf=yc&&yc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},KI=ne("events"),YI=yf(gn()),zI=yf(hf()),is=YI.default("agent-base");function XI(e){return!!e&&typeof e.addRequest=="function"}function hc(){let{stack:e}=new Error;return typeof e!="string"?!1:e.split(`
9
+ `).some(t=>t.indexOf("(https.js:")!==-1||t.indexOf("node:https:")!==-1)}function Fi(e,t){return new Fi.Agent(e,t)}(function(e){class t extends KI.EventEmitter{constructor(n,s){super();let i=s;typeof n=="function"?this.callback=n:n&&(i=n),this.timeout=null,i&&typeof i.timeout=="number"&&(this.timeout=i.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:hc()?443:80}set defaultPort(n){this.explicitDefaultPort=n}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:hc()?"https:":"http:"}set protocol(n){this.explicitProtocol=n}callback(n,s,i){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(n,s){let i=Object.assign({},s);typeof i.secureEndpoint!="boolean"&&(i.secureEndpoint=hc()),i.host==null&&(i.host="localhost"),i.port==null&&(i.port=i.secureEndpoint?443:80),i.protocol==null&&(i.protocol=i.secureEndpoint?"https:":"http:"),i.host&&i.path&&delete i.path,delete i.agent,delete i.hostname,delete i._defaultAgent,delete i.defaultPort,delete i.createConnection,n._last=!0,n.shouldKeepAlive=!1;let a=!1,o=null,c=i.timeout||this.timeout,u=f=>{n._hadError||(n.emit("error",f),n._hadError=!0)},l=()=>{o=null,a=!0;let f=new Error(`A "socket" was not created for HTTP request before ${c}ms`);f.code="ETIMEOUT",u(f)},d=f=>{a||(o!==null&&(clearTimeout(o),o=null),u(f))},m=f=>{if(a)return;if(o!=null&&(clearTimeout(o),o=null),XI(f)){is("Callback returned another Agent instance %o",f.constructor.name),f.addRequest(n,i);return}if(f){f.once("free",()=>{this.freeSocket(f,i)}),n.onSocket(f);return}let g=new Error(`no Duplex stream was returned to agent-base for \`${n.method} ${n.path}\``);u(g)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(is("Converting legacy callback function to promise"),this.promisifiedCallback=zI.default(this.callback)):this.promisifiedCallback=this.callback),typeof c=="number"&&c>0&&(o=setTimeout(l,c)),"port"in i&&typeof i.port!="number"&&(i.port=Number(i.port));try{is("Resolving socket for %o request: %o",i.protocol,`${n.method} ${n.path}`),Promise.resolve(this.promisifiedCallback(n,i)).then(m,d)}catch(f){Promise.reject(f).catch(d)}}freeSocket(n,s){is("Freeing socket %o %o",n.constructor.name,s),n.destroy()}destroy(){is("Destroying agent %o",this.constructor.name)}}e.Agent=t,e.prototype=e.Agent.prototype})(Fi||(Fi={}));_f.exports=Fi});var Tf=P(os=>{"use strict";p();var QI=os&&os.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(os,"__esModule",{value:!0});var ZI=QI(gn()),as=ZI.default("https-proxy-agent:parse-proxy-response");function eP(e){return new Promise((t,r)=>{let n=0,s=[];function i(){let d=e.read();d?l(d):e.once("readable",i)}function a(){e.removeListener("end",c),e.removeListener("error",u),e.removeListener("close",o),e.removeListener("readable",i)}function o(d){as("onclose had error %o",d)}function c(){as("onend")}function u(d){a(),as("onerror %o",d),r(d)}function l(d){s.push(d),n+=d.length;let m=Buffer.concat(s,n);if(m.indexOf(`\r
10
+ \r
11
+ `)===-1){as("have not received end of HTTP headers yet..."),i();return}let g=m.toString("ascii",0,m.indexOf(`\r
12
+ `)),_=+g.split(" ")[1];as("got proxy server response: %o",g),t({statusCode:_,buffered:m})}e.on("error",u),e.on("close",o),e.on("end",c),i()})}os.default=eP});var xf=P(Nr=>{"use strict";p();var tP=Nr&&Nr.__awaiter||function(e,t,r,n){function s(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(l){try{u(n.next(l))}catch(d){a(d)}}function c(l){try{u(n.throw(l))}catch(d){a(d)}}function u(l){l.done?i(l.value):s(l.value).then(o,c)}u((n=n.apply(e,t||[])).next())})},hn=Nr&&Nr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Nr,"__esModule",{value:!0});var bf=hn(ne("net")),vf=hn(ne("tls")),rP=hn(ne("url")),nP=hn(ne("assert")),sP=hn(gn()),iP=Ef(),aP=hn(Tf()),cs=sP.default("https-proxy-agent:agent"),_c=class extends iP.Agent{constructor(t){let r;if(typeof t=="string"?r=rP.default.parse(t):r=t,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");cs("creating new HttpsProxyAgent instance: %o",r),super(r);let n=Object.assign({},r);this.secureProxy=r.secureProxy||lP(n.protocol),n.host=n.hostname||n.host,typeof n.port=="string"&&(n.port=parseInt(n.port,10)),!n.port&&n.host&&(n.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in n)&&(n.ALPNProtocols=["http 1.1"]),n.host&&n.path&&(delete n.path,delete n.pathname),this.proxy=n}callback(t,r){return tP(this,void 0,void 0,function*(){let{proxy:n,secureProxy:s}=this,i;s?(cs("Creating `tls.Socket`: %o",n),i=vf.default.connect(n)):(cs("Creating `net.Socket`: %o",n),i=bf.default.connect(n));let a=Object.assign({},n.headers),c=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
13
+ `;n.auth&&(a["Proxy-Authorization"]=`Basic ${Buffer.from(n.auth).toString("base64")}`);let{host:u,port:l,secureEndpoint:d}=r;cP(l,d)||(u+=`:${l}`),a.Host=u,a.Connection="close";for(let E of Object.keys(a))c+=`${E}: ${a[E]}\r
14
+ `;let m=aP.default(i);i.write(`${c}\r
15
+ `);let{statusCode:f,buffered:g}=yield m;if(f===200){if(t.once("socket",oP),r.secureEndpoint){cs("Upgrading socket connection to TLS");let E=r.servername||r.host;return vf.default.connect(Object.assign(Object.assign({},uP(r,"host","hostname","path","port")),{socket:i,servername:E}))}return i}i.destroy();let _=new bf.default.Socket({writable:!1});return _.readable=!0,t.once("socket",E=>{cs("replaying proxy buffer for failed request"),nP.default(E.listenerCount("data")>0),E.push(g),E.push(null)}),_})}};Nr.default=_c;function oP(e){e.resume()}function cP(e,t){return!!(!t&&e===80||t&&e===443)}function lP(e){return typeof e=="string"?/^https:?$/i.test(e):!1}function uP(e,...t){let r={},n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}});var Af=P((bc,Rf)=>{"use strict";p();var dP=bc&&bc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Ec=dP(xf());function Tc(e){return new Ec.default(e)}(function(e){e.HttpsProxyAgent=Ec.default,e.prototype=Ec.default.prototype})(Tc||(Tc={}));Rf.exports=Tc});var Sf=P((TV,wf)=>{"use strict";p();var ls;wf.exports=function(){if(!ls){try{ls=gn()("follow-redirects")}catch{}typeof ls!="function"&&(ls=function(){})}ls.apply(null,arguments)}});var Cf=P((vV,Nc)=>{"use strict";p();var ds=ne("url"),us=ds.URL,pP=ne("http"),mP=ne("https"),wc=ne("stream").Writable,Sc=ne("assert"),If=Sf();(function(){var t=typeof process<"u",r=typeof window<"u"&&typeof document<"u",n=kr(Error.captureStackTrace);!t&&(r||!n)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var Ic=!1;try{Sc(new us(""))}catch(e){Ic=e.code==="ERR_INVALID_URL"}var fP=["Authorization","Proxy-Authorization","Cookie"],gP=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],Pc=["abort","aborted","connect","error","socket","timeout"],Dc=Object.create(null);Pc.forEach(function(e){Dc[e]=function(t,r,n){this._redirectable.emit(e,t,r,n)}});var xc=ps("ERR_INVALID_URL","Invalid URL",TypeError),Rc=ps("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),hP=ps("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",Rc),yP=ps("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),_P=ps("ERR_STREAM_WRITE_AFTER_END","write after end"),EP=wc.prototype.destroy||Df;function st(e,t){wc.call(this),this._sanitizeOptions(e),this._options=e,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var r=this;this._onNativeResponse=function(n){try{r._processResponse(n)}catch(s){r.emit("error",s instanceof Rc?s:new Rc({cause:s}))}},this._headerFilter=new RegExp("^(?:"+fP.concat(e.sensitiveHeaders).map(AP).join("|")+")$","i"),this._performRequest()}st.prototype=Object.create(wc.prototype);st.prototype.abort=function(){Cc(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};st.prototype.destroy=function(e){return Cc(this._currentRequest,e),EP.call(this,e),this};st.prototype.write=function(e,t,r){if(this._ending)throw new _P;if(!Lr(e)&&!xP(e))throw new TypeError("data should be a string, Buffer or Uint8Array");if(kr(t)&&(r=t,t=null),e.length===0){r&&r();return}this._requestBodyLength+e.length<=this._options.maxBodyLength?(this._requestBodyLength+=e.length,this._requestBodyBuffers.push({data:e,encoding:t}),this._currentRequest.write(e,t,r)):(this.emit("error",new yP),this.abort())};st.prototype.end=function(e,t,r){if(kr(e)?(r=e,e=t=null):kr(t)&&(r=t,t=null),!e)this._ended=this._ending=!0,this._currentRequest.end(null,null,r);else{var n=this,s=this._currentRequest;this.write(e,t,function(){n._ended=!0,s.end(null,null,r)}),this._ending=!0}};st.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)};st.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)};st.prototype.setTimeout=function(e,t){var r=this;function n(a){a.setTimeout(e),a.removeListener("timeout",a.destroy),a.addListener("timeout",a.destroy)}function s(a){r._timeout&&clearTimeout(r._timeout),r._timeout=setTimeout(function(){r.emit("timeout"),i()},e),n(a)}function i(){r._timeout&&(clearTimeout(r._timeout),r._timeout=null),r.removeListener("abort",i),r.removeListener("error",i),r.removeListener("response",i),r.removeListener("close",i),t&&r.removeListener("timeout",t),r.socket||r._currentRequest.removeListener("socket",s)}return t&&this.on("timeout",t),this.socket?s(this.socket):this._currentRequest.once("socket",s),this.on("socket",n),this.on("abort",i),this.on("error",i),this.on("response",i),this.on("close",i),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(e){st.prototype[e]=function(t,r){return this._currentRequest[e](t,r)}});["aborted","connection","socket"].forEach(function(e){Object.defineProperty(st.prototype,e,{get:function(){return this._currentRequest[e]}})});st.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),vP(e.sensitiveHeaders)||(e.sensitiveHeaders=[]),e.host&&(e.hostname||(e.hostname=e.host),delete e.host),!e.pathname&&e.path){var t=e.path.indexOf("?");t<0?e.pathname=e.path:(e.pathname=e.path.substring(0,t),e.search=e.path.substring(t))}};st.prototype._performRequest=function(){var e=this._options.protocol,t=this._options.nativeProtocols[e];if(!t)throw new TypeError("Unsupported protocol "+e);if(this._options.agents){var r=e.slice(0,-1);this._options.agent=this._options.agents[r]}var n=this._currentRequest=t.request(this._options,this._onNativeResponse);n._redirectable=this;for(var s of Pc)n.on(s,Dc[s]);if(this._currentUrl=/^\//.test(this._options.path)?ds.format(this._options):this._options.path,this._isRedirect){var i=0,a=this,o=this._requestBodyBuffers;(function c(u){if(n===a._currentRequest)if(u)a.emit("error",u);else if(i<o.length){var l=o[i++];n.finished||n.write(l.data,l.encoding,c)}else a._ended&&n.end()})()}};st.prototype._processResponse=function(e){var t=e.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t});var r=e.headers.location;if(!r||this._options.followRedirects===!1||t<300||t>=400){e.responseUrl=this._currentUrl,e.redirects=this._redirects,this.emit("response",e),this._requestBodyBuffers=[];return}if(Cc(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)throw new hP;var n,s=this._options.beforeRedirect;s&&(n=Object.assign({Host:e.req.getHeader("host")},this._options.headers));var i=this._options.method;((t===301||t===302)&&this._options.method==="POST"||t===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],vc(/^content-/i,this._options.headers));var a=vc(/^host$/i,this._options.headers),o=Oc(this._currentUrl),c=a||o.host,u=/^\w+:/.test(r)?this._currentUrl:ds.format(Object.assign(o,{host:c})),l=TP(r,u);if(If("redirecting to",l.href),this._isRedirect=!0,Ac(l,this._options),(l.protocol!==o.protocol&&l.protocol!=="https:"||l.host!==c&&!bP(l.host,c))&&vc(this._headerFilter,this._options.headers),kr(s)){var d={headers:e.headers,statusCode:t},m={url:u,method:i,headers:n};s(this._options,d,m),this._sanitizeOptions(this._options)}this._performRequest()};function Pf(e){var t={maxRedirects:21,maxBodyLength:10485760},r={};return Object.keys(e).forEach(function(n){var s=n+":",i=r[s]=e[n],a=t[n]=Object.create(i);function o(u,l,d){return RP(u)?u=Ac(u):Lr(u)?u=Ac(Oc(u)):(d=l,l=Of(u),u={protocol:s}),kr(l)&&(d=l,l=null),l=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},u,l),l.nativeProtocols=r,!Lr(l.host)&&!Lr(l.hostname)&&(l.hostname="::1"),Sc.equal(l.protocol,s,"protocol mismatch"),If("options",l),new st(l,d)}function c(u,l,d){var m=a.request(u,l,d);return m.end(),m}Object.defineProperties(a,{request:{value:o,configurable:!0,enumerable:!0,writable:!0},get:{value:c,configurable:!0,enumerable:!0,writable:!0}})}),t}function Df(){}function Oc(e){var t;if(Ic)t=new us(e);else if(t=Of(ds.parse(e)),!Lr(t.protocol))throw new xc({input:e});return t}function TP(e,t){return Ic?new us(e,t):Oc(ds.resolve(t,e))}function Of(e){if(/^\[/.test(e.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(e.hostname))throw new xc({input:e.href||e});if(/^\[/.test(e.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(e.host))throw new xc({input:e.href||e});return e}function Ac(e,t){var r=t||{};for(var n of gP)r[n]=e[n];return r.hostname.startsWith("[")&&(r.hostname=r.hostname.slice(1,-1)),r.port!==""&&(r.port=Number(r.port)),r.path=r.search?r.pathname+r.search:r.pathname,r}function vc(e,t){var r;for(var n in t)e.test(n)&&(r=t[n],delete t[n]);return r===null||typeof r>"u"?void 0:String(r).trim()}function ps(e,t,r){function n(s){kr(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,s||{}),this.code=e,this.message=this.cause?t+": "+this.cause.message:t}return n.prototype=new(r||Error),Object.defineProperties(n.prototype,{constructor:{value:n,enumerable:!1},name:{value:"Error ["+e+"]",enumerable:!1}}),n}function Cc(e,t){for(var r of Pc)e.removeListener(r,Dc[r]);e.on("error",Df),e.destroy(t)}function bP(e,t){Sc(Lr(e)&&Lr(t));var r=e.length-t.length-1;return r>0&&e[r]==="."&&e.endsWith(t)}function vP(e){return e instanceof Array}function Lr(e){return typeof e=="string"||e instanceof String}function kr(e){return typeof e=="function"}function xP(e){return typeof e=="object"&&"length"in e}function RP(e){return us&&e instanceof us}function AP(e){return e.replace(/[\]\\/()*+?.$]/g,"\\$&")}Nc.exports=Pf({http:pP,https:mP});Nc.exports.wrap=Pf});var Qe=P((RV,Jg)=>{"use strict";p();var lg=lf(),wP=ne("crypto"),SP=ne("url"),ug=Af(),dg=ne("http"),pg=ne("https"),mg=ne("http2"),el=ne("util"),Nf=ne("path"),IP=Cf(),xt=ne("zlib"),it=ne("stream"),PP=ne("events");function fg(e,t){return function(){return e.apply(t,arguments)}}var{toString:DP}=Object.prototype,{getPrototypeOf:En}=Object,{iterator:ys,toStringTag:gg}=Symbol,Hi=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),fs=(e,t)=>{let r=e,n=[];for(;r!=null&&r!==Object.prototype;){if(n.indexOf(r)!==-1)return!1;if(n.push(r),Hi(r,t))return!0;r=En(r)}return!1},OP=(e,t)=>e!=null&&fs(e,t)?e[t]:void 0,tl=(e=>t=>{let r=DP.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Rt=e=>(e=e.toLowerCase(),t=>tl(t)===e),zi=e=>t=>typeof t===e,{isArray:Fr}=Array,jr=zi("undefined");function bn(e){return e!==null&&!jr(e)&&e.constructor!==null&&!jr(e.constructor)&&at(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var hg=Rt("ArrayBuffer");function CP(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&hg(e.buffer),t}var NP=zi("string"),at=zi("function"),yg=zi("number"),vn=e=>e!==null&&typeof e=="object",LP=e=>e===!0||e===!1,Bi=e=>{if(!vn(e))return!1;let t=En(e);return(t===null||t===Object.prototype||En(t)===null)&&!fs(e,gg)&&!fs(e,ys)},kP=e=>{if(!vn(e)||bn(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},MP=Rt("Date"),UP=Rt("File"),FP=e=>!!(e&&typeof e.uri<"u"),jP=e=>e&&typeof e.getParts<"u",qP=Rt("Blob"),BP=Rt("FileList"),VP=Rt("Set"),GP=e=>vn(e)&&at(e.pipe);function HP(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var Lf=HP(),kf=typeof Lf.FormData<"u"?Lf.FormData:void 0,$P=e=>{if(!e)return!1;if(kf&&e instanceof kf)return!0;let t=En(e);if(!t||t===Object.prototype||!at(e.append))return!1;let r=tl(e);return r==="formdata"||r==="object"&&at(e.toString)&&e.toString()==="[object FormData]"},WP=Rt("URLSearchParams"),[JP,KP,YP,zP]=["ReadableStream","Request","Response","Headers"].map(Rt),XP=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function _s(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,s;if(typeof e!="object"&&(e=[e]),Fr(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{if(bn(e))return;let i=r?Object.getOwnPropertyNames(e):Object.keys(e),a=i.length,o;for(n=0;n<a;n++)o=i[n],t.call(null,e[o],o,e)}}function _g(e,t){if(bn(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,s;for(;n-- >0;)if(s=r[n],t===s.toLowerCase())return s;return null}var Mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Eg=e=>!jr(e)&&e!==Mr;function $c(...e){let{caseless:t,skipUndefined:r}=Eg(this)&&this||{},n={},s=(i,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;let o=t&&typeof a=="string"&&_g(n,a)||a,c=Hi(n,o)?n[o]:void 0;Bi(c)&&Bi(i)?n[o]=$c(c,i):Bi(i)?n[o]=$c({},i):Fr(i)?n[o]=i.slice():(!r||!jr(i))&&(n[o]=i)};for(let i=0,a=e.length;i<a;i++){let o=e[i];if(!o||bn(o)||(_s(o,s),typeof o!="object"||Fr(o)))continue;let c=Object.getOwnPropertySymbols(o);for(let u=0;u<c.length;u++){let l=c[u];lD.call(o,l)&&s(o[l],l)}}return n}var QP=(e,t,r,{allOwnKeys:n}={})=>(_s(t,(s,i)=>{r&&at(s)?Object.defineProperty(e,i,{__proto__:null,value:fg(s,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:s,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),ZP=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eD=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),r&&Object.assign(e.prototype,r)},tD=(e,t,r,n)=>{let s,i,a,o={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)a=s[i],(!n||n(a,e,t))&&!o[a]&&(t[a]=e[a],o[a]=!0);e=r!==!1&&En(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},nD=e=>{if(!e)return null;if(Fr(e))return e;let t=e.length;if(!yg(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},sD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&En(Uint8Array)),iD=(e,t)=>{let n=(e&&e[ys]).call(e),s;for(;(s=n.next())&&!s.done;){let i=s.value;t.call(e,i[0],i[1])}},aD=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},oD=Rt("HTMLFormElement"),cD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),{propertyIsEnumerable:lD}=Object.prototype,uD=Rt("RegExp"),Tg=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};_s(r,(s,i)=>{let a;(a=t(s,i,e))!==!1&&(n[i]=a||s)}),Object.defineProperties(e,n)},dD=e=>{Tg(e,(t,r)=>{if(at(e)&&["arguments","caller","callee"].includes(r))return!1;let n=e[r];if(at(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},pD=(e,t)=>{let r={},n=s=>{s.forEach(i=>{r[i]=!0})};return Fr(e)?n(e):n(String(e).split(t)),r},mD=()=>{},fD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function gD(e){return!!(e&&at(e.append)&&e[gg]==="FormData"&&e[ys])}var hD=e=>{let t=new WeakSet,r=n=>{if(vn(n)){if(t.has(n))return;if(bn(n))return n;if(!("toJSON"in n)){t.add(n);let s;if(VP(n)){s=[];for(let i of n){let a=r(i);!jr(a)&&s.push(a)}}else s=Fr(n)?[]:{},_s(n,(i,a)=>{let o=r(i);!jr(o)&&(s[a]=o)});return t.delete(n),s}}return n};return r(e)},yD=Rt("AsyncFunction"),_D=e=>e&&(vn(e)||at(e))&&at(e.then)&&at(e.catch),bg=((e,t)=>e?setImmediate:t?((r,n)=>(Mr.addEventListener("message",({source:s,data:i})=>{s===Mr&&i===r&&n.length&&n.shift()()},!1),s=>{n.push(s),Mr.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",at(Mr.postMessage)),ED=typeof queueMicrotask<"u"?queueMicrotask.bind(Mr):typeof process<"u"&&process.nextTick||bg,vg=e=>e!=null&&at(e[ys]),TD=e=>e!=null&&fs(e,ys)&&vg(e),h={isArray:Fr,isArrayBuffer:hg,isBuffer:bn,isFormData:$P,isArrayBufferView:CP,isString:NP,isNumber:yg,isBoolean:LP,isObject:vn,isPlainObject:Bi,isEmptyObject:kP,isReadableStream:JP,isRequest:KP,isResponse:YP,isHeaders:zP,isUndefined:jr,isDate:MP,isFile:UP,isReactNativeBlob:FP,isReactNative:jP,isBlob:qP,isRegExp:uD,isFunction:at,isStream:GP,isURLSearchParams:WP,isTypedArray:sD,isFileList:BP,forEach:_s,merge:$c,extend:QP,trim:XP,stripBOM:ZP,inherits:eD,toFlatObject:tD,kindOf:tl,kindOfTest:Rt,endsWith:rD,toArray:nD,forEachEntry:iD,matchAll:aD,isHTMLForm:oD,hasOwnProperty:Hi,hasOwnProp:Hi,hasOwnInPrototypeChain:fs,getSafeProp:OP,reduceDescriptors:Tg,freezeMethods:dD,toObjectSet:pD,toCamelCase:cD,noop:mD,toFiniteNumber:fD,findKey:_g,global:Mr,isContextDefined:Eg,isSpecCompliantForm:gD,toJSONObject:hD,isAsyncFn:yD,isThenable:_D,setImmediate:bg,asap:ED,isIterable:vg,isSafeIterable:TD},bD=h.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),vD=e=>{let t={},r,n,s;return e&&e.split(`
16
+ `).forEach(function(a){s=a.indexOf(":"),r=a.substring(0,s).trim().toLowerCase(),n=a.substring(s+1).trim();let o=h.hasOwnProp(t,r);!r||o&&h.hasOwnProp(bD,r)||(r==="set-cookie"?o?t[r].push(n):t[r]=[n]:t[r]=o?t[r]+", "+n:n)}),t};function xD(e){let t=0,r=e.length;for(;t<r;){let n=e.charCodeAt(t);if(n!==9&&n!==32)break;t+=1}for(;r>t;){let n=e.charCodeAt(r-1);if(n!==9&&n!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}var RD=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),AD=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function rl(e,t){return h.isArray(e)?e.map(r=>rl(r,t)):xD(String(e).replace(t,""))}var wD=e=>rl(e,RD),SD=e=>rl(e,AD);function nl(e){let t=Object.create(null);return h.forEach(e.toJSON(),(r,n)=>{t[n]=SD(r)}),t}var Mf=Symbol("internals");function ms(e){return e&&String(e).trim().toLowerCase()}function Vi(e){return e===!1||e==null?e:h.isArray(e)?e.map(Vi):wD(String(e))}function ID(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var PD=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Lc(e){let t=0,r=e.length;for(;t<r;){let n=e.charCodeAt(t);if(n!==9&&n!==32)break;t+=1}for(;r>t;){let n=e.charCodeAt(r-1);if(n!==9&&n!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}function DD(e){let t=e.length-1;if(t<1||e.charCodeAt(0)!==34||e.charCodeAt(t)!==34)return e;let r="";for(let n=1;n<t;n++){let s=e.charCodeAt(n);if(s===34||s===92&&(n+=1,n>=t))return e;r+=e[n]}return r}function OD(e){let t=Object.create(null),r=String(e),n=0,s=!1,i=!1;function a(o){let c=Lc(r.slice(n,o)),u=c.indexOf("=");if(u<1)return;let l=Lc(c.slice(0,u));if(!PD.test(l))return;let d=l.toLowerCase();if(d==="__proto__"||d==="constructor"||d==="prototype")return;let m=Lc(c.slice(u+1));t[d]=DD(m)}for(let o=0;o<r.length;o++){let c=r.charCodeAt(o);s?i?i=!1:c===92?i=!0:c===34&&(s=!1):c===34?s=!0:(c===44||c===59)&&(a(o),n=o+1)}return a(r.length),t}var CD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function kc(e,t,r,n,s){if(h.isFunction(n))return n.call(this,t,r);if(s&&(t=r),!!h.isString(t)){if(h.isString(n))return t.indexOf(n)!==-1;if(h.isRegExp(n))return n.test(t)}}function ND(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function LD(e,t){let r=h.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{__proto__:null,value:function(s,i,a){return this[n].call(this,t,s,i,a)},configurable:!0})})}var Ie=class{constructor(t){t&&this.set(t)}set(t,r,n){let s=this;function i(o,c,u){let l=ms(c);if(!l)return;let d=h.findKey(s,l);(!d||s[d]===void 0||u===!0||u===void 0&&s[d]!==!1)&&(s[d||c]=Vi(o))}let a=(o,c)=>h.forEach(o,(u,l)=>i(u,l,c));if(h.isPlainObject(t)||t instanceof this.constructor)a(t,r);else if(h.isString(t)&&(t=t.trim())&&!CD(t))a(vD(t),r);else if(h.isObject(t)&&h.isSafeIterable(t)){let o=Object.create(null),c,u;for(let l of t){if(!h.isArray(l))throw new TypeError("Object iterator must return a key-value pair");u=l[0],h.hasOwnProp(o,u)?(c=o[u],o[u]=h.isArray(c)?[...c,l[1]]:[c,l[1]]):o[u]=l[1]}a(o,r)}else t!=null&&i(r,t,n);return this}get(t,r){if(t=ms(t),t){let n=h.findKey(this,t);if(n){let s=this[n];if(!r)return s;if(r===!0)return ID(s);if(h.isFunction(r))return r.call(this,s,n);if(h.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=ms(t),t){let n=h.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||kc(this,this[n],n,r)))}return!1}delete(t,r){let n=this,s=!1;function i(a){if(a=ms(a),a){let o=h.findKey(n,a);o&&(!r||kc(n,n[o],o,r))&&(delete n[o],s=!0)}}return h.isArray(t)?t.forEach(i):i(t),s}clear(t){let r=Object.keys(this),n=r.length,s=!1;for(;n--;){let i=r[n];(!t||kc(this,this[i],i,t,!0))&&(delete this[i],s=!0)}return s}normalize(t){let r=this,n={};return h.forEach(this,(s,i)=>{let a=h.findKey(n,i);if(a){r[a]=Vi(s),delete r[i];return}let o=t?ND(i):String(i).trim();o!==i&&delete r[i],r[o]=Vi(s),n[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return h.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=t&&h.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
17
+ `)}getSetCookie(){let t=this.get("set-cookie");return h.isArray(t)?t:t==null||t===!1?[]:[t]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static parseParameters(t){return OD(t)}static concat(t,...r){let n=new this(t);return r.forEach(s=>n.set(s)),n}static accessor(t){let n=(this[Mf]=this[Mf]={accessors:{}}).accessors,s=this.prototype;function i(a){let o=ms(a);n[o]||(LD(s,a),n[o]=!0)}return h.isArray(t)?t.forEach(i):i(t),this}};Ie.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);h.reduceDescriptors(Ie.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});h.freezeMethods(Ie);var $i="[REDACTED ****]";function kD(e){if(h.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(h.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function MD(e,t){let r=new Set(t.map(i=>String(i).toLowerCase())),n=[],s=i=>{if(i===null||typeof i!="object"||h.isBuffer(i))return i;if(n.indexOf(i)!==-1)return;i instanceof Ie&&(i=i.toJSON()),n.push(i);let a;if(h.isArray(i))a=[],i.forEach((o,c)=>{let u=s(o);h.isUndefined(u)||(a[c]=u)});else{if(!h.isPlainObject(i)&&kD(i))return n.pop(),i;a=Object.create(null);for(let[o,c]of Object.entries(i)){let u=r.has(o.toLowerCase())?$i:s(c);h.isUndefined(u)||(a[o]=u)}}return n.pop(),a};return s(e)}function Uf(e){try{return String(e)}catch{return""}}function UD(e){return e.errors.map(r=>{try{return r&&r.message?Uf(r.message):Uf(r)}catch{return""}}).filter(Boolean).join("; ")||e.name||"AggregateError"}var A=class e extends Error{static from(t,r,n,s,i,a){let o=t.message;!o&&h.isArray(t.errors)&&t.errors.length&&(o=UD(t));let c=new e(o,r||t.code,n,s,i);return Object.defineProperty(c,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),c.name=t.name,t.status!=null&&c.status==null&&(c.status=t.status),a&&Object.assign(c,a),c}constructor(t,r,n,s,i){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),n&&(this.config=n),s&&(this.request=s),i&&(this.response=i,this.status=i.status)}toJSON(){let t=this.config,r=t&&h.hasOwnProp(t,"redact")?t.redact:void 0,n=h.isArray(r)&&r.length>0?MD(t,r):h.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:n,code:this.code,status:this.status}}};A.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";A.ERR_BAD_OPTION="ERR_BAD_OPTION";A.ECONNABORTED="ECONNABORTED";A.ETIMEDOUT="ETIMEDOUT";A.ECONNREFUSED="ECONNREFUSED";A.ERR_NETWORK="ERR_NETWORK";A.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";A.ERR_DEPRECATED="ERR_DEPRECATED";A.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";A.ERR_BAD_REQUEST="ERR_BAD_REQUEST";A.ERR_CANCELED="ERR_CANCELED";A.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";A.ERR_INVALID_URL="ERR_INVALID_URL";A.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var Mc={isBufferAvailable(){return typeof Buffer<"u"},from(e){return Buffer.from(e)}},xg=100;function Wc(e){return h.isPlainObject(e)||h.isArray(e)}function Rg(e){return h.endsWith(e,"[]")?e.slice(0,-2):e}function Uc(e,t,r){return e?e.concat(t).map(function(s,i){return s=Rg(s),!r&&i?"["+s+"]":s}).join(r?".":""):t}function FD(e){return h.isArray(e)&&!e.some(Wc)}var jD=h.toFlatObject(h,{},null,function(t){return/^is[A-Z]/.test(t)});function Xi(e,t,r){if(!h.isObject(e))throw new TypeError("target must be an object");t=t||new(lg||FormData),r=h.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,R){return!h.isUndefined(R[x])});let n=r.metaTokens,s=r.visitor||g,i=r.dots,a=r.indexes,o=r.Blob||typeof Blob<"u"&&Blob,c=r.maxDepth===void 0?xg:r.maxDepth,u=o&&h.isSpecCompliantForm(t),l=[];if(!h.isFunction(s))throw new TypeError("visitor must be a function");function d(T){if(T===null)return"";if(h.isDate(T))return T.toISOString();if(h.isBoolean(T))return T.toString();if(!u&&h.isBlob(T))throw new A("Blob is not supported. Use a Buffer instead.");if(h.isArrayBuffer(T)||h.isTypedArray(T)){if(u&&typeof o=="function")return new o([T]);if(Mc&&Mc.isBufferAvailable())return Mc.from(T);throw new A("Blob is not supported. Use a Buffer instead.",A.ERR_NOT_SUPPORT)}return T}function m(T){if(T>c)throw new A("Object is too deeply nested ("+T+" levels). Max depth: "+c,A.ERR_FORM_DATA_DEPTH_EXCEEDED)}function f(T,x){if(c===1/0)return JSON.stringify(T);let R=[];return JSON.stringify(T,function(N,k){if(!h.isObject(k))return k;for(;R.length&&R[R.length-1]!==this;)R.pop();return R.push(k),m(x+R.length-1),k})}function g(T,x,R){let I=T;if(h.isReactNative(t)&&h.isReactNativeBlob(T))return t.append(Uc(R,x,i),d(T)),!1;if(T&&!R&&typeof T=="object"){if(h.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=f(T,1);else if(h.isArray(T)&&FD(T)||(h.isFileList(T)||h.endsWith(x,"[]"))&&(I=h.toArray(T)))return x=Rg(x),I.forEach(function(k,B){!(h.isUndefined(k)||k===null)&&t.append(a===!0?Uc([x],B,i):a===null?x:x+"[]",d(k))}),!1}return Wc(T)?!0:(t.append(Uc(R,x,i),d(T)),!1)}let _=Object.assign(jD,{defaultVisitor:g,convertValue:d,isVisitable:Wc});function E(T,x,R=0){if(!h.isUndefined(T)){if(m(R),l.indexOf(T)!==-1)throw new Error("Circular reference detected in "+x.join("."));l.push(T),h.forEach(T,function(N,k){(!(h.isUndefined(N)||N===null)&&s.call(t,N,h.isString(k)?k.trim():k,x,_))===!0&&E(N,x?x.concat(k):[k],R+1)}),l.pop()}}if(!h.isObject(e))throw new TypeError("data must be an object");return E(e),t}function Ff(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(n){return t[n]})}function Ag(e,t){this._pairs=[],e&&Xi(e,this,t)}var wg=Ag.prototype;wg.append=function(t,r){this._pairs.push([t,r])};wg.toString=function(t){let r=t?n=>t.call(this,n,Ff):Ff;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};function qD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function sl(e,t,r){if(!t)return e;e=e||"";let n=h.isFunction(r)?{serialize:r}:r,s=h.getSafeProp(n,"encode")||qD,i=h.getSafeProp(n,"serialize"),a;if(i?a=i(t,n):a=h.isURLSearchParams(t)?t.toString():new Ag(t,n).toString(s),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Wi=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){h.forEach(this.handlers,function(n){n!==null&&t(n)})}},Qi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},BD=SP.URLSearchParams,Fc="abcdefghijklmnopqrstuvwxyz",jf="0123456789",Sg={DIGIT:jf,ALPHA:Fc,ALPHA_DIGIT:Fc+Fc.toUpperCase()+jf},VD=(e=16,t=Sg.ALPHA_DIGIT)=>{let r="",{length:n}=t,s=new Uint32Array(e);wP.randomFillSync(s);for(let i=0;i<e;i++)r+=t[s[i]%n];return r},GD={isNode:!0,classes:{URLSearchParams:BD,FormData:lg,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Sg,generateString:VD,protocols:["http","https","file","data"]},il=typeof window<"u"&&typeof document<"u",Jc=typeof navigator=="object"&&navigator||void 0,HD=il&&(!Jc||["ReactNative","NativeScript","NS"].indexOf(Jc.product)<0),$D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",WD=il&&window.location.href||"http://localhost",JD=Object.freeze({__proto__:null,hasBrowserEnv:il,hasStandardBrowserEnv:HD,hasStandardBrowserWebWorkerEnv:$D,navigator:Jc,origin:WD}),ve={...JD,...GD};function KD(e,t){return Xi(e,new ve.classes.URLSearchParams,{visitor:function(r,n,s,i){return ve.isNode&&h.isBuffer(r)?(this.append(n,r.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}var qf=xg;function Ig(e){if(e>qf)throw new A("FormData field is too deeply nested ("+e+" levels). Max depth: "+qf,A.ERR_FORM_DATA_DEPTH_EXCEEDED)}function YD(e){let t=[],r=/[^.[\]]+|\[([^.[\]]*)]/g,n;for(;(n=r.exec(e))!==null;)Ig(t.length),t.push(n[0]==="[]"?"":n[1]||n[0]);return t}function zD(e){let t={},r=Object.keys(e),n,s=r.length,i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}function Pg(e){function t(r,n,s,i){Ig(i);let a=r[i++];if(a==="__proto__")return!0;let o=Number.isFinite(+a),c=i>=r.length;return a=!a&&h.isArray(s)?s.length:a,c?(h.hasOwnProp(s,a)?s[a]=h.isArray(s[a])?s[a].concat(n):[s[a],n]:s[a]=n,!o):((!h.hasOwnProp(s,a)||!h.isObject(s[a]))&&(s[a]=[]),t(r,n,s[a],i)&&h.isArray(s[a])&&(s[a]=zD(s[a])),!o)}if(h.isFormData(e)&&h.isFunction(e.entries)){let r={};return h.forEachEntry(e,(n,s)=>{t(YD(n),s,r,0)}),r}return null}var yn=(e,t)=>e!=null&&h.hasOwnProp(e,t)?e[t]:void 0;function XD(e,t,r){if(h.isString(e))try{return(t||JSON.parse)(e),h.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var Es={transitional:Qi,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",s=n.indexOf("application/json")>-1,i=h.isObject(t);if(i&&h.isHTMLForm(t)&&(t=new FormData(t)),h.isFormData(t))return s?JSON.stringify(Pg(t)):t;if(h.isArrayBuffer(t)||h.isBuffer(t)||h.isStream(t)||h.isFile(t)||h.isBlob(t)||h.isReadableStream(t))return t;if(h.isArrayBufferView(t))return t.buffer;if(h.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(i){let c=yn(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return KD(t,c).toString();if((o=h.isFileList(t))||n.indexOf("multipart/form-data")>-1){let u=yn(this,"env"),l=u&&u.FormData;return Xi(o?{"files[]":t}:t,l&&new l,c)}}return i||s?(r.setContentType("application/json",!1),XD(t)):t}],transformResponse:[function(t){let r=yn(this,"transitional")||Es.transitional,n=r&&r.forcedJSONParsing,s=yn(this,"responseType"),i=s==="json";if(h.isResponse(t)||h.isReadableStream(t))return t;if(t&&h.isString(t)&&(n&&!s||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,yn(this,"parseReviver"))}catch(c){if(o)throw c.name==="SyntaxError"?A.from(c,A.ERR_BAD_RESPONSE,this,null,yn(this,"response")):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ve.classes.FormData,Blob:ve.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};h.forEach(["delete","get","head","post","put","patch","query"],e=>{Es.headers[e]={}});function jc(e,t){let r=this||Es,n=t||r,s=Ie.from(n.headers),i=n.data;return h.forEach(e,function(o){i=o.call(r,i,s.normalize(),t?t.status:void 0)}),s.normalize(),i}function Dg(e){return!!(e&&e.__CANCEL__)}var er=class extends A{constructor(t,r,n){super(t??"canceled",A.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function _n(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new A("Request failed with status code "+r.status,r.status>=400&&r.status<500?A.ERR_BAD_REQUEST:A.ERR_BAD_RESPONSE,r.config,r.request,r))}function QD(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ZD(e,t){if(!t)return e;let r=e.length;for(;r>0&&e.charCodeAt(r-1)===47;)r--;return e.slice(0,r)+"/"+t.replace(/^\/+/,"")}var eO=/^https?:(?!\/\/)/i,tO=/[\t\n\r]/g;function rO(e){let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t)}function nO(e){return rO(e).replace(tO,"")}function sO(e){return e&&e.replace(/(^|&)([^=&]*=)?[^&]+/g,(t,r,n="")=>`${r}${n}${$i}`)}function iO(e){let t=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${$i}@`),r=t.indexOf("#"),s=(r===-1?t:t.slice(0,r)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${$i}`);return r===-1?s:`${s}#${sO(t.slice(r+1))}`}function Bf(e,t){if(typeof e=="string"){let r=nO(e);if(eO.test(r))throw new A(`Invalid URL ${JSON.stringify(iO(r))}: missing "//" after protocol`,A.ERR_INVALID_URL,t)}}function al(e,t,r,n){Bf(t,n);let s=!QD(t);return e&&(s||r===!1)?(Bf(e,n),ZD(e,t)):t}var aO={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function oO(e){try{return new URL(e)}catch{return null}}function cO(e){var t=(typeof e=="string"?oO(e):e)||{},r=t.protocol,n=t.host,s=t.port;if(typeof n!="string"||!n||typeof r!="string"||(r=r.split(":",1)[0],n=n.replace(/:\d*$/,""),s=parseInt(s)||aO[r]||0,!lO(n,s)))return"";var i=Kc(r+"_proxy")||Kc("all_proxy");return i&&i.indexOf("://")===-1&&(i=r+"://"+i),i}function lO(e,t){var r=Kc("no_proxy").toLowerCase();return r?r==="*"?!1:r.split(/[,\s]/).every(function(n){if(!n)return!0;var s=n.match(/^(.+):(\d+)$/),i=s?s[1]:n,a=s?parseInt(s[2]):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.charAt(0)==="*"&&(i=i.slice(1)),!e.endsWith(i)):e!==i}):!0}function Kc(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||""}var gs="1.19.0";function Og(e){let t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}var uO=/^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;function dO(e,t,r){let n=r&&r.Blob||ve.classes.Blob,s=Og(e);if(t===void 0&&n&&(t=!0),s==="data"){e=s.length?e.slice(s.length+1):e;let i=uO.exec(e);if(!i)throw new A("Invalid URL",A.ERR_INVALID_URL);let a=i[1],o=i[2],c=i[3]?"base64":"utf8",u=i[4],l="";a?l=o?a+o:a:o&&(l="text/plain"+o);let d=c==="base64"?Buffer.from(u,"base64"):Buffer.from(decodeURIComponent(u),c);if(t){if(!n)throw new A("Blob is not supported",A.ERR_NOT_SUPPORT);return new n([d],{type:l})}return d}throw new A("Unsupported protocol "+s,A.ERR_NOT_SUPPORT)}var pO=["content-type","content-length"];function Cg(e,t,r){if(r!=="content-only"){e.set(t);return}Object.entries(t||{}).forEach(([n,s])=>{pO.includes(n.toLowerCase())&&e.set(n,s)})}var qc=Symbol("internals"),Ji=class extends it.Transform{constructor(t){t=h.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,s)=>!h.isUndefined(s[n])),super({readableHighWaterMark:t.chunkSize});let r=this[qc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",n=>{n==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[qc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let s=this[qc],i=s.maxRate,a=this.readableHighWaterMark,o=s.timeWindow,c=1e3/o,u=i/c,l=s.minChunkSize!==!1?Math.max(s.minChunkSize,u*.01):0,d=(f,g)=>{let _=Buffer.byteLength(f);s.bytesSeen+=_,s.bytes+=_,s.isCaptured&&this.emit("progress",s.bytesSeen),this.push(f)?process.nextTick(g):s.onReadCallback=()=>{s.onReadCallback=null,process.nextTick(g)}},m=(f,g)=>{let _=Buffer.byteLength(f),E=null,T=a,x,R=0;if(i){let I=Date.now();(!s.ts||(R=I-s.ts)>=o)&&(s.ts=I,x=u-s.bytes,s.bytes=x<0?-x:0,R=0),x=u-s.bytes}if(i){if(x<=0)return setTimeout(()=>{g(null,f)},o-R);x<T&&(T=x)}T&&_>T&&_-T>l&&(E=f.subarray(T),f=f.subarray(0,T)),d(f,E?()=>{process.nextTick(g,null,E)}:g)};m(t,function f(g,_){if(g)return n(g);_?m(_,f):n(null)})}},{asyncIterator:Vf}=Symbol,Ng=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Vf]?yield*e[Vf]():yield e},mO=ve.ALPHABET.ALPHA_DIGIT+"-_",hs=typeof TextEncoder=="function"?new TextEncoder:new el.TextEncoder,Ur=`\r
18
+ `,fO=hs.encode(Ur),gO=2,Yc=class{constructor(t,r){let{escapeName:n}=this.constructor,s=h.isString(r),i=`Content-Disposition: form-data; name="${n(t)}"${!s&&r.name?`; filename="${n(r.name)}"`:""}${Ur}`;if(s)r=hs.encode(String(r).replace(/\r?\n|\r\n?/g,Ur));else{let a=String(r.type||"application/octet-stream").replace(/[\r\n]/g,"");i+=`Content-Type: ${a}${Ur}`}this.headers=hs.encode(i+Ur),this.contentLength=s?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+gO,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;h.isTypedArray(t)?yield t:yield*Ng(t),yield fO}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},hO=(e,t,r)=>{let{tag:n="form-data-boundary",size:s=25,boundary:i=n+"-"+ve.generateString(s,mO)}=r||{};if(!h.isFormData(e))throw new TypeError("FormData instance required");if(i.length<1||i.length>70)throw new Error("boundary must be 1-70 characters long");let a=hs.encode("--"+i+Ur),o=hs.encode("--"+i+"--"+Ur),c=o.byteLength,u=Array.from(e.entries()).map(([d,m])=>{let f=new Yc(d,m);return c+=f.size,f});c+=a.byteLength*u.length,c=h.toFiniteNumber(c);let l={"Content-Type":`multipart/form-data; boundary=${i}`};return Number.isFinite(c)&&(l["Content-Length"]=c),t&&t(l),it.Readable.from((async function*(){for(let d of u)yield a,yield*d.encode();yield o})())},zc=class extends it.Transform{__transform(t,r,n){this.push(t),n()}_transform(t,r,n){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let s=Buffer.alloc(2);s[0]=120,s[1]=156,this.push(s,r)}this.__transform(t,r,n)}},Xc=class{constructor(){this.sessions=Object.create(null)}getSession(t,r){r=Object.assign({sessionTimeout:1e3},r);let n=this.sessions[t];if(n){let d=n.length;for(let m=0;m<d;m++){let[f,g]=n[m];if(!f.destroyed&&!f.closed&&el.isDeepStrictEqual(g,r))return f}}let s=mg.connect(t,r),i,a,o=()=>{if(i)return;i=!0,a&&(clearTimeout(a),a=null);let d=n,m=d.length,f=m;for(;f--;)if(d[f][0]===s){m===1?delete this.sessions[t]:d.splice(f,1),s.closed||s.close();return}},c=s.request,{sessionTimeout:u}=r;if(u!=null){let d=0;s.request=function(){let m=c.apply(this,arguments);return d++,a&&(clearTimeout(a),a=null),m.once("close",()=>{--d||(a=setTimeout(()=>{a=null,o()},u))}),m}}s.once("close",o);let l=[s,r];return n?n.push(l):n=this.sessions[t]=[l],s}},yO=(e,t)=>h.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(s=>{try{t?n(null,...t(s)):n(null,s)}catch(i){n(i)}},n)}:e,_O=new Set(["localhost","0.0.0.0"]),Lg=e=>{let t=e.split(".");return t.length!==4||t[0]!=="127"?!1:t.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)},Bc=e=>{if(/^0[xX][0-9a-fA-F]+$/.test(e)){let t=parseInt(e.slice(2),16);return Number.isFinite(t)?t:null}if(e.length>1&&/^0[0-7]+$/.test(e)){let t=parseInt(e,8);return Number.isFinite(t)?t:null}if(e.length>1&&/^0[0-9]+$/.test(e))return null;if(/^[0-9]+$/.test(e)){let t=parseInt(e,10);return Number.isFinite(t)?t:null}return null},EO=e=>{if(typeof e!="string"||!e||e.indexOf(":")!==-1)return e;let t=e;if(t.charAt(0)==="["&&t.charAt(t.length-1)==="]"&&(t=t.slice(1,-1)),t=t.replace(/\.+$/,""),!/^[0-9.xXa-fA-F]+$/.test(t))return e;let r=t.split(".");if(r.some(l=>l===""))return e;if(r.length===4){let l=r.map(Bc);return l.some(d=>d===null||d<0||d>255)?e:l.join(".")}if(r.length>4||r.length===1)return e;let n=r.slice(0,-1),s=r[r.length-1],i=4-n.length,a=Bc(s);if(a===null)return e;let o=(1<<8*i)-1;if(a<0||a>o)return e;let c=new Array(i).fill(0);for(let l=i-1,d=a;l>=0;l--,d>>=8)c[l]=d&255;let u=n.map(Bc);return u.some(l=>l===null||l<0||l>255)?e:[...u,...c].join(".")},Vc=e=>/^0{1,4}$/.test(e),TO=e=>{if(e==="::")return!0;let t=e.indexOf("::");if(t!==-1){if(t!==e.lastIndexOf("::"))return!1;let n=e.slice(0,t),s=e.slice(t+2),i=n?n.split(":"):[],a=s?s.split(":"):[];return i.length+a.length<8&&i.every(Vc)&&a.every(Vc)}let r=e.split(":");return r.length===8&&r.every(Vc)},bO=e=>{if(e==="::1")return!0;let t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return Lg(t[1]);let r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){let s=parseInt(r[1],16);return s>=32512&&s<=32767}let n=e.split(":");if(n.length===8){for(let s=0;s<7;s++)if(!/^0+$/.test(n[s]))return!1;return/^0*1$/.test(n[7])}return!1},Gf=e=>e?_O.has(e)||Lg(e)||TO(e)?!0:bO(e):!1,vO={http:80,https:443,ws:80,wss:443,ftp:21},xO=e=>{let t=e,r=0;if(t.charAt(0)==="["){let i=t.indexOf("]");if(i!==-1){let a=t.slice(1,i),o=t.slice(i+1);return o.charAt(0)===":"&&/^\d+$/.test(o.slice(1))&&(r=Number.parseInt(o.slice(1),10)),[a,r]}}let n=t.indexOf(":"),s=t.lastIndexOf(":");return n!==-1&&n===s&&/^\d+$/.test(t.slice(s+1))&&(r=Number.parseInt(t.slice(s+1),10),t=t.slice(0,s)),[t,r]},RO=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,AO=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,wO=e=>{if(typeof e!="string"||e.indexOf(":")===-1)return e;let t=e.match(RO);if(t)return t[1];let r=e.match(AO);if(r){let n=parseInt(r[1],16),s=parseInt(r[2],16);return`${n>>8}.${n&255}.${s>>8}.${s&255}`}return e},Hf=e=>{if(!e)return e;e.charAt(0)==="["&&e.charAt(e.length-1)==="]"&&(e=e.slice(1,-1));let t=e.replace(/\.+$/,""),r=EO(t);return r!==t?r:wO(t)};function SO(e){let t;try{t=new URL(e)}catch{return!1}let r=(process.env.no_proxy||process.env.NO_PROXY||"").toLowerCase();if(!r)return!1;if(r==="*")return!0;let n=Number.parseInt(t.port,10)||vO[t.protocol.split(":",1)[0]]||0,s=Hf(t.hostname.toLowerCase());return r.split(/[\s,]+/).some(i=>{if(!i)return!1;if(i==="*")return!0;let[a,o]=xO(i);return a=Hf(a),!a||o&&o!==n?!1:(a.charAt(0)==="*"&&(a=a.slice(1)),a.charAt(0)==="."?s.endsWith(a):s===a||Gf(s)&&Gf(a))})}function IO(e,t){e=e||10;let r=new Array(e),n=new Array(e),s=0,i=0,a;return t=t!==void 0?t:1e3,function(c){let u=Date.now(),l=n[i];a||(a=u),r[s]=c,n[s]=u;let d=i,m=0;for(;d!==s;)m+=r[d++],d=d%e;if(s=(s+1)%e,s===i&&(i=(i+1)%e),u-a<t)return;let f=l&&u-l;return f?Math.round(m*1e3/f):void 0}}function PO(e,t){let r=0,n=1e3/t,s,i,a=(u,l=Date.now())=>{r=l,s=null,i&&(clearTimeout(i),i=null),e(...u)};return[(...u)=>{let l=Date.now(),d=l-r;d>=n?a(u,l):(s=u,i||(i=setTimeout(()=>{i=null,a(s)},n-d)))},()=>s&&a(s)]}var Tn=(e,t,r=3)=>{let n=0,s=IO(50,250);return PO(i=>{if(!i||typeof i.loaded!="number")return;let a=i.loaded,o=i.lengthComputable?i.total:void 0,c=Math.max(0,o!=null?Math.min(a,o):a),u=Math.max(0,c-n),l=s(u);n=Math.max(n,c);let d={loaded:c,total:o,progress:o?c/o:void 0,bytes:u,rate:l||void 0,estimated:l&&o?(o-c)/l:void 0,event:i,lengthComputable:o!=null,[t?"download":"upload"]:!0};e(d)},r)},Ki=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Yi=(e,t=h.asap)=>(...r)=>t(()=>e(...r)),$f=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,kg=(e,t,r)=>t+2<r&&$f(e.charCodeAt(t+1))&&$f(e.charCodeAt(t+2)),Wf=e=>e<=57?e-48:(e&223)-55,DO=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===45||e===95,OO=e=>e===9||e===10||e===12||e===13||e===32,CO=e=>{let t=Math.floor(e/4),r=e%4;return t*3+(r===2?1:r===3?2:0)},Mg=e=>{let t=e.length,r=0;return t>0&&e.charCodeAt(t-1)===61&&(r++,t>1&&e.charCodeAt(t-2)===61&&r++),Math.floor((t-r)*3/4)},NO=e=>{let t=e.length,r=0,n=0,s=!1;for(let i=0;i<t;i++){let a=e.charCodeAt(i);if(a===37&&kg(e,i,t)&&(a=Wf(e.charCodeAt(i+1))*16+Wf(e.charCodeAt(i+2)),i+=2),!OO(a)){if(a===61){n++;continue}if(!DO(a)||n>0){s=!0;continue}r++}}return s||n>2||n>0&&(r+n)%4!==0||r%4===1?Mg(e):CO(r)},Ug=(e,t)=>{if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let r=e.indexOf(",");if(r<0)return 0;let n=e.slice(5,r),s=e.slice(r+1);if(/;base64/i.test(n))return t(s);let a=0;for(let o=0,c=s.length;o<c;o++){let u=s.charCodeAt(o);if(u===37&&kg(s,o,c))a+=1,o+=2;else if(u<128)a+=1;else if(u<2048)a+=2;else if(u>=55296&&u<=56319&&o+1<c){let l=s.charCodeAt(o+1);l>=56320&&l<=57343?(a+=4,o++):a+=3}else a+=3}return a};function LO(e){let t=typeof e=="string"?e.indexOf("#"):-1;return Ug(t===-1?e:e.slice(0,t),NO)}function kO(e){return Ug(e,Mg)}var Jf={flush:xt.constants.Z_SYNC_FLUSH,finishFlush:xt.constants.Z_SYNC_FLUSH},MO={flush:xt.constants.BROTLI_OPERATION_FLUSH,finishFlush:xt.constants.BROTLI_OPERATION_FLUSH},UO={flush:xt.constants.ZSTD_e_flush,finishFlush:xt.constants.ZSTD_e_flush},Fg=h.isFunction(xt.createBrotliDecompress),jg=h.isFunction(xt.createZstdDecompress),qg="gzip, compress, deflate"+(Fg?", br":""),FO=qg+(jg?", zstd":""),Kf=typeof process<"u"&&process.nextTick?process.nextTick.bind(process):h.asap,{http:jO,https:qO}=IP,ol=/https:?/,Yf=Symbol("axios.http.socketListener"),ji=Symbol("axios.http.currentReq"),Bg=Symbol("axios.http.installedTunnel"),BO=new Map,zf=new WeakMap,Xf={22:21,24:5};function VO(e=process.versions&&process.versions.node){if(!e)return!1;let[t,r]=e.split(".").map(n=>Number(n));return!Number.isInteger(t)||!Number.isInteger(r)?!1:t>24?!0:Xf[t]!=null&&r>=Xf[t]}function GO(e,t=process.versions&&process.versions.node){if(!VO(t))return!1;let r=e&&e.options;return!!(r&&h.hasOwnProp(r,"proxyEnv")&&r.proxyEnv!=null)}function HO(e,t,r){return ol.test(e.protocol)?r||pg.globalAgent:t||dg.globalAgent}function $O(e,t){let r=e.protocol+"//"+e.hostname+":"+(e.port||"")+"#"+(e.auth||""),n=t?zf.get(t)||zf.set(t,new Map).get(t):BO,s=n.get(r);if(s)return s;let i=t&&t.options?{...t.options,...e}:e;if(s=new ug(i),t&&t.options){let a={...t.options},o=s.callback;s.callback=function(u,l){return o.call(this,u,{...a,...l})}}return s[Bg]=!0,n.set(r,s),s}var Qf=ve.protocols.map(e=>e+":"),Zf=e=>{if(!h.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},eg=(e,[t,r])=>(e.on("end",r).on("error",r),t),WO=new Xc;function JO(e,t,r){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.auth&&e.beforeRedirects.auth(e),e.beforeRedirects.sensitiveHeaders&&e.beforeRedirects.sensitiveHeaders(e,r),e.beforeRedirects.config&&e.beforeRedirects.config(e,t,r)}function KO(e,t){e&&Object.keys(e).forEach(r=>{t.has(r.toLowerCase())&&delete e[r]})}function YO(e,t){if(!t)return!1;try{return new URL(t.url).origin===new URL(e.href).origin}catch{return!1}}function Vg(e,t,r,n,s,i){let a=t,o=HO(e,i,s);if(!a&&a!==!1&&!GO(o)){let c=cO(r);c&&(SO(r)||(a=new URL(c)))}if(n&&e.headers)for(let c of Object.keys(e.headers))c.toLowerCase()==="proxy-authorization"&&delete e.headers[c];if(n&&e.agent&&e.agent[Bg]&&(e.agent=void 0),a){let c=a instanceof URL,u=g=>c||h.hasOwnProp(a,g)?a[g]:void 0,l=u("username"),d=u("password"),m=h.hasOwnProp(a,"auth")?a.auth:void 0;if(l&&(m=(l||"")+":"+(d||"")),m){let g=typeof m=="object",_=g&&h.hasOwnProp(m,"username")?m.username:void 0,E=g&&h.hasOwnProp(m,"password")?m.password:void 0;if(!!(_||E))m=(_||"")+":"+(E||"");else if(g)throw new A("Invalid proxy authorization",A.ERR_BAD_OPTION,{proxy:a})}if(ol.test(e.protocol)){if(!(s instanceof ug)){let g=u("hostname")||u("host"),_=u("port"),E=u("protocol"),T=E?E.includes(":")?E:`${E}:`:"http:",x=g&&g.includes(":")&&!g.startsWith("[")?`[${g}]`:g,R=new URL(`${T}//${x}${_?":"+_:""}`),I={protocol:R.protocol,hostname:R.hostname.replace(/^\[|\]$/g,""),port:R.port,auth:m&&typeof m=="string"?m:void 0};R.protocol==="https:"&&(I.ALPNProtocols=["http/1.1"]);let N=$O(I,s);e.agent=N,e.agents&&(e.agents.https=N)}}else{if(m){let T=Buffer.from(m,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+T}let g=!1;for(let T of Object.keys(e.headers))if(T.toLowerCase()==="host"){g=!0;break}g||(e.headers.host=e.hostname+(e.port?":"+e.port:""));let _=u("hostname")||u("host");e.hostname=_,e.host=_,e.port=u("port"),e.path=r;let E=u("protocol");E&&(e.protocol=E.includes(":")?E:`${E}:`)}}e.beforeRedirects.proxy=function(u){Vg(u,t,u.href,!0,s,i)}}var zO=typeof process<"u"&&h.kindOf(process)==="process",XO=e=>new Promise((t,r)=>{let n,s,i=(c,u)=>{s||(s=!0,n&&n(c,u))},a=c=>{i(c),t(c)},o=c=>{i(c,!0),r(c)};e(a,o,c=>n=c).catch(o)}),QO=({address:e,family:t})=>{if(!h.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},tg=(e,t)=>QO(h.isObject(e)?e:{address:e,family:t}),ZO={request(e,t){let r=e.protocol+"//"+e.hostname+":"+(e.port||(e.protocol==="https:"?443:80)),{http2Options:n,headers:s}=e,i=WO.getSession(r,n),{HTTP2_HEADER_SCHEME:a,HTTP2_HEADER_METHOD:o,HTTP2_HEADER_PATH:c,HTTP2_HEADER_STATUS:u}=mg.constants,l={[a]:e.protocol.replace(":",""),[o]:e.method,[c]:e.path};h.forEach(s,(m,f)=>{f.charAt(0)!==":"&&(l[f]=m)});let d=i.request(l);return d.once("response",m=>{let f=d;m=Object.assign({},m);let g=m[u];delete m[u],f.headers=m,f.statusCode=+g,t(f)}),d}},eC=zO&&function(t){return XO(async function(n,s,i){let a=M=>h.getSafeProp(t,M),o=a("transitional")||Qi,c=a("data"),u=a("lookup"),l=a("family"),d=a("httpVersion");d===void 0&&(d=1);let m=a("http2Options"),f=a("httpAgent"),g=a("httpsAgent"),_=a("proxy"),E=a("responseType"),T=a("responseEncoding"),x=a("socketPath"),R=a("method").toUpperCase(),I=a("maxRedirects"),N=a("maxBodyLength"),k=a("maxContentLength"),B=a("decompress"),Y,re=!1,q,Z;if(d=+d,Number.isNaN(d))throw TypeError(`Invalid protocol version: '${t.httpVersion}' is not a number`);if(d!==1&&d!==2)throw TypeError(`Unsupported protocol version '${d}'`);let Ve=d===2;if(u){let M=yO(u,L=>h.isArray(L)?L:[L]);u=(L,se,Te)=>{M(L,se,(X,Ue,Je)=>{if(X)return Te(X);let Se=h.isArray(Ue)?Ue.map(en=>tg(en)):[tg(Ue,Je)];se.all?Te(X,Se):Te(X,Se[0].address,Se[0].family)})}}let We=new PP.EventEmitter;function ue(M){try{We.emit("abort",!M||M.type?new er(null,t,q):M)}catch{}}function Ge(){Z&&(clearTimeout(Z),Z=null)}function vr(){let M=a("timeout"),L=M?"timeout of "+M+"ms exceeded":"timeout exceeded",se=a("timeoutErrorMessage");return se&&(L=se),new A(L,o.clarifyTimeoutError?A.ETIMEDOUT:A.ECONNABORTED,t,q)}We.once("abort",s);let xr=()=>{Ge(),t.cancelToken&&t.cancelToken.unsubscribe(ue),t.signal&&t.signal.removeEventListener("abort",ue),We.removeAllListeners()};(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(ue),t.signal&&(t.signal.aborted?ue():t.signal.addEventListener("abort",ue))),i((M,L)=>{if(Y=!0,Ge(),L){re=!0,xr();return}let{data:se}=M;if(se instanceof it.Readable||se instanceof it.Duplex){let Te=it.finished(se,()=>{Te(),xr()})}else xr()});let Ys=al(a("baseURL"),a("url"),a("allowAbsoluteUrls"),t),zs=x?"http://localhost":ve.hasBrowserEnv?ve.origin:void 0,ye=new URL(Ys,zs),Ee=ye.protocol||Qf[0];if(Ee==="data:"){if(k>-1){let L=String(a("url")||Ys||"");if(kO(L)>k)return s(new A("maxContentLength size of "+k+" exceeded",A.ERR_BAD_RESPONSE,t))}let M;if(R!=="GET")return _n(n,s,{status:405,statusText:"method not allowed",headers:{},config:t});try{M=dO(a("url"),E==="blob",{Blob:t.env&&t.env.Blob})}catch(L){throw A.from(L,A.ERR_BAD_REQUEST,t)}return E==="text"?(M=M.toString(T),(!T||T==="utf8")&&(M=h.stripBOM(M))):E==="stream"&&(M=it.Readable.from(M)),_n(n,s,{data:M,status:200,statusText:"OK",headers:new Ie,config:t})}if(Qf.indexOf(Ee)===-1)return s(new A("Unsupported protocol "+Ee,A.ERR_BAD_REQUEST,t));let we=Ie.from(t.headers).normalize();we.set("User-Agent","axios/"+gs,!1);let{onUploadProgress:Ut,onDownloadProgress:Kt}=t,Rr=t.maxRate,ce,He;if(h.isSpecCompliantForm(c)){let M=we.getContentType(/boundary=([-_\w\d]{10,70})/i);c=hO(c,L=>{we.set(L)},{tag:`axios-${gs}-boundary`,boundary:M&&M[1]||void 0})}else if(h.isFormData(c)&&h.isFunction(c.getHeaders)&&c.getHeaders!==Object.prototype.getHeaders){if(Cg(we,c.getHeaders(),a("formDataHeaderPolicy")),!we.hasContentLength())try{let M=await el.promisify(c.getLength).call(c);Number.isFinite(M)&&M>=0&&we.setContentLength(M)}catch{}}else if(h.isBlob(c)||h.isFile(c))c.size&&we.setContentType(c.type||"application/octet-stream"),we.setContentLength(c.size||0),c=it.Readable.from(Ng(c));else if(c&&!h.isStream(c)){if(!Buffer.isBuffer(c))if(h.isArrayBuffer(c))c=Buffer.from(new Uint8Array(c));else if(h.isString(c))c=Buffer.from(c,"utf-8");else return s(new A("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",A.ERR_BAD_REQUEST,t));if(we.setContentLength(c.length,!1),N>-1&&c.length>N)return s(new A("Request body larger than maxBodyLength limit",A.ERR_BAD_REQUEST,t))}let Qr=h.toFiniteNumber(we.getContentLength());h.isArray(Rr)?(ce=Rr[0],He=Rr[1]):ce=He=Rr,c&&(Ut||ce)&&(h.isStream(c)||(c=it.Readable.from(c,{objectMode:!1})),c=it.pipeline([c,new Ji({maxRate:h.toFiniteNumber(ce)})],h.noop),Ut&&c.on("progress",eg(c,Ki(Qr,Tn(Yi(Ut,Kf),!1,3)))));let Ft,$n=a("auth");if($n){let M=h.getSafeProp($n,"username")||"",L=h.getSafeProp($n,"password")||"";Ft=M+":"+L}if(!Ft&&(ye.username||ye.password)){let M=Zf(ye.username),L=Zf(ye.password);Ft=M+":"+L}Ft&&we.delete("authorization");let Wn;try{Wn=sl(ye.pathname+ye.search,a("params"),a("paramsSerializer")).replace(/^\?/,"")}catch(M){return s(A.from(M,A.ERR_BAD_REQUEST,t,null,null,{url:a("url"),exists:!0}))}we.set("Accept-Encoding",h.hasOwnProp(o,"advertiseZstdAcceptEncoding")&&o.advertiseZstdAcceptEncoding===!0?FO:qg,!1);let de=Object.assign(Object.create(null),{path:Wn,method:R,headers:nl(we),agents:{http:f,https:g},auth:Ft,protocol:Ee,family:l,beforeRedirect:JO,beforeRedirects:Object.create(null),http2Options:m});if(!h.isUndefined(u)&&(de.lookup=u),x){if(typeof x!="string")return s(new A("socketPath must be a string",A.ERR_BAD_OPTION_VALUE,t));let M=a("allowedSocketPaths");if(M!=null){let L=Array.isArray(M)?M:[M],se=Nf.resolve(x);if(!L.some(X=>typeof X=="string"&&Nf.resolve(X)===se))return s(new A(`socketPath "${x}" is not permitted by allowedSocketPaths`,A.ERR_BAD_OPTION_VALUE,t))}de.socketPath=x}else de.hostname=ye.hostname.startsWith("[")?ye.hostname.slice(1,-1):ye.hostname,de.port=ye.port,Vg(de,_,Ee+"//"+ye.hostname+(ye.port?":"+ye.port:"")+de.path,!1,g,f);let ar,Zr=!1,Et=!1,W=ol.test(de.protocol);if(de.agent==null&&(de.agent=W?g:f),Ve)ar=ZO;else{let M=a("transport");if(M)ar=M;else if(I===0)ar=W?pg:dg,Zr=!0;else{Et=!0,de.sensitiveHeaders=[],I&&(de.maxRedirects=I);let L=a("beforeRedirect");if(L&&(de.beforeRedirects.config=L),Ft){let Te=ye.origin,X=Ft;de.beforeRedirects.auth=function(Je){try{new URL(Je.href).origin===Te&&(Je.auth=X)}catch{}}}let se=a("sensitiveHeaders");if(se!=null){if(!h.isArray(se))return s(new A("sensitiveHeaders must be an array of strings",A.ERR_BAD_OPTION_VALUE,t));let Te=new Set;for(let X of se){if(!h.isString(X))return s(new A("sensitiveHeaders must be an array of strings",A.ERR_BAD_OPTION_VALUE,t));Te.add(X.toLowerCase())}Te.size&&(de.sensitiveHeaders=Array.from(Te),de.beforeRedirects.sensitiveHeaders=function(Ue,Je){YO(Ue,Je)||KO(Ue.headers,Te)})}ar=W?qO:jO}}N>-1?de.maxBodyLength=N:de.maxBodyLength=1/0,de.insecureHTTPParser=!!a("insecureHTTPParser"),q=ar.request(de,function(L){if(Ge(),q.destroyed)return;let se=[L],Te=h.toFiniteNumber(L.headers["content-length"]);if(Kt||He){let Se=new Ji({maxRate:h.toFiniteNumber(He)});Kt&&Se.on("progress",eg(Se,Ki(Te,Tn(Yi(Kt,Kf),!0,3)))),se.push(Se)}let X=L,Ue=L.req||q;if(B!==!1&&L.headers["content-encoding"])switch((R==="HEAD"||L.statusCode===204)&&delete L.headers["content-encoding"],(L.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":se.push(xt.createUnzip(Jf)),delete L.headers["content-encoding"];break;case"deflate":se.push(new zc),se.push(xt.createUnzip(Jf)),delete L.headers["content-encoding"];break;case"br":Fg&&(se.push(xt.createBrotliDecompress(MO)),delete L.headers["content-encoding"]);break;case"zstd":jg&&(se.push(xt.createZstdDecompress(UO)),delete L.headers["content-encoding"]);break}X=se.length>1?it.pipeline(se,h.noop):se[0];let Je={status:L.statusCode,statusText:L.statusMessage,headers:new Ie(L.headers),config:t,request:Ue};if(E==="stream"){if(k>-1){let Se=k,en=X;async function*Jn(){let Fe=0;for await(let Zu of en){if(Fe+=Zu.length,Fe>Se)throw new A("maxContentLength size of "+Se+" exceeded",A.ERR_BAD_RESPONSE,t,Ue);yield Zu}}X=it.Readable.from(Jn(),{objectMode:!1})}Je.data=X,_n(n,s,Je)}else{let Se=[],en=0;X.on("data",function(Fe){Se.push(Fe),en+=Fe.length,k>-1&&en>k&&(re=!0,X.destroy(),ue(new A("maxContentLength size of "+k+" exceeded",A.ERR_BAD_RESPONSE,t,Ue)))}),X.on("aborted",function(){if(re)return;let Fe=new A("stream has been aborted",A.ERR_BAD_RESPONSE,t,Ue,Je);X.destroy(Fe),s(Fe)}),X.on("error",function(Fe){re||s(A.from(Fe,null,t,Ue,Je))}),X.on("end",function(){try{let Fe=Se.length===1?Se[0]:Buffer.concat(Se);E!=="arraybuffer"&&(Fe=Fe.toString(T),(!T||T==="utf8")&&(Fe=h.stripBOM(Fe))),Je.data=Fe}catch(Fe){return s(A.from(Fe,null,t,Je.request,Je))}_n(n,s,Je)})}We.once("abort",Se=>{X.destroyed||(X.emit("error",Se),X.destroy())})}),We.once("abort",M=>{q.close?q.close():q.destroy(M)}),q.on("error",function(L){s(A.from(L,null,t,q))});let $e=new Set;if(q.on("socket",function(L){typeof L.setKeepAlive=="function"&&L.setKeepAlive(!0,1e3*60),L[Yf]||(L.on("error",function(Te){let X=L[ji];X&&!X.destroyed&&X.destroy(Te)}),L[Yf]=!0),L[ji]=q,$e.add(L)}),q.once("close",function(){Ge();for(let L of $e)L[ji]===q&&(L[ji]=null);$e.clear()}),a("timeout")){let M=parseInt(a("timeout"),10);if(Number.isNaN(M)){ue(new A("error trying to parse `config.timeout` to int",A.ERR_BAD_OPTION_VALUE,t,q));return}let L=function(){Y||ue(vr())};Zr&&M>0&&(Z=setTimeout(L,M)),q.setTimeout(M,L)}else q.setTimeout(0);if(h.isStream(c)){let M=!1,L=!1;c.on("end",()=>{M=!0}),c.once("error",Te=>{L=!0,q.destroy(Te)}),c.on("close",()=>{!M&&!L&&ue(new er("Request stream has been aborted",t,q))});let se=c;if(N>-1&&!Et){let Te=N,X=0;se=it.pipeline([c,new it.Transform({transform(Ue,Je,Se){if(X+=Ue.length,X>Te)return Se(new A("Request body larger than maxBodyLength limit",A.ERR_BAD_REQUEST,t,q));Se(null,Ue)}})],h.noop),se.on("error",Ue=>{q.destroyed||q.destroy(Ue)})}se.pipe(q)}else c&&q.write(c),q.end()})},tC=ve.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ve.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ve.origin),ve.navigator&&/(msie|trident)/i.test(ve.navigator.userAgent)):()=>!0,rC=ve.hasStandardBrowserEnv?{write(e,t,r,n,s,i,a){if(typeof document>"u")return;let o=[`${e}=${encodeURIComponent(t)}`];h.isNumber(r)&&o.push(`expires=${new Date(r).toUTCString()}`),h.isString(n)&&o.push(`path=${n}`),h.isString(s)&&o.push(`domain=${s}`),i===!0&&o.push("secure"),h.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let r=0;r<t.length;r++){let n=t[r].replace(/^\s+/,""),s=n.indexOf("=");if(s!==-1&&n.slice(0,s)===e)try{return decodeURIComponent(n.slice(s+1))}catch{return n.slice(s+1)}}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}},rg=e=>e instanceof Ie?{...e}:e,nC=e=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(e).concat(Object.getOwnPropertySymbols(e).filter(t=>Object.getOwnPropertyDescriptor(e,t).enumerable)):Object.keys(e);function qr(e,t){e=e||{},t=t||{};let r=Object.create(null);Object.defineProperty(r,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function n(l,d,m,f){return h.isPlainObject(l)&&h.isPlainObject(d)?h.merge.call({caseless:f},l,d):h.isPlainObject(d)?h.merge({},d):h.isArray(d)?d.slice():d}function s(l,d,m,f){if(h.isUndefined(d)){if(!h.isUndefined(l))return n(void 0,l,m,f)}else return n(l,d,m,f)}function i(l,d){if(!h.isUndefined(d))return n(void 0,d)}function a(l,d){if(h.isUndefined(d)){if(!h.isUndefined(l))return n(void 0,l)}else return n(void 0,d)}function o(l){let d=h.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!h.isUndefined(d))if(h.isPlainObject(d)){if(h.hasOwnProp(d,l))return d[l]}else return;let m=h.hasOwnProp(e,"transitional")?e.transitional:void 0;if(h.isPlainObject(m)&&h.hasOwnProp(m,l))return m[l]}function c(l,d,m){if(h.hasOwnProp(t,m))return n(l,d);if(h.hasOwnProp(e,m))return n(void 0,l)}let u={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,allowedSocketPaths:a,responseEncoding:a,validateStatus:c,headers:(l,d,m)=>s(rg(l),rg(d),m,!0)};return h.forEach(nC({...e,...t}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;let m=h.hasOwnProp(u,d)?u[d]:s,f=h.hasOwnProp(e,d)?e[d]:void 0,g=h.hasOwnProp(t,d)?t[d]:void 0,_=m(f,g,d);h.isUndefined(_)&&m!==c||(r[d]=_)}),h.hasOwnProp(t,"validateStatus")&&h.isUndefined(t.validateStatus)&&o("validateStatusUndefinedResolves")===!1&&(h.hasOwnProp(e,"validateStatus")?r.validateStatus=n(void 0,e.validateStatus):delete r.validateStatus),r}var sC=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,r)=>String.fromCharCode(parseInt(r,16)));function Gg(e){let t=qr({},e),r=m=>h.hasOwnProp(t,m)?t[m]:void 0,n=r("data"),s=r("withXSRFToken"),i=r("xsrfHeaderName"),a=r("xsrfCookieName"),o=r("headers"),c=r("auth"),u=r("baseURL"),l=r("allowAbsoluteUrls"),d=r("url");if(t.headers=o=Ie.from(o),t.url=sl(al(u,d,l,t),r("params"),r("paramsSerializer")),c){let m=h.getSafeProp(c,"username")||"",f=h.getSafeProp(c,"password")||"";try{o.set("Authorization","Basic "+btoa(m+":"+(f?sC(f):"")))}catch(g){throw A.from(g,A.ERR_BAD_OPTION_VALUE,e)}}if(h.isFormData(n)&&(ve.hasStandardBrowserEnv||ve.hasStandardBrowserWebWorkerEnv||h.isReactNative(n)?o.setContentType(void 0):h.isFunction(n.getHeaders)&&Cg(o,n.getHeaders(),r("formDataHeaderPolicy"))),ve.hasStandardBrowserEnv&&(h.isFunction(s)&&(s=s(t)),s===!0||s==null&&tC(t.url))){let f=i&&a&&rC.read(a);f&&o.set(i,f)}return t}var iC=typeof XMLHttpRequest<"u",aC=iC&&function(e){return new Promise(function(r,n){let s=Gg(e),i=s.data,a=Ie.from(s.headers).normalize(),{responseType:o,onUploadProgress:c,onDownloadProgress:u}=s,l,d,m,f,g;function _(){f&&f(),g&&g(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let E=new XMLHttpRequest;E.open(s.method.toUpperCase(),s.url,!0),E.timeout=s.timeout;function T(){if(!E)return;let R=Ie.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),N={data:!o||o==="text"||o==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:R,config:e,request:E};_n(function(B){r(B),_()},function(B){n(B),_()},N),E=null}"onloadend"in E?E.onloadend=T:E.onreadystatechange=function(){!E||E.readyState!==4||E.status===0&&!(E.responseURL&&E.responseURL.startsWith("file:"))||setTimeout(T)},E.onabort=function(){E&&(n(new A("Request aborted",A.ECONNABORTED,e,E)),_(),E=null)},E.onerror=function(I){let N=I&&I.message?I.message:"Network Error",k=new A(N,A.ERR_NETWORK,e,E);k.event=I||null,n(k),_(),E=null},E.ontimeout=function(){let I=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded",N=s.transitional||Qi;s.timeoutErrorMessage&&(I=s.timeoutErrorMessage),n(new A(I,N.clarifyTimeoutError?A.ETIMEDOUT:A.ECONNABORTED,e,E)),_(),E=null},i===void 0&&a.setContentType(null),"setRequestHeader"in E&&h.forEach(nl(a),function(I,N){E.setRequestHeader(N,I)}),h.isUndefined(s.withCredentials)||(E.withCredentials=!!s.withCredentials),o&&o!=="json"&&(E.responseType=s.responseType),u&&([m,g]=Tn(u,!0),E.addEventListener("progress",m)),c&&E.upload&&([d,f]=Tn(c),E.upload.addEventListener("progress",d),E.upload.addEventListener("loadend",f)),(s.cancelToken||s.signal)&&(l=R=>{E&&(n(!R||R.type?new er(null,e,E):R),E.abort(),_(),E=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));let x=Og(s.url);if(x&&!ve.protocols.includes(x)){n(new A("Unsupported protocol "+x+":",A.ERR_BAD_REQUEST,e)),_();return}E.send(i||null)})},oC=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;let r=new AbortController,n=!1,s=function(c){if(!n){n=!0,a();let u=c instanceof Error?c:this.reason;r.abort(u instanceof A?u:new er(u instanceof Error?u.message:u))}},i=t&&setTimeout(()=>{i=null,s(new A(`timeout of ${t}ms exceeded`,A.ETIMEDOUT))},t),a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>{if(!n){if(c.aborted){s.call(c);return}c.addEventListener("abort",s,{once:!0})}});let{signal:o}=r;return o.unsubscribe=()=>h.asap(a),o},cC=function*(e,t){let r=e.byteLength;if(r<t){yield e;return}let n=0,s;for(;n<r;)s=n+t,yield e.slice(n,s),n=s},lC=async function*(e,t){for await(let r of uC(e))yield*cC(r,t)},uC=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},ng=(e,t,r,n)=>{let s=lC(e,t),i=0,a,o=c=>{a||(a=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:u,value:l}=await s.next();if(u){o(),c.close();return}let d=l.byteLength;if(r){let m=i+=d;r(m)}c.enqueue(new Uint8Array(l))}catch(u){throw o(u),u}},cancel(c){return o(c),s.return()}},{highWaterMark:2})},sg=64*1024,{isFunction:qi}=h,dC=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,r)=>String.fromCharCode(parseInt(r,16))),ig=e=>{if(!h.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},ag=(e,...t)=>{try{return!!e(...t)}catch{return!1}},pC=e=>{let t=e.indexOf("://"),r=e;return t!==-1&&(r=r.slice(t+3)),r.includes("@")||r.includes(":")},mC=e=>{let t=h.global!==void 0&&h.global!==null?h.global:globalThis,{ReadableStream:r,TextEncoder:n}=t;e=h.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);let{fetch:s,Request:i,Response:a}=e,o=s?qi(s):typeof fetch=="function",c=qi(i),u=qi(a);if(!o)return!1;let l=o&&qi(r),d=o&&(typeof n=="function"?(T=>x=>T.encode(x))(new n):async T=>new Uint8Array(await new i(T).arrayBuffer())),m=c&&l&&ag(()=>{let T=!1,x=new i(ve.origin,{body:new r,method:"POST",get duplex(){return T=!0,"half"}}),R=x.headers.has("Content-Type");return x.body!=null&&x.body.cancel(),T&&!R}),f=u&&l&&ag(()=>h.isReadableStream(new a("").body)),g={stream:f&&(T=>T.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(T=>{!g[T]&&(g[T]=(x,R)=>{let I=x&&x[T];if(I)return I.call(x);throw new A(`Response type '${T}' is not supported`,A.ERR_NOT_SUPPORT,R)})});let _=async T=>{if(T==null)return 0;if(h.isBlob(T))return T.size;if(h.isSpecCompliantForm(T))return(await new i(ve.origin,{method:"POST",body:T}).arrayBuffer()).byteLength;if(h.isArrayBufferView(T)||h.isArrayBuffer(T))return T.byteLength;if(h.isURLSearchParams(T)&&(T=T+""),h.isString(T))return(await d(T)).byteLength},E=async(T,x)=>{let R=h.toFiniteNumber(T.getContentLength());return R??_(x)};return async T=>{let{url:x,method:R,data:I,signal:N,cancelToken:k,timeout:B,onDownloadProgress:Y,onUploadProgress:re,responseType:q,headers:Z,withCredentials:Ve="same-origin",fetchOptions:We,maxContentLength:ue,maxBodyLength:Ge}=Gg(T),vr=h.isNumber(ue)&&ue>-1,xr=h.isNumber(Ge)&&Ge>-1,Ys=ce=>h.hasOwnProp(T,ce)?T[ce]:void 0,zs=s||fetch;q=q?(q+"").toLowerCase():"text";let ye=oC([N,k&&k.toAbortSignal()],B),Ee=null,we=ye&&ye.unsubscribe&&(()=>{ye.unsubscribe()}),Ut,Kt=null,Rr=()=>new A("Request body larger than maxBodyLength limit",A.ERR_BAD_REQUEST,T,Ee);try{let ce,He=Ys("auth");if(He){let W=h.getSafeProp(He,"username")||"",$e=h.getSafeProp(He,"password")||"";ce={username:W,password:$e}}if(pC(x)){let W=new URL(x,ve.origin);if(!ce&&(W.username||W.password)){let $e=ig(W.username),M=ig(W.password);ce={username:$e,password:M}}(W.username||W.password)&&(W.username="",W.password="",x=W.href)}if(ce&&(Z.delete("authorization"),Z.set("Authorization","Basic "+btoa(dC((ce.username||"")+":"+(ce.password||""))))),vr&&typeof x=="string"&&x.startsWith("data:")&&LO(x)>ue)throw new A("maxContentLength size of "+ue+" exceeded",A.ERR_BAD_RESPONSE,T,Ee);if(xr&&R!=="get"&&R!=="head"){let W=await _(I);if(typeof W=="number"&&isFinite(W)&&(Ut=W,W>Ge))throw Rr()}let Qr=xr&&(h.isReadableStream(I)||h.isStream(I)),Ft=(W,$e,M)=>ng(W,sg,L=>{if(xr&&L>Ge)throw Kt=Rr();$e&&$e(L)},M);if(m&&R!=="get"&&R!=="head"&&(re||Qr)){if(Ut=Ut??await E(Z,I),Ut!==0||Qr){let W=new i(x,{method:"POST",body:I,duplex:"half"}),$e;if(h.isFormData(I)&&($e=W.headers.get("content-type"))&&Z.setContentType($e),W.body){let[M,L]=re&&Ki(Ut,Tn(Yi(re)))||[];I=Ft(W.body,M,L)}}}else if(Qr&&!c&&l&&R!=="get"&&R!=="head")I=Ft(I);else if(Qr&&c&&!m&&R!=="get"&&R!=="head")throw new A("Stream request bodies are not supported by the current fetch implementation",A.ERR_NOT_SUPPORT,T,Ee);h.isString(Ve)||(Ve=Ve?"include":"omit");let $n=c&&"credentials"in i.prototype;if(h.isFormData(I)){let W=Z.getContentType();W&&/^multipart\/form-data/i.test(W)&&!/boundary=/i.test(W)&&Z.delete("content-type")}Z.set("User-Agent","axios/"+gs,!1);let Wn={...We,signal:ye,method:R.toUpperCase(),headers:nl(Z.normalize()),body:I,duplex:"half",credentials:$n?Ve:void 0};Ee=c&&new i(x,Wn);let de=await(c?zs(Ee,We):zs(x,Wn)),ar=Ie.from(de.headers);if(vr){let W=h.toFiniteNumber(ar.getContentLength());if(W!=null&&W>ue)throw new A("maxContentLength size of "+ue+" exceeded",A.ERR_BAD_RESPONSE,T,Ee)}let Zr=f&&(q==="stream"||q==="response");if(f&&de.body&&(Y||vr||Zr&&we)){let W={};["status","statusText","headers"].forEach(X=>{W[X]=de[X]});let $e=h.toFiniteNumber(ar.getContentLength()),[M,L]=Y&&Ki($e,Tn(Yi(Y),!0))||[],se=0,Te=X=>{if(vr&&(se=X,se>ue))throw new A("maxContentLength size of "+ue+" exceeded",A.ERR_BAD_RESPONSE,T,Ee);M&&M(X)};de=new a(ng(de.body,sg,Te,()=>{L&&L(),we&&we()}),W)}q=q||"text";let Et=await g[h.findKey(g,q)||"text"](de,T);if(vr&&!f&&!Zr){let W;if(Et!=null&&(typeof Et.byteLength=="number"?W=Et.byteLength:typeof Et.size=="number"?W=Et.size:typeof Et=="string"&&(W=typeof n=="function"?new n().encode(Et).byteLength:Et.length)),typeof W=="number"&&W>ue)throw new A("maxContentLength size of "+ue+" exceeded",A.ERR_BAD_RESPONSE,T,Ee)}return!Zr&&we&&we(),await new Promise((W,$e)=>{_n(W,$e,{data:Et,headers:Ie.from(de.headers),status:de.status,statusText:de.statusText,config:T,request:Ee})})}catch(ce){if(we&&we(),ye&&ye.aborted&&ye.reason instanceof A){let He=ye.reason;throw He.config=T,Ee&&(He.request=Ee),ce!==He&&Object.defineProperty(He,"cause",{__proto__:null,value:ce,writable:!0,enumerable:!1,configurable:!0}),He}if(Kt)throw Ee&&!Kt.request&&(Kt.request=Ee),Kt;if(ce instanceof A)throw Ee&&!ce.request&&(ce.request=Ee),ce;if(ce&&ce.name==="TypeError"&&/Load failed|fetch/i.test(ce.message)){let He=new A("Network Error",A.ERR_NETWORK,T,Ee,ce&&ce.response);throw Object.defineProperty(He,"cause",{__proto__:null,value:ce.cause||ce,writable:!0,enumerable:!1,configurable:!0}),He}throw A.from(ce,ce&&ce.code,T,Ee,ce&&ce.response)}}},fC=new Map,Hg=e=>{let t=e&&e.env||{},{fetch:r,Request:n,Response:s}=t,i=[n,s,r],a=i.length,o=a,c,u,l=fC;for(;o--;)c=i[o],u=l.get(c),u===void 0&&l.set(c,u=o?new Map:mC(t)),l=u;return u};Hg();var cl={http:eC,xhr:aC,fetch:{get:Hg}};h.forEach(cl,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});var og=e=>`- ${e}`,gC=e=>h.isFunction(e)||e===null||e===!1;function hC(e,t){e=h.isArray(e)?e:[e];let{length:r}=e,n,s,i={};for(let a=0;a<r;a++){n=e[a];let o;if(s=n,!gC(n)&&(s=cl[(o=String(n)).toLowerCase()],s===void 0))throw new A(`Unknown adapter '${o}'`);if(s&&(h.isFunction(s)||(s=s.get(t))))break;i[o||"#"+a]=s}if(!s){let a=Object.entries(i).map(([c,u])=>`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build")),o=r?a.length>1?`since :
19
+ `+a.map(og).join(`
20
+ `):" "+og(a[0]):"as no adapter specified";throw new A("There is no suitable adapter to dispatch the request "+o,A.ERR_NOT_SUPPORT)}return s}var $g={getAdapter:hC,adapters:cl};function Gc(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new er(null,e)}function Hc(e){return Gc(e),e.headers=Ie.from(e.headers),e.data=jc.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),$g.getAdapter(e.adapter||Es.adapter,e)(e).then(function(n){Gc(e),e.response=n;try{n.data=jc.call(e,e.transformResponse,n)}finally{delete e.response}return n.headers=Ie.from(n.headers),n},function(n){if(!Dg(n)&&(Gc(e),n&&n.response)){e.response=n.response;try{n.response.data=jc.call(e,e.transformResponse,n.response)}finally{delete e.response}n.response.headers=Ie.from(n.response.headers)}return Promise.reject(n)})}var Zi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Zi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var cg={};Zi.transitional=function(t,r,n){function s(i,a){return"[Axios v"+gs+"] Transitional option '"+i+"'"+a+(n?". "+n:"")}return(i,a,o)=>{if(t===!1)throw new A(s(a," has been removed"+(r?" in "+r:"")),A.ERR_DEPRECATED);return r&&!cg[a]&&(cg[a]=!0,console.warn(s(a," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(i,a,o):!0}};Zi.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function yC(e,t,r){if(typeof e!="object"||e===null)throw new A("options must be an object",A.ERR_BAD_OPTION_VALUE);let n=Object.keys(e),s=n.length;for(;s-- >0;){let i=n[s],a=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0;if(a){let o=e[i],c=o===void 0||a(o,i,e);if(c!==!0)throw new A("option "+i+" must be "+c,A.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new A("Unknown option "+i,A.ERR_BAD_OPTION)}}var Gi={assertOptions:yC,validators:Zi},Ke=Gi.validators,Zt=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Wi,response:new Wi}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;let i=(()=>{if(!s.stack)return"";let a=s.stack.indexOf(`
21
+ `);return a===-1?"":s.stack.slice(a+1)})();try{if(!n.stack)n.stack=i;else if(i){let a=i.indexOf(`
22
+ `),o=a===-1?-1:i.indexOf(`
23
+ `,a+1),c=o===-1?"":i.slice(o+1);String(n.stack).endsWith(c)||(n.stack+=`
24
+ `+i)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=qr(this.defaults,r);let{transitional:n,paramsSerializer:s,headers:i}=r;n!==void 0&&Gi.assertOptions(n,{silentJSONParsing:Ke.transitional(Ke.boolean),forcedJSONParsing:Ke.transitional(Ke.boolean),clarifyTimeoutError:Ke.transitional(Ke.boolean),legacyInterceptorReqResOrdering:Ke.transitional(Ke.boolean),advertiseZstdAcceptEncoding:Ke.transitional(Ke.boolean),validateStatusUndefinedResolves:Ke.transitional(Ke.boolean)},!1),s!=null&&(h.isFunction(s)?r.paramsSerializer={serialize:s}:Gi.assertOptions(s,{encode:Ke.function,serialize:Ke.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Gi.assertOptions(r,{baseUrl:Ke.spelling("baseURL"),withXsrfToken:Ke.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=i&&h.merge(i.common,i[r.method]);i&&h.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete i[g]}),r.headers=Ie.concat(a,i);let o=[],c=!0;this.interceptors.request.forEach(function(_){if(typeof _.runWhen=="function"&&_.runWhen(r)===!1)return;c=c&&_.synchronous;let E=r.transitional||Qi;E&&E.legacyInterceptorReqResOrdering?o.unshift(_.fulfilled,_.rejected):o.push(_.fulfilled,_.rejected)});let u=[];this.interceptors.response.forEach(function(_){u.push(_.fulfilled,_.rejected)});let l,d=0,m;if(!c){let g=[Hc.bind(this),void 0];for(g.unshift(...o),g.push(...u),m=g.length,l=Promise.resolve(r);d<m;)l=l.then(g[d++],g[d++]);return l}m=o.length;let f=r;for(;d<m;){let g=o[d++],_=o[d++];try{f=g?g(f):f}catch(E){if(!_){l=Promise.reject(E);break}try{let T=_.call(this,E);h.isThenable(T)&&(l=Promise.resolve(T).then(()=>Hc.call(this,f)))}catch(T){l=Promise.reject(T)}break}}if(!l)try{l=Hc.call(this,f)}catch(g){l=Promise.reject(g)}for(d=0,m=u.length;d<m;)l=l.then(u[d++],u[d++]);return l}getUri(t){t=qr(this.defaults,t);let r=al(t.baseURL,t.url,t.allowAbsoluteUrls,t);return sl(r,t.params,t.paramsSerializer)}};h.forEach(["delete","get","head","options"],function(t){Zt.prototype[t]=function(r,n){return this.request(qr(n||{},{method:t,url:r,data:n&&h.hasOwnProp(n,"data")?n.data:void 0}))}});h.forEach(["post","put","patch","query"],function(t){function r(n){return function(i,a,o){return this.request(qr(o||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:a}))}}Zt.prototype[t]=r(),t!=="query"&&(Zt.prototype[t+"Form"]=r(!0))});var Qc=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(i){r=i});let n=this;this.promise.then(s=>{if(!n._listeners)return;let i=n._listeners.length;for(;i-- >0;)n._listeners[i](s);n._listeners=null}),this.promise.then=s=>{let i,a=new Promise(o=>{n.subscribe(o),i=o}).then(s);return a.cancel=function(){n.unsubscribe(i)},a},t(function(i,a,o){n.reason||(n.reason=new er(i,a,o),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(s){t=s}),cancel:t}}};function _C(e){return function(r){return e.apply(null,r)}}function EC(e){return h.isObject(e)&&e.isAxiosError===!0}var Zc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Zc).forEach(([e,t])=>{Zc[t]=e});function Wg(e){let t=new Zt(e),r=fg(Zt.prototype.request,t);return h.extend(r,Zt.prototype,t,{allOwnKeys:!0}),h.extend(r,t,null,{allOwnKeys:!0}),r.create=function(s){return Wg(qr(e,s))},r}var Oe=Wg(Es);Oe.Axios=Zt;Oe.CanceledError=er;Oe.CancelToken=Qc;Oe.isCancel=Dg;Oe.VERSION=gs;Oe.toFormData=Xi;Oe.AxiosError=A;Oe.Cancel=Oe.CanceledError;Oe.all=function(t){return Promise.all(t)};Oe.spread=_C;Oe.isAxiosError=EC;Oe.mergeConfig=qr;Oe.AxiosHeaders=Ie;Oe.formToJSON=e=>Pg(h.isHTMLForm(e)?new FormData(e):e);Oe.getAdapter=$g.getAdapter;Oe.HttpStatusCode=Zc;Oe.default=Oe;Jg.exports=Oe});var ul=P(Re=>{"use strict";p();var TC=Re&&Re.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Re,"__esModule",{value:!0});Re.Api=Re.HttpClient=Re.ContentType=Re.MissionV1Type=Re.MissionType=Re.MissionRewardType=Re.MissionFrequency=Re.LinkActionType=Re.BannerType=void 0;var Kg;(function(e){e.Clutch="Clutch",e.TelegramMiniApp="TelegramMiniApp",e.TelegramMiniAppBookLocation="TelegramMiniApp-book-location",e.TelegramMiniAppBookInfo="TelegramMiniApp-book-info",e.TelegramMiniAppMVLDescription="TelegramMiniApp-MVL-description"})(Kg||(Re.BannerType=Kg={}));var Yg;(function(e){e.NONE="NONE",e.WEBVIEW="WEBVIEW",e.DAPPVIEW="DAPPVIEW",e.DEEPLINK="DEEPLINK",e.DEEPLINK_WITH_DEFERRED_AUTH="DEEPLINK_WITH_DEFERRED_AUTH",e.MISSION_GROUP="MISSION_GROUP"})(Yg||(Re.LinkActionType=Yg={}));var zg;(function(e){e.PERMANANT="PERMANANT",e.DAILY="DAILY"})(zg||(Re.MissionFrequency=zg={}));var Xg;(function(e){e.BALANCE="BALANCE",e.MISSION_POINT="MISSION_POINT"})(Xg||(Re.MissionRewardType=Xg={}));var Qg;(function(e){e.USER_ACTIVITY="USER_ACTIVITY",e.THIRDPARTY_ACTIVITY="THIRDPARTY_ACTIVITY",e.REFEREE_ACTIVITY="REFEREE_ACTIVITY"})(Qg||(Re.MissionType=Qg={}));var Zg;(function(e){e.MY_ACTIVITIES_COUNT="MY_ACTIVITIES_COUNT",e.REFEREE_ACTIVITIES_COUNT="REFEREE_ACTIVITIES_COUNT"})(Zg||(Re.MissionV1Type=Zg={}));var bC=TC(Qe()),xn;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(xn||(Re.ContentType=xn={}));var ea=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=bC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/activity"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===xn.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===xn.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==xn.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};Re.HttpClient=ea;var ll=class extends ea{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getMissionsDemocopter=(t,r={})=>this.request({path:"/missions/democopter",method:"GET",query:t,format:"json",...r});getV1Banners=(t,r={})=>this.request({path:"/v1/banners",method:"GET",query:t,secure:!0,format:"json",...r});getV1BannersBasic=(t,r={})=>this.request({path:"/v1/banners-basic",method:"GET",query:t,secure:!0,format:"json",...r});getV1BannersBasicByRegion=(t,r,n={})=>this.request({path:`/v1/banners-basic/${t}`,method:"GET",query:r,secure:!0,format:"json",...n});getV1BannersByRegion=(t,r,n={})=>this.request({path:`/v1/banners/${t}`,method:"GET",query:r,secure:!0,format:"json",...n});getV1MissionPoint=(t,r={})=>this.request({path:"/v1/mission-point",method:"GET",query:t,secure:!0,format:"json",...r});getV1PublicBanners=(t,r={})=>this.request({path:"/v1/public/banners",method:"GET",query:t,format:"json",...r});getV1ReferralCodeCurrent=(t={})=>this.request({path:"/v1/referralCode/current",method:"GET",secure:!0,format:"json",...t});getV1ReferralsCurrentInviteCount=(t={})=>this.request({path:"/v1/referrals/current/invite-count",method:"GET",secure:!0,format:"json",...t});getV2Missions=(t,r={})=>this.request({path:"/v2/missions",method:"GET",query:t,secure:!0,format:"json",...r});getV2MissionsGroups=(t,r={})=>this.request({path:"/v2/missions/groups",method:"GET",query:t,secure:!0,format:"json",...r});getV2MissionsGroupsByAlias=(t,r={})=>this.request({path:`/v2/missions/groups/${t}`,method:"GET",secure:!0,format:"json",...r});getV2PublicMissions=(t,r={})=>this.request({path:"/v2/public/missions",method:"GET",query:t,format:"json",...r});getV2PublicMissionsGroups=(t,r={})=>this.request({path:"/v2/public/missions/groups",method:"GET",query:t,format:"json",...r});getV2PublicMissionsGroupsByAlias=(t,r={})=>this.request({path:`/v2/public/missions/groups/${t}`,method:"GET",format:"json",...r});getV3Missions=(t,r={})=>this.request({path:"/v3/missions",method:"GET",query:t,secure:!0,format:"json",...r});getV3MissionsGroups=(t,r={})=>this.request({path:"/v3/missions/groups",method:"GET",query:t,secure:!0,format:"json",...r});getV3MissionsGroupsByAlias=(t,r={})=>this.request({path:`/v3/missions/groups/${t}`,method:"GET",secure:!0,format:"json",...r});postV1ReferralCodeRegister=(t,r={})=>this.request({path:"/v1/referralCode/register",method:"POST",body:t,secure:!0,type:xn.Json,format:"json",...r});postV2ActivitiesByTypeId=(t,r={})=>this.request({path:`/v2/activities/${t}`,method:"POST",secure:!0,format:"json",...r});postV2MissionsByIdAfterAction=(t,r={})=>this.request({path:`/v2/missions/${t}/after-action`,method:"POST",secure:!0,format:"json",...r});postV2MissionsByIdClaim=(t,r={})=>this.request({path:`/v2/missions/${t}/claim`,method:"POST",secure:!0,format:"json",...r});postV3ActivitiesByTypeId=(t,r={})=>this.request({path:`/v3/activities/${t}`,method:"POST",secure:!0,format:"json",...r});postV3MissionsByIdAfterAction=(t,r={})=>this.request({path:`/v3/missions/${t}/after-action`,method:"POST",secure:!0,format:"json",...r});postV3MissionsByIdClaim=(t,r={})=>this.request({path:`/v3/missions/${t}/claim`,method:"POST",secure:!0,format:"json",...r})};Re.Api=ll});var pl=P(K=>{"use strict";p();var vC=K&&K.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(K,"__esModule",{value:!0});K.Api=K.HttpClient=K.ContentType=K.AmbientHailingTelemetryEventDtoSubMarketEnum=K.AmbientHailingTelemetryEventDtoStageEnum=K.AmbientHailingTelemetryEventDtoRegionEnum=K.AmbientHailingTelemetryEventDtoPaymentModeEnum=K.AmbientHailingTelemetryEventDtoOutcomeEnum=K.AmbientHailingTelemetryEventDtoJourneyOutcomeEnum=K.AmbientHailingTelemetryEventDtoFailureReasonEnum=K.AmbientHailingTelemetryEventDtoEventNameEnum=K.AmbientHailingTelemetryEventDtoErrorCodeEnum=K.AmbientHailingTelemetryEventDtoDispatchOutcomeEnum=K.AmbientHailingTelemetryEventDtoCommandEnum=K.AmbientHailingTelemetryEventDtoCancellationStageEnum=K.AmbientHailingTelemetryEventDtoCancellationActorEnum=K.AmbientHailingTelemetryEventDtoBuildEnvEnum=K.AmbientHailingTelemetryEventDtoAhUserTypeEnum=K.AmbientHailingTelemetryBatchDtoSourceEnum=K.AmbientHailingTelemetryBatchDtoSchemaVersionEnum=void 0;var eh;(function(e){e[e.Value1=1]="Value1"})(eh||(K.AmbientHailingTelemetryBatchDtoSchemaVersionEnum=eh={}));var th;(function(e){e.AmbientHailing="ambient_hailing"})(th||(K.AmbientHailingTelemetryBatchDtoSourceEnum=th={}));var rh;(function(e){e.New="new",e.Existing="existing"})(rh||(K.AmbientHailingTelemetryEventDtoAhUserTypeEnum=rh={}));var nh;(function(e){e.Dev="dev",e.Staging="staging",e.Production="production"})(nh||(K.AmbientHailingTelemetryEventDtoBuildEnvEnum=nh={}));var sh;(function(e){e.Rider="rider",e.Driver="driver",e.Company="company",e.System="system"})(sh||(K.AmbientHailingTelemetryEventDtoCancellationActorEnum=sh={}));var ih;(function(e){e.PreMatch="pre_match",e.PostMatch="post_match",e.InRide="in_ride"})(ih||(K.AmbientHailingTelemetryEventDtoCancellationStageEnum=ih={}));var ah;(function(e){e.Activation="activation",e.RideSearch="ride-search",e.RideRequest="ride-request",e.RidePayPrepare="ride-pay-prepare",e.RidePayConfirm="ride-pay-confirm",e.RideMonitor="ride-monitor",e.Tip="tip"})(ah||(K.AmbientHailingTelemetryEventDtoCommandEnum=ah={}));var oh;(function(e){e.SearchNotStarted="search_not_started",e.SearchStarted="search_started",e.NoDriver="no_driver",e.Matched="matched"})(oh||(K.AmbientHailingTelemetryEventDtoDispatchOutcomeEnum=oh={}));var ch;(function(e){e.RIDE_SEARCH_FAILED="RIDE_SEARCH_FAILED",e.RIDE_REQUEST_FAILED="RIDE_REQUEST_FAILED",e.RIDE_PAY_PREPARE_FAILED="RIDE_PAY_PREPARE_FAILED",e.RIDE_PAY_CONFIRM_FAILED="RIDE_PAY_CONFIRM_FAILED"})(ch||(K.AmbientHailingTelemetryEventDtoErrorCodeEnum=ch={}));var lh;(function(e){e.AmbientCliCommandStarted="ambient_cli_command_started",e.AmbientCliCommandCompleted="ambient_cli_command_completed",e.AmbientCliCommandFailed="ambient_cli_command_failed"})(lh||(K.AmbientHailingTelemetryEventDtoEventNameEnum=lh={}));var uh;(function(e){e.WalletNoBalance="wallet_no_balance",e.WalletInsufficientBalance="wallet_insufficient_balance",e.CardError="card_error",e.Other="other"})(uh||(K.AmbientHailingTelemetryEventDtoFailureReasonEnum=uh={}));var dh;(function(e){e.Completed="completed",e.Cancelled="cancelled",e.Abandoned="abandoned"})(dh||(K.AmbientHailingTelemetryEventDtoJourneyOutcomeEnum=dh={}));var ph;(function(e){e.Started="started",e.Completed="completed",e.Failed="failed"})(ph||(K.AmbientHailingTelemetryEventDtoOutcomeEnum=ph={}));var mh;(function(e){e.Card="card",e.WalletUsdc="wallet_usdc"})(mh||(K.AmbientHailingTelemetryEventDtoPaymentModeEnum=mh={}));var fh;(function(e){e.SG="SG",e.US="US"})(fh||(K.AmbientHailingTelemetryEventDtoRegionEnum=fh={}));var gh;(function(e){e.VehicleSearchStarted="vehicle_search_started",e.OptionsPresented="options_presented",e.ZeroResults="zero_results",e.VehicleSearchFailed="vehicle_search_failed",e.CallConfirmed="call_confirmed",e.BookingRequested="booking_requested",e.BookingFailed="booking_failed",e.PaymentStarted="payment_started",e.PaymentAuthorizationPrepared="payment_authorization_prepared",e.PaymentConfirmationStarted="payment_confirmation_started",e.PaymentStepCompleted="payment_step_completed",e.PaymentCompleted="payment_completed",e.PaymentFailed="payment_failed",e.RideCreated="ride_created",e.DriverSearchStarted="driver_search_started",e.DriverMatched="driver_matched",e.PickupArrived="pickup_arrived",e.RideStarted="ride_started",e.RideArrived="ride_arrived",e.RideCancelled="ride_cancelled",e.RideAbandoned="ride_abandoned",e.TipCompleted="tip_completed",e.ActivationInstalled="activation_installed",e.ActivationAuthenticated="activation_authenticated"})(gh||(K.AmbientHailingTelemetryEventDtoStageEnum=gh={}));var hh;(function(e){e.SG="SG",e.NYC="NYC",e.DENVER="DENVER",e.OTHER="OTHER"})(hh||(K.AmbientHailingTelemetryEventDtoSubMarketEnum=hh={}));var xC=vC(Qe()),Rn;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Rn||(K.ContentType=Rn={}));var ta=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=xC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/amb-telemetry"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Rn.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Rn.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Rn.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};K.HttpClient=ta;var dl=class extends ta{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});postV1Events=(t,r={})=>this.request({path:"/v1/events",method:"POST",body:t,type:Rn.Json,format:"json",...r})};K.Api=dl});var fl=P(At=>{"use strict";p();var RC=At&&At.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(At,"__esModule",{value:!0});At.Api=At.HttpClient=At.ContentType=At.SwapType=void 0;var yh;(function(e){e.TOBEP20="TO_BEP20",e.TOERC20="TO_ERC20"})(yh||(At.SwapType=yh={}));var AC=RC(Qe()),pr;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(pr||(At.ContentType=pr={}));var ra=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=AC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/v1/bridge-swap"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===pr.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===pr.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==pr.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};At.HttpClient=ra;var ml=class extends ra{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getV1BridgeSwap=(t,r={})=>this.request({path:"/v1/bridge-swap",method:"GET",query:t,secure:!0,format:"json",...r});getV1BridgeSwapFee=(t,r={})=>this.request({path:"/v1/bridge-swap/fee",method:"GET",query:t,secure:!0,format:"json",...r});getV1Swap=(t,r={})=>this.request({path:"/v1/swap",method:"GET",query:t,format:"json",...r});getV1SwapFee=(t,r={})=>this.request({path:"/v1/swap/fee",method:"GET",query:t,format:"json",...r});getV2SwapStatus=(t={})=>this.request({path:"/v2/swap/status",method:"GET",format:"json",...t});postV1BridgeSwap=(t,r={})=>this.request({path:"/v1/bridge-swap",method:"POST",body:t,secure:!0,type:pr.Json,format:"json",...r});postV1Swap=(t,r={})=>this.request({path:"/v1/swap",method:"POST",body:t,type:pr.Json,...r});postV2Swap=(t,r={})=>this.request({path:"/v2/swap",method:"POST",body:t,type:pr.Json,format:"json",...r})};At.Api=ml});var hl=P($=>{"use strict";p();var wC=$&&$.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty($,"__esModule",{value:!0});$.Api=$.HttpClient=$.ContentType=$.UpbitPriceInfoResponseDtoCurrencyCodeEnum=$.TransactionType=$.TransactionStatus=$.TokenType=$.StakingType=$.StakingStatus=$.SortOrder=$.GetV3BlockchainNetworksParamsRegionEnum=$.GetV3BlockchainNetworksParamsEnvironmentEnum=$.GetV3BlockchainContractsParamsRegionEnum=$.GetV3BlockchainContractsParamsEnvironmentEnum=$.GetV2WalletsSimplePricePublicParamsIdsEnum=$.GetV1PriceHistoryMvlParamsCurrencyEnum=$.GetTokenPriceByDateDtoPriceTypeEnum=$.FilterType=$.CryptoCurrency=$.ContractName=$.BlockchainNetwork=$.AssetMigrationStatus=void 0;var _h;(function(e){e.PENDING="PENDING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"})(_h||($.AssetMigrationStatus=_h={}));var Eh;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(Eh||($.BlockchainNetwork=Eh={}));var Th;(function(e){e.API3ReaderProxy="API3ReaderProxy",e.AccountRegistry="AccountRegistry",e.AdaptiveCurveIrm="AdaptiveCurveIrm",e.AgentDepositV1="AgentDepositV1",e.BEP20Mintable="BEP20Mintable",e.BMVL="BMVL",e.BMVLBridgeAdapter="BMVLBridgeAdapter",e.BTX="BTX",e.BiswapPair="BiswapPair",e.BiswapPairLP="BiswapPairLP",e.BiswapRouter02="BiswapRouter02",e.Bundler3="Bundler3",e.ConsentRegistry="ConsentRegistry",e.DEMOT1="DEMOT1",e.DepinLocationInfoV1="DepinLocationInfoV1",e.ERC1155="ERC1155",e.ERC20="ERC20",e.ERC721="ERC721",e.FiatTokenV22="FiatTokenV2_2",e.GeneralAdapter1="GeneralAdapter1",e.GeneralToken="GeneralToken",e.GuarantorRegistry="GuarantorRegistry",e.GuarantorVault="GuarantorVault",e.IMulticall3="IMulticall3",e.InvoiceManager="InvoiceManager",e.LeaseToken="LeaseToken",e.LockedTadaPointV1="LockedTadaPointV1",e.MVLBridgeAdapter="MVLBridgeAdapter",e.MVLDrop="MVLDrop",e.MVLToken="MVLToken",e.MVLTokenTest="MVLTokenTest",e.MasterChefLPEvent="MasterChefLPEvent",e.MasterChefSingleEvent="MasterChefSingleEvent",e.MasterChefSingleEventLock="MasterChefSingleEventLock",e.MetaMorphoV11="MetaMorphoV1_1",e.MetaMorphoV11Factory="MetaMorphoV1_1Factory",e.Morpho="Morpho",e.MorphoChainlinkOracleV2="MorphoChainlinkOracleV2",e.MusubiARNFT="MusubiARNFT",e.MusubiARProtocol="MusubiARProtocol",e.MusubiAccIncome="MusubiAccIncome",e.MusubiLeaseV2="MusubiLeaseV2",e.MusubiManager="MusubiManager",e.MusubiOwnership="MusubiOwnership",e.MusubiOwnershipV2="MusubiOwnershipV2",e.MusubiV2="MusubiV2",e.NonfungiblePositionManager="NonfungiblePositionManager",e.OptimismMintableERC20="OptimismMintableERC20",e.OracleConverter="OracleConverter",e.OwnershipToken="OwnershipToken",e.PaybackEscrow="PaybackEscrow",e.PayerRegistry="PayerRegistry",e.Permit2="Permit2",e.PledgeRegistry="PledgeRegistry",e.PointSystemV1="PointSystemV1",e.PriceFeed="PriceFeed",e.PriceFeedAdapter="PriceFeedAdapter",e.PricingStrategyRegistry="PricingStrategyRegistry",e.ProtocolAccessControl="ProtocolAccessControl",e.ProtocolConfig="ProtocolConfig",e.PurchaseEscrow="PurchaseEscrow",e.RideRecord="RideRecord",e.RideRecordDep="RideRecord_dep",e.SellerRegistry="SellerRegistry",e.StableToken="StableToken",e.TADAwhiteList="TADAwhiteList",e.TadaPointUSV1="TadaPointUSV1",e.TadaToken="TadaToken",e.TetherToken="TetherToken",e.TruefareV1="TruefareV1",e.USTadaPointV1="USTadaPointV1",e.UniswapV2ERC20="UniswapV2ERC20",e.UniswapV2Factory="UniswapV2Factory",e.UniswapV2Pair="UniswapV2Pair",e.UniswapV2Router02="UniswapV2Router02",e.UniswapV3Factory="UniswapV3Factory",e.UniswapV3Pool="UniswapV3Pool",e.WBNB="WBNB",e.WETH="WETH"})(Th||($.ContractName=Th={}));var bh;(function(e){e.JPY="JPY",e.USDC="USDC"})(bh||($.CryptoCurrency=bh={}));var vh;(function(e){e.ALL="ALL",e.SEND="SEND",e.RECEIVE="RECEIVE"})(vh||($.FilterType=vh={}));var xh;(function(e){e.HIGH="HIGH",e.LOW="LOW"})(xh||($.GetTokenPriceByDateDtoPriceTypeEnum=xh={}));var Rh;(function(e){e.USD="USD",e.SGD="SGD",e.KRW="KRW",e.IDR="IDR",e.THB="THB",e.KHR="KHR",e.JPY="JPY"})(Rh||($.GetV1PriceHistoryMvlParamsCurrencyEnum=Rh={}));var Ah;(function(e){e.MassVehicleLedger="mass-vehicle-ledger"})(Ah||($.GetV2WalletsSimplePricePublicParamsIdsEnum=Ah={}));var wh;(function(e){e.Production="production",e.Stage="stage",e.Dev="dev"})(wh||($.GetV3BlockchainContractsParamsEnvironmentEnum=wh={}));var Sh;(function(e){e.ALL="ALL",e.KR="KR",e.SG="SG",e.KH="KH",e.VN="VN",e.TH="TH",e.JP="JP",e.CO="CO",e.HK="HK",e.ID="ID",e.NY="NY"})(Sh||($.GetV3BlockchainContractsParamsRegionEnum=Sh={}));var Ih;(function(e){e.Production="production",e.Stage="stage",e.Dev="dev"})(Ih||($.GetV3BlockchainNetworksParamsEnvironmentEnum=Ih={}));var Ph;(function(e){e.ALL="ALL",e.KR="KR",e.SG="SG",e.KH="KH",e.VN="VN",e.TH="TH",e.JP="JP",e.CO="CO",e.HK="HK",e.ID="ID",e.NY="NY"})(Ph||($.GetV3BlockchainNetworksParamsRegionEnum=Ph={}));var Dh;(function(e){e.Asc="asc",e.Desc="desc"})(Dh||($.SortOrder=Dh={}));var Oh;(function(e){e.ACTIVE="ACTIVE",e.FINISHED="FINISHED"})(Oh||($.StakingStatus=Oh={}));var Ch;(function(e){e.LP="LP",e.SINGLE="SINGLE",e.SINGLE_LOCKUP="SINGLE_LOCKUP"})(Ch||($.StakingType=Ch={}));var Nh;(function(e){e.COIN="COIN",e.ERC20="ERC20",e.BEP20="BEP20",e.FA2="FA2",e.FA12="FA1.2",e.SERVERED="SERVERED",e.JETTON="JETTON"})(Nh||($.TokenType=Nh={}));var Lh;(function(e){e.PENDING="PENDING",e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(Lh||($.TransactionStatus=Lh={}));var kh;(function(e){e.SEND_ETH="SEND_ETH",e.SENDERC20="SEND_ERC20",e.SENDERC721="SEND_ERC721",e.SENDBEP20="SEND_BEP20",e.SEND_BNB="SEND_BNB",e.SEND_XTZ="SEND_XTZ",e.SEND_BTC="SEND_BTC",e.UNKNOWN="UNKNOWN"})(kh||($.TransactionType=kh={}));var Mh;(function(e){e.USD="USD",e.SGD="SGD",e.KRW="KRW",e.IDR="IDR",e.THB="THB",e.KHR="KHR",e.JPY="JPY"})(Mh||($.UpbitPriceInfoResponseDtoCurrencyCodeEnum=Mh={}));var SC=wC(Qe()),Bt;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Bt||($.ContentType=Bt={}));var na=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=SC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/clutch"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Bt.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Bt.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Bt.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};$.HttpClient=na;var gl=class extends na{getApiMvlInfo=(t={})=>this.request({path:"/api/mvl/info",method:"GET",format:"json",...t});getAssetMigrationByAddress=(t,r={})=>this.request({path:`/asset-migration/${t}`,method:"GET",format:"json",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getV11LinkTransferReceive=(t={})=>this.request({path:"/v1.1/link-transfer/receive",method:"GET",...t});getV11WalletsSimplePrice=(t,r={})=>this.request({path:"/v1.1/wallets/simple/price",method:"GET",query:t,format:"json",...r});getV11WalletsTransactions=(t,r={})=>this.request({path:"/v1.1/wallets/transactions",method:"GET",query:t,format:"json",...r});getV1BlockTransactions=(t,r={})=>this.request({path:"/v1/block-transactions",method:"GET",query:t,secure:!0,format:"json",...r});getV1PriceHistoryMvl=(t,r={})=>this.request({path:"/v1/price/history/mvl",method:"GET",query:t,format:"json",...r});getV1Stakings=(t,r={})=>this.request({path:"/v1/stakings",method:"GET",query:t,format:"json",...r});getV1TokenByNetwork=(t,r={})=>this.request({path:`/v1/token/${t}`,method:"GET",format:"json",...r});getV1Transactions=(t,r={})=>this.request({path:"/v1/transactions",method:"GET",query:t,format:"json",...r});getV1TransactionsRefresh=(t,r={})=>this.request({path:"/v1/transactions/refresh",method:"GET",query:t,format:"json",...r});getV1TransactionsRefreshBulk=(t,r={})=>this.request({path:"/v1/transactions/refresh-bulk",method:"GET",query:t,format:"json",...r});getV1WalletsTransactions=(t,r={})=>this.request({path:"/v1/wallets/transactions",method:"GET",query:t,format:"json",...r});getV2BlockchainChains=(t={})=>this.request({path:"/v2/blockchain/chains",method:"GET",format:"json",...t});getV2Token=(t={})=>this.request({path:"/v2/token",method:"GET",format:"json",...t});getV2TokenByNetwork=(t,r={})=>this.request({path:`/v2/token/${t}`,method:"GET",format:"json",...r});getV2TransactionsRefresh=(t,r={})=>this.request({path:"/v2/transactions/refresh",method:"GET",query:t,format:"json",...r});getV2WalletsSimplePrice=(t,r={})=>this.request({path:"/v2/wallets/simple/price",method:"GET",query:t,secure:!0,format:"json",...r});getV2WalletsSimplePricePublic=(t,r={})=>this.request({path:"/v2/wallets/simple/price/public",method:"GET",query:t,format:"json",...r});getV2WalletsTransactionHistory=(t,r={})=>this.request({path:"/v2/wallets/transaction/history",method:"GET",query:t,format:"json",...r});getV2WalletsTransactionHistoryById=(t,r={})=>this.request({path:`/v2/wallets/transaction/history/${t}`,method:"GET",format:"json",...r});getV3BlockchainContracts=(t,r={})=>this.request({path:"/v3/blockchain/contracts",method:"GET",query:t,secure:!0,format:"json",...r});getV3BlockchainNetworks=(t,r={})=>this.request({path:"/v3/blockchain/networks",method:"GET",query:t,secure:!0,format:"json",...r});getV3Token=(t={})=>this.request({path:"/v3/token",method:"GET",format:"json",...t});getV3TokenByNetwork=(t,r={})=>this.request({path:`/v3/token/${t}`,method:"GET",format:"json",...r});getV3TokenByNetworkByTokenSymbol=(t,r,n={})=>this.request({path:`/v3/token/${t}/${r}`,method:"GET",format:"json",...n});postAssetMigration=(t,r={})=>this.request({path:"/asset-migration",method:"POST",body:t,type:Bt.Json,format:"json",...r});postV11WalletsTransactions=(t,r={})=>this.request({path:"/v1.1/wallets/transactions",method:"POST",body:t,type:Bt.Json,format:"json",...r});postV1WalletsTransactions=(t,r={})=>this.request({path:"/v1/wallets/transactions",method:"POST",body:t,type:Bt.Json,format:"json",...r});postV2LinkTransferLog=(t,r={})=>this.request({path:"/v2/link-transfer/log",method:"POST",body:t,secure:!0,type:Bt.Json,format:"json",...r});postV2WalletsTransaction=(t,r={})=>this.request({path:"/v2/wallets/transaction",method:"POST",body:t,secure:!0,type:Bt.Json,format:"json",...r})};$.Api=gl});var _l=P(V=>{"use strict";p();var IC=V&&V.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(V,"__esModule",{value:!0});V.Api=V.HttpClient=V.ContentType=V.UserIdentifierType=V.TriggerSnapshotDtoRegionsEnum=V.TriggerSnapshotDtoIdentifierTypesEnum=V.TransferingToDataAttestationWalletRequestDtoToCurrencyEnum=V.TransferingToDataAttestationWalletRequestDtoFromCurrencyEnum=V.TransferInputDtoUserModelEnum=V.TransferInputDtoTransferTypeEnum=V.TransactionStatusEnum=V.TadaPointRuleType=V.S2SGetWalletBalanceResponseDtoCurrencyEnum=V.S2SGetWalletBalanceRequestDtoCurrencyEnum=V.Region=V.PointRequestType=V.GetWalletTokenHistoryResponseDtoCurrencyEnum=V.GetWalletTokenHistoryRequestDtoCurrencyEnum=V.GetWalletBalanceUcResponseCurrencyEnum=V.DataGeneratedNotificationV1DtoStatusEnum=V.DataAttestationTxType=V.DATA_PROVIDER=V.BulkRegisterWalletResultStatus=V.BlockchainNetwork=V.AttestationRequestStatus=void 0;var Uh;(function(e){e.REQUESTED="REQUESTED",e.INTERNAL_PARTY_READY="INTERNAL_PARTY_READY",e.SOURCE_DATA_UPLOADING="SOURCE_DATA_UPLOADING",e.SOURCE_DATA_UPLOADED="SOURCE_DATA_UPLOADED",e.ATTESTING="ATTESTING",e.ATTESTED="ATTESTED",e.ATTESTED_DATA_UPLOADING="ATTESTED_DATA_UPLOADING",e.ATTESTED_DATA_UPLOADED="ATTESTED_DATA_UPLOADED",e.FINISHED="FINISHED",e.FAILED="FAILED"})(Uh||(V.AttestationRequestStatus=Uh={}));var Fh;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(Fh||(V.BlockchainNetwork=Fh={}));var jh;(function(e){e.Reused="reused",e.Created="created",e.Skipped="skipped",e.PrivyMissing="privy_missing",e.Error="error"})(jh||(V.BulkRegisterWalletResultStatus=jh={}));var qh;(function(e){e.TADA="TADA"})(qh||(V.DATA_PROVIDER=qh={}));var Bh;(function(e){e.COIN_TRANSFER="COIN_TRANSFER",e.TOKEN_TRANSFER="TOKEN_TRANSFER",e.SUBSIDY_TRANSFER="SUBSIDY_TRANSFER",e.INCENTIVE_TRANSFER="INCENTIVE_TRANSFER",e.RIDE_RECORD_EVENT="RIDE_RECORD_EVENT",e.LOCK_POINT_EVENT="LOCK_POINT_EVENT",e.UNLOCK_POINT_EVENT="UNLOCK_POINT_EVENT"})(Bh||(V.DataAttestationTxType=Bh={}));var Vh;(function(e){e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(Vh||(V.DataGeneratedNotificationV1DtoStatusEnum=Vh={}));var Gh;(function(e){e.BITCOIN="BITCOIN",e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})(Gh||(V.GetWalletBalanceUcResponseCurrencyEnum=Gh={}));var Hh;(function(e){e.BITCOIN="BITCOIN",e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})(Hh||(V.GetWalletTokenHistoryRequestDtoCurrencyEnum=Hh={}));var $h;(function(e){e.BITCOIN="BITCOIN",e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})($h||(V.GetWalletTokenHistoryResponseDtoCurrencyEnum=$h={}));var Wh;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(Wh||(V.PointRequestType=Wh={}));var Jh;(function(e){e.ALL="ALL",e.KR="KR",e.SG="SG",e.KH="KH",e.VN="VN",e.TH="TH",e.JP="JP",e.CO="CO",e.HK="HK",e.ID="ID",e.NY="NY"})(Jh||(V.Region=Jh={}));var Kh;(function(e){e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})(Kh||(V.S2SGetWalletBalanceRequestDtoCurrencyEnum=Kh={}));var Yh;(function(e){e.BITCOIN="BITCOIN",e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})(Yh||(V.S2SGetWalletBalanceResponseDtoCurrencyEnum=Yh={}));var zh;(function(e){e.ESTIMATED_DISTANCE_BAND="ESTIMATED_DISTANCE_BAND",e.RIDE_PRODUCT="RIDE_PRODUCT",e.OTHERS="OTHERS",e.GEOFENCE="GEOFENCE",e.REFERRAL="REFERRAL",e.APPROVED_DRIVER="APPROVED_DRIVER"})(zh||(V.TadaPointRuleType=zh={}));var Xh;(function(e){e.PENDING="PENDING",e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(Xh||(V.TransactionStatusEnum=Xh={}));var Qh;(function(e){e.COIN_TRANSFER="COIN_TRANSFER",e.INCENTIVE_TRANSFER="INCENTIVE_TRANSFER",e.SUBSIDY_TRANSFER="SUBSIDY_TRANSFER"})(Qh||(V.TransferInputDtoTransferTypeEnum=Qh={}));var Zh;(function(e){e.DRIVER="DRIVER",e.RIDER="RIDER"})(Zh||(V.TransferInputDtoUserModelEnum=Zh={}));var ey;(function(e){e.FIAT_SGD="FIAT_SGD",e.FIAT_USD="FIAT_USD",e.MVL="MVL",e.TADA_TOKEN="TADA_TOKEN"})(ey||(V.TransferingToDataAttestationWalletRequestDtoFromCurrencyEnum=ey={}));var ty;(function(e){e.MVL="MVL",e.TADA_TOKEN="TADA_TOKEN"})(ty||(V.TransferingToDataAttestationWalletRequestDtoToCurrencyEnum=ty={}));var ry;(function(e){e.PASSWORD="PASSWORD",e.FACEBOOK="FACEBOOK",e.GOOGLE="GOOGLE",e.TWITTER="TWITTER",e.DISCORD="DISCORD",e.APPLE="APPLE",e.WEB3="WEB3",e.HMAC="HMAC",e.TELEGRAM_MINIAPP="TELEGRAM_MINIAPP",e.THIRDPARTYS2S="THIRDPARTY_S2S",e.PRIVY="PRIVY",e.TADA_COUPON_VOUCHER="TADA_COUPON_VOUCHER",e.DATA_ATTESTATION_TADA_DRIVER="DATA_ATTESTATION_TADA_DRIVER",e.DATA_ATTESTATION_TADA_RIDER="DATA_ATTESTATION_TADA_RIDER",e.BASE_MINIAPP="BASE_MINIAPP",e.AR_INVESTOR="AR_INVESTOR",e.SIWE="SIWE",e.IN_MIGRATION="IN_MIGRATION"})(ry||(V.TriggerSnapshotDtoIdentifierTypesEnum=ry={}));var ny;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(ny||(V.TriggerSnapshotDtoRegionsEnum=ny={}));var sy;(function(e){e.PASSWORD="PASSWORD",e.FACEBOOK="FACEBOOK",e.GOOGLE="GOOGLE",e.TWITTER="TWITTER",e.DISCORD="DISCORD",e.APPLE="APPLE",e.WEB3="WEB3",e.HMAC="HMAC",e.TELEGRAM_MINIAPP="TELEGRAM_MINIAPP",e.THIRDPARTYS2S="THIRDPARTY_S2S",e.PRIVY="PRIVY",e.TADA_COUPON_VOUCHER="TADA_COUPON_VOUCHER",e.DATA_ATTESTATION_TADA_DRIVER="DATA_ATTESTATION_TADA_DRIVER",e.DATA_ATTESTATION_TADA_RIDER="DATA_ATTESTATION_TADA_RIDER",e.BASE_MINIAPP="BASE_MINIAPP",e.AR_INVESTOR="AR_INVESTOR",e.SIWE="SIWE",e.IN_MIGRATION="IN_MIGRATION"})(sy||(V.UserIdentifierType=sy={}));var PC=IC(Qe()),Pe;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Pe||(V.ContentType=Pe={}));var sa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=PC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/attestation"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Pe.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Pe.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Pe.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};V.HttpClient=sa;var yl=class extends sa{getConsentTest=(t={})=>this.request({path:"/consent/test",method:"GET",format:"json",...t});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getRequestTest=(t={})=>this.request({path:"/request/test",method:"GET",format:"json",...t});getV1ConsoleUserVerify=(t={})=>this.request({path:"/v1/console-user/verify",method:"GET",format:"json",...t});getV1DynamicValues=(t,r={})=>this.request({path:"/v1/dynamic-values",method:"GET",query:t,secure:!0,format:"json",...r});getV1ExternalDataAttestationById=(t,r={})=>this.request({path:`/v1/external/data-attestation/${t}`,method:"GET",format:"json",...r});getV1ExternalDataAttestationHistories=(t,r={})=>this.request({path:"/v1/external/data-attestation/histories",method:"GET",query:t,format:"json",...r});getV1FeatureFlag=(t={})=>this.request({path:"/v1/feature-flag",method:"GET",format:"json",...t});getV1InternalTransactionHistory=(t,r={})=>this.request({path:"/v1/internal/transaction/history",method:"GET",query:t,secure:!0,format:"json",...r});getV1InternalWebhookAttestationRequestById=(t,r={})=>this.request({path:`/v1/internal/webhook/attestation-request/${t}`,method:"GET",secure:!0,format:"json",...r});getV1PointPrograms=(t={})=>this.request({path:"/v1/point/programs",method:"GET",secure:!0,format:"json",...t});getV1PublicIncentiveAggregateSummary=(t,r={})=>this.request({path:"/v1/public/incentive-aggregate/summary",method:"GET",query:t,format:"json",...r});getV1StaticAssetCampaignMechanics=(t,r={})=>this.request({path:"/v1/static-asset/campaign-mechanics",method:"GET",query:t,format:"json",...r});getV1WalletMeBalance=(t,r={})=>this.request({path:"/v1/wallet/me/balance",method:"GET",query:t,secure:!0,format:"json",...r});postV1ConsoleUserLogin=(t,r={})=>this.request({path:"/v1/console-user/login",method:"POST",body:t,type:Pe.Json,format:"json",...r});postV1ConsoleUserLogout=(t={})=>this.request({path:"/v1/console-user/logout",method:"POST",format:"json",...t});postV1ExternalDataAttestation=(t,r={})=>this.request({path:"/v1/external/data-attestation",method:"POST",body:t,type:Pe.Json,format:"json",...r});postV1IncentiveAggregateSummary=(t,r={})=>this.request({path:"/v1/incentive-aggregate/summary",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalSubsidy=(t,r={})=>this.request({path:"/v1/internal/subsidy",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalTransactionHistory=(t,r={})=>this.request({path:"/v1/internal/transaction/history",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalTransactionRideHistory=(t,r={})=>this.request({path:"/v1/internal/transaction/ride-history",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalWallet=(t,r={})=>this.request({path:"/v1/internal/wallet",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalWalletBalanceSnapshot=(t,r={})=>this.request({path:"/v1/internal/wallet-balance/snapshot",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalWalletBulk=(t,r={})=>this.request({path:"/v1/internal/wallet/bulk",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalWebhookNotificationDataGenerated=(t,r={})=>this.request({path:"/v1/internal/webhook/notification/data-generated",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1InternalWebhookNotificationDataGeneratedRevert=(t={})=>this.request({path:"/v1/internal/webhook/notification/data-generated/revert",method:"POST",secure:!0,format:"json",...t});postV1S2SPointLock=(t,r={})=>this.request({path:"/v1/s2s/point/lock",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1S2SPointUnlock=(t,r={})=>this.request({path:"/v1/s2s/point/unlock",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1TadaReferrals=(t,r={})=>this.request({path:"/v1/tada/referrals",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1TransferingToDataAttestationWallet=(t,r={})=>this.request({path:"/v1/transfering-to-data-attestation-wallet",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1WalletBalance=(t,r={})=>this.request({path:"/v1/wallet/balance",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postV1WalletHistory=(t,r={})=>this.request({path:"/v1/wallet/history",method:"POST",body:t,secure:!0,type:Pe.Json,format:"json",...r});postWebhookDummy=(t={})=>this.request({path:"/webhook-dummy",method:"POST",...t})};V.Api=yl});var Tl=P(ot=>{"use strict";p();var DC=ot&&ot.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ot,"__esModule",{value:!0});ot.Api=ot.HttpClient=ot.ContentType=ot.TextAlignEnum=ot.FontEnum=void 0;var iy;(function(e){e.D2Coding="D2Coding",e.MaruBuri="MaruBuri",e.NanumGothic="NanumGothic",e.Poppins="Poppins",e.PoppinsLight="PoppinsLight",e.PoppinsMedium="PoppinsMedium",e.PoppinsSemiBold="PoppinsSemiBold",e.PoppinsBold="PoppinsBold"})(iy||(ot.FontEnum=iy={}));var ay;(function(e){e.Left="left",e.Center="center",e.Right="right"})(ay||(ot.TextAlignEnum=ay={}));var OC=DC(Qe()),An;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(An||(ot.ContentType=An={}));var ia=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=OC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/image-factory"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===An.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===An.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==An.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};ot.HttpClient=ia;var El=class extends ia{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});postImageFactoryCreate=(t,r={})=>this.request({path:"/image-factory/create",method:"POST",body:t,type:An.Json,format:"json",...r})};ot.Api=El});var bl=P(Vt=>{"use strict";p();var CC=Vt&&Vt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vt,"__esModule",{value:!0});Vt.error=Vt.warn=Vt.log=void 0;var NC=CC(gn()),aa=(0,NC.default)("api-client");aa.log=console.log.bind(console);var LC=aa.extend("log");Vt.log=LC;var oy=aa.extend("warn");Vt.warn=oy;oy.log=console.warn.bind(console);var cy=aa.extend("error");Vt.error=cy;cy.log=console.error.bind(console)});var xl=P(wt=>{"use strict";p();var kC=wt&&wt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(wt,"__esModule",{value:!0});wt.Api=wt.HttpClient=wt.ContentType=wt.EntityType=void 0;var ly;(function(e){e.MISSION_GROUP="MISSION_GROUP",e.INVENTORY_ITEM="INVENTORY_ITEM"})(ly||(wt.EntityType=ly={}));var MC=kC(Qe()),Ts;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Ts||(wt.ContentType=Ts={}));var oa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=MC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/push"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Ts.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Ts.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Ts.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};wt.HttpClient=oa;var vl=class extends oa{deleteV1EntityNotificationsById=(t,r={})=>this.request({path:`/v1/entity-notifications/${t}`,method:"DELETE",secure:!0,format:"json",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getV1EntityNotifications=(t,r={})=>this.request({path:"/v1/entity-notifications",method:"GET",query:t,secure:!0,format:"json",...r})};wt.Api=vl});var Al=P(v=>{"use strict";p();var UC=v&&v.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(v,"__esModule",{value:!0});v.PreparedLeaseTokenPrototypeDtoTokenTypeEnum=v.PreparedLeaseTokenPrototypeDtoTokenStandardEnum=v.PreparedLeaseTokenPrototypeDtoStatusEnum=v.PaymentInfoStatus=v.PaymentEventType=v.PaymentEventCurrency=v.PaymentEventChannel=v.PayerStatus=v.OrderStatus=v.OperatorActionType=v.OperatorActionStatus=v.OnchainTransactionType=v.OnchainTransactionStatus=v.OnchainStatus=v.OnchainEntityType=v.NftType=v.NftLeaseStatus=v.MusubiTransactionTypeFilter=v.MusubiIncomesCurrency=v.ListingSortBy=v.LeaseIssueStrategy=v.LeaseDetailByMaturityDateDtoCurrencyEnum=v.LeaseCompanyPeriods=v.KycStatus=v.InvoiceSavedStatus=v.InvoicePaymentStatus=v.InvestorStatus=v.InitiateRedeemResultStatus=v.GuarantorVaultTransactionType=v.GuarantorVaultTransactionStatus=v.GuarantorVaultToken=v.GuarantorStatus=v.GuaranteePositionStatus=v.GetV2JpRwaVehicleNftsParamsTypeEnum=v.GetV1GarageExportCsvParamsLangEnum=v.GetNftsSortBy=v.GetMarketListingParamsSortOrderEnum=v.DepreciationMethod=v.DataProvisionConsent=v.Currency=v.ContractStatus=v.ContractPaymentScheduleType=v.ContractPaymentFrequency=v.ContractPayerConfirmation=v.ContractCurrency=v.ClassifiedTransactionType=v.BlockchainNetwork=v.ArPaymentMethod=v.ArB2BTokenStatus=v.AmlStatus=void 0;v.Api=v.HttpClient=v.ContentType=v.XAxisInterval=v.VehicleTokenType=v.VehicleStatus=v.VehicleProductCategory=v.VehicleOdometerHistoryDtoTypeEnum=v.VehicleOdometerHistoryDtoPeriodEnum=v.VehicleAssetStockStatus=v.TransferTokenResponseDtoTokenTypeEnum=v.TransferTokenResponseDtoTokenStandardEnum=v.TransferTokenRequestDtoVersionEnum=v.TokenType=v.TokenStatus=v.TokenPrototypeDtoTokenTypeEnum=v.TokenPrototypeDtoTokenStandardEnum=v.TokenPrototypeDtoStatusEnum=v.TermsConsent=v.SupportedLanguage=v.Strategy=v.StatisticsPeriod=v.SortOrder=v.SettlementPeriodType=v.SellerStatus=v.RwaNoticeTag=v.RwaNoticeStatus=v.RwaNoticeCategory=v.ReverifyPurchaseOutcome=v.RegisteredBy=v.RedeemStatus=v.RedeemMode=v.PurchaseType=v.PurchaseTransactionStatus=v.PreparedOwnershipTokenPrototypeDtoTokenTypeEnum=v.PreparedOwnershipTokenPrototypeDtoTokenStandardEnum=v.PreparedOwnershipTokenPrototypeDtoStatusEnum=void 0;var uy;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(uy||(v.AmlStatus=uy={}));var dy;(function(e){e.HELD="HELD",e.MATURED="MATURED",e.REDEEMED="REDEEMED"})(dy||(v.ArB2BTokenStatus=dy={}));var py;(function(e){e.FIAT_SELLER="FIAT_SELLER",e.TADA="TADA",e.WALLET="WALLET",e.GUARANTOR="GUARANTOR"})(py||(v.ArPaymentMethod=py={}));var my;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(my||(v.BlockchainNetwork=my={}));var fy;(function(e){e.PURCHASE="PURCHASE",e.RETURN="RETURN",e.RECEIVED="RECEIVED",e.SENT="SENT",e.APPROVE="APPROVE",e.MINT="MINT",e.UNKNOWN="UNKNOWN"})(fy||(v.ClassifiedTransactionType=fy={}));var gy;(function(e){e.USD="USD",e.USDC="USDC",e.JPYC="JPYC"})(gy||(v.ContractCurrency=gy={}));var hy;(function(e){e.RECEIVED="RECEIVED",e.PENDING="PENDING",e.REJECTED="REJECTED"})(hy||(v.ContractPayerConfirmation=hy={}));var yy;(function(e){e.WEEKLY="WEEKLY",e.MONTHLY="MONTHLY",e.QUARTERLY="QUARTERLY",e.YEARLY="YEARLY"})(yy||(v.ContractPaymentFrequency=yy={}));var _y;(function(e){e.FIXED_DATE="FIXED_DATE",e.CUSTOM_DATE="CUSTOM_DATE"})(_y||(v.ContractPaymentScheduleType=_y={}));var Ey;(function(e){e.DRAFT="DRAFT",e.DELETED="DELETED",e.INVOICE_GENERATED="INVOICE_GENERATED",e.GUARANTEE_REGISTERED="GUARANTEE_REGISTERED",e.CLOSED="CLOSED"})(Ey||(v.ContractStatus=Ey={}));var Ty;(function(e){e.USD="USD",e.USDC="USDC",e.MVL="MVL",e.JPY="JPY",e.BTC="BTC"})(Ty||(v.Currency=Ty={}));var by;(function(e){e.RECEIVED="RECEIVED",e.WAITING="WAITING",e.REJECTED="REJECTED"})(by||(v.DataProvisionConsent=by={}));var vy;(function(e){e.FLAT_RATE="FLAT_RATE"})(vy||(v.DepreciationMethod=vy={}));var xy;(function(e){e.Asc="asc",e.Desc="desc"})(xy||(v.GetMarketListingParamsSortOrderEnum=xy={}));var Ry;(function(e){e.MATURITY="MATURITY",e.VEHICLE_STATUS="VEHICLE_STATUS"})(Ry||(v.GetNftsSortBy=Ry={}));var Ay;(function(e){e.En="en",e.Jp="jp"})(Ay||(v.GetV1GarageExportCsvParamsLangEnum=Ay={}));var wy;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(wy||(v.GetV2JpRwaVehicleNftsParamsTypeEnum=wy={}));var Sy;(function(e){e.DRAFT="DRAFT",e.CONFIRMED="CONFIRMED",e.ONCHAIN_SUCCESS="ONCHAIN_SUCCESS"})(Sy||(v.GuaranteePositionStatus=Sy={}));var Iy;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.PENDING="PENDING",e.REJECTED="REJECTED",e.DELETED="DELETED"})(Iy||(v.GuarantorStatus=Iy={}));var Py;(function(e){e.USDC="USDC",e.MVL="MVL"})(Py||(v.GuarantorVaultToken=Py={}));var Dy;(function(e){e.PENDING="PENDING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(Dy||(v.GuarantorVaultTransactionStatus=Dy={}));var Oy;(function(e){e.DEPOSIT="DEPOSIT",e.WITHDRAWAL="WITHDRAWAL"})(Oy||(v.GuarantorVaultTransactionType=Oy={}));var Cy;(function(e){e.QUEUED="QUEUED"})(Cy||(v.InitiateRedeemResultStatus=Cy={}));var Ny;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.REJECTED="REJECTED"})(Ny||(v.InvestorStatus=Ny={}));var Ly;(function(e){e.UNPAID="UNPAID",e.PARTIALLY_PAID="PARTIALLY_PAID",e.OVERDUE="OVERDUE",e.MISSED="MISSED",e.PAID="PAID",e.DEFAULTED="DEFAULTED"})(Ly||(v.InvoicePaymentStatus=Ly={}));var ky;(function(e){e.DRAFT="DRAFT",e.CONFIRMED="CONFIRMED",e.LISTED="LISTED",e.PARTIALLY_FUNDED="PARTIALLY_FUNDED",e.SOLD_OUT="SOLD_OUT"})(ky||(v.InvoiceSavedStatus=ky={}));var My;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(My||(v.KycStatus=My={}));var Uy;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(Uy||(v.LeaseCompanyPeriods=Uy={}));var Fy;(function(e){e.USD="USD",e.BTC="BTC"})(Fy||(v.LeaseDetailByMaturityDateDtoCurrencyEnum=Fy={}));var jy;(function(e){e.SINGLE="SINGLE",e.FRACTIONAL="FRACTIONAL"})(jy||(v.LeaseIssueStrategy=jy={}));var qy;(function(e){e.CreatedAt="createdAt",e.FaceValue="faceValue",e.DueDate="dueDate"})(qy||(v.ListingSortBy=qy={}));var By;(function(e){e.USD="USD",e.MVL="MVL",e.BTC="BTC"})(By||(v.MusubiIncomesCurrency=By={}));var Vy;(function(e){e.PURCHASE="PURCHASE",e.RETURN="RETURN",e.RECEIVED="RECEIVED",e.SENT="SENT",e.APPROVE="APPROVE",e.MINT="MINT",e.UNKNOWN="UNKNOWN",e.ALL="ALL"})(Vy||(v.MusubiTransactionTypeFilter=Vy={}));var Gy;(function(e){e.NOT_STARTED="NOT_STARTED",e.ACTIVE="ACTIVE",e.EXPIRED="EXPIRED",e.CLAIMED="CLAIMED"})(Gy||(v.NftLeaseStatus=Gy={}));var Hy;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(Hy||(v.NftType=Hy={}));var $y;(function(e){e.SELLER="SELLER",e.PAYER="PAYER",e.GUARANTOR="GUARANTOR",e.GUARANTEE_POSITION="GUARANTEE_POSITION",e.INVOICE="INVOICE",e.SELLER_SETTLEMENT="SELLER_SETTLEMENT"})($y||(v.OnchainEntityType=$y={}));var Wy;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(Wy||(v.OnchainStatus=Wy={}));var Jy;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED",e.PERMANENTLY_FAILED="PERMANENTLY_FAILED"})(Jy||(v.OnchainTransactionStatus=Jy={}));var Ky;(function(e){e.REGISTER="REGISTER",e.UPDATE_STATUS="UPDATE_STATUS",e.IPFS_UPLOAD="IPFS_UPLOAD",e.SC_REGISTER="SC_REGISTER",e.SETTLE="SETTLE",e.INITIATE_REDEEM="INITIATE_REDEEM",e.PAYMENT_SYNC="PAYMENT_SYNC"})(Ky||(v.OnchainTransactionType=Ky={}));var Yy;(function(e){e.IDLE="IDLE",e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"})(Yy||(v.OperatorActionStatus=Yy={}));var zy;(function(e){e.GUARANTOR_DEPOSIT="GUARANTOR_DEPOSIT",e.PURCHASE="PURCHASE",e.REDEEM="REDEEM",e.PAYMENT="PAYMENT"})(zy||(v.OperatorActionType=zy={}));var Xy;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.CANCELLED="CANCELLED",e.REFUNDED="REFUNDED",e.PENDING_RESTOCK="PENDING_RESTOCK",e.FAILED="FAILED"})(Xy||(v.OrderStatus=Xy={}));var Qy;(function(e){e.ACTIVE="ACTIVE",e.PENDING="PENDING",e.REJECTED="REJECTED"})(Qy||(v.PayerStatus=Qy={}));var Zy;(function(e){e.ADMIN_CSV="ADMIN_CSV",e.ADMIN_MANUAL="ADMIN_MANUAL",e.AUTO_GENERATED="AUTO_GENERATED"})(Zy||(v.PaymentEventChannel=Zy={}));var e_;(function(e){e.USD="USD",e.USDC="USDC"})(e_||(v.PaymentEventCurrency=e_={}));var t_;(function(e){e.PAID="PAID",e.OVERDUE="OVERDUE",e.MISSED="MISSED",e.DEFAULTED="DEFAULTED"})(t_||(v.PaymentEventType=t_={}));var r_;(function(e){e.VERIFICATION_REQUIRED="VERIFICATION_REQUIRED",e.COMFIRMED="COMFIRMED",e.FAILED="FAILED"})(r_||(v.PaymentInfoStatus=r_={}));var n_;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(n_||(v.PreparedLeaseTokenPrototypeDtoStatusEnum=n_={}));var s_;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(s_||(v.PreparedLeaseTokenPrototypeDtoTokenStandardEnum=s_={}));var i_;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(i_||(v.PreparedLeaseTokenPrototypeDtoTokenTypeEnum=i_={}));var a_;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(a_||(v.PreparedOwnershipTokenPrototypeDtoStatusEnum=a_={}));var o_;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(o_||(v.PreparedOwnershipTokenPrototypeDtoTokenStandardEnum=o_={}));var c_;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(c_||(v.PreparedOwnershipTokenPrototypeDtoTokenTypeEnum=c_={}));var l_;(function(e){e.PENDING="PENDING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e.VERIFICATION_FAILED="VERIFICATION_FAILED"})(l_||(v.PurchaseTransactionStatus=l_={}));var u_;(function(e){e.OWNERSHIP="OWNERSHIP",e.FRACTIONAL="FRACTIONAL"})(u_||(v.PurchaseType=u_={}));var d_;(function(e){e.MANUAL="MANUAL",e.AUTO="AUTO"})(d_||(v.RedeemMode=d_={}));var p_;(function(e){e.REDEEMED="REDEEMED",e.PARTIAL_REDEEM="PARTIAL_REDEEM",e.FAILED="FAILED",e.VERIFICATION_FAILED="VERIFICATION_FAILED"})(p_||(v.RedeemStatus=p_={}));var m_;(function(e){e.SELLER="SELLER",e.OPERATOR="OPERATOR"})(m_||(v.RegisteredBy=m_={}));var f_;(function(e){e.CONFIRMED="CONFIRMED",e.ALREADY_CONFIRMED="ALREADY_CONFIRMED",e.REJECTED="REJECTED"})(f_||(v.ReverifyPurchaseOutcome=f_={}));var g_;(function(e){e.NEW_RELEASE="NEW_RELEASE",e.MEDIA_COVERAGE="MEDIA_COVERAGE",e.ETC="ETC"})(g_||(v.RwaNoticeCategory=g_={}));var h_;(function(e){e.VALID="VALID",e.ABOLISHED="ABOLISHED",e.CLOSED="CLOSED",e.IN_PREPARATION="IN_PREPARATION"})(h_||(v.RwaNoticeStatus=h_={}));var y_;(function(e){e.DOCUMENT="DOCUMENT",e.NOTICE="NOTICE",e.REPORT="REPORT",e.PROMOTION="PROMOTION",e.OTHERS="OTHERS"})(y_||(v.RwaNoticeTag=y_={}));var __;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.REJECTED="REJECTED"})(__||(v.SellerStatus=__={}));var E_;(function(e){e.Year="year",e.Month="month",e.Week="week"})(E_||(v.SettlementPeriodType=E_={}));var T_;(function(e){e.ASC="ASC",e.DESC="DESC"})(T_||(v.SortOrder=T_={}));var b_;(function(e){e.WEEK="WEEK",e.MONTH="MONTH",e.THREE_MONTHS="THREE_MONTHS",e.YEAR="YEAR",e.ALL="ALL"})(b_||(v.StatisticsPeriod=b_={}));var v_;(function(e){e.LINEAR_DECAY="LINEAR_DECAY",e.FIXED_APR="FIXED_APR",e.STEP_DECAY="STEP_DECAY"})(v_||(v.Strategy=v_={}));var x_;(function(e){e.En="en",e.Jp="jp"})(x_||(v.SupportedLanguage=x_={}));var R_;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(R_||(v.TermsConsent=R_={}));var A_;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(A_||(v.TokenPrototypeDtoStatusEnum=A_={}));var w_;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(w_||(v.TokenPrototypeDtoTokenStandardEnum=w_={}));var S_;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(S_||(v.TokenPrototypeDtoTokenTypeEnum=S_={}));var I_;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(I_||(v.TokenStatus=I_={}));var P_;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(P_||(v.TokenType=P_={}));var D_;(function(e){e.V1="v1",e.V2="v2"})(D_||(v.TransferTokenRequestDtoVersionEnum=D_={}));var O_;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(O_||(v.TransferTokenResponseDtoTokenStandardEnum=O_={}));var C_;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(C_||(v.TransferTokenResponseDtoTokenTypeEnum=C_={}));var N_;(function(e){e.TO_BE_PROCURED="TO_BE_PROCURED",e.ON_SALE="ON_SALE",e.PROCESSING="PROCESSING",e.SOLD="SOLD",e.DIRECT_SALES_PLANNING="DIRECT_SALES_PLANNING",e.DIRECT_SALES_CONDITION_CONFIRMED="DIRECT_SALES_CONDITION_CONFIRMED",e.DIRECT_SALES_PROPOSED="DIRECT_SALES_PROPOSED",e.DIRECT_SALES_RESERVED="DIRECT_SALES_RESERVED",e.DIRECT_SALES_SOLD="DIRECT_SALES_SOLD"})(N_||(v.VehicleAssetStockStatus=N_={}));var L_;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(L_||(v.VehicleOdometerHistoryDtoPeriodEnum=L_={}));var k_;(function(e){e.ODOMETER="ODOMETER",e.BATTERY="BATTERY"})(k_||(v.VehicleOdometerHistoryDtoTypeEnum=k_={}));var M_;(function(e){e.TUKTUK="TUKTUK",e.BIKE="BIKE",e.CAR="CAR",e.TRUCK="TRUCK",e.UNKNOWN="UNKNOWN"})(M_||(v.VehicleProductCategory=M_={}));var U_;(function(e){e[e.Value20=20]="Value20",e[e.Value40=40]="Value40",e[e.Value50=50]="Value50",e[e.Value70=70]="Value70"})(U_||(v.VehicleStatus=U_={}));var F_;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(F_||(v.VehicleTokenType=F_={}));var j_;(function(e){e.MONTHLY="MONTHLY",e.QUARTERLY="QUARTERLY",e.BI_ANNUAL="BI_ANNUAL"})(j_||(v.XAxisInterval=j_={}));var FC=UC(Qe()),ht;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(ht||(v.ContentType=ht={}));var ca=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=FC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/musubi"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===ht.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===ht.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==ht.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};v.HttpClient=ca;var Rl=class extends ca{getB2BToken=(t,r={})=>this.request({path:"/b2b/token",method:"GET",query:t,secure:!0,format:"json",...r});getHealth=(t={})=>this.request({path:"/health",method:"GET",format:"json",...t});getInvestor=(t={})=>this.request({path:"/investor",method:"GET",secure:!0,format:"json",...t});getMarketListing=(t,r={})=>this.request({path:"/market/listing",method:"GET",query:t,format:"json",...r});getMarketListingByInvoiceId=(t,r={})=>this.request({path:`/market/listing/${t}`,method:"GET",format:"json",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getOperatorActionByContractId=(t,r={})=>this.request({path:`/operator/action/${t}`,method:"GET",secure:!0,format:"json",...r});getOperatorInvestments=(t,r={})=>this.request({path:"/operator/investments",method:"GET",query:t,secure:!0,format:"json",...r});getOperatorInvestmentsByContractId=(t,r={})=>this.request({path:`/operator/investments/${t}`,method:"GET",secure:!0,format:"json",...r});getPurchaseHistory=(t,r={})=>this.request({path:"/purchase/history",method:"GET",query:t,secure:!0,format:"json",...r});getPurchasePortfolioSummary=(t={})=>this.request({path:"/purchase/portfolio-summary",method:"GET",secure:!0,format:"json",...t});getPurchaseStatus=(t,r={})=>this.request({path:"/purchase/status",method:"GET",query:t,secure:!0,format:"json",...r});getUserConfig=(t={})=>this.request({path:"/user-config",method:"GET",secure:!0,format:"json",...t});getV1GarageExportCsv=(t,r={})=>this.request({path:"/v1/garage/export/csv",method:"GET",query:t,secure:!0,...r});getV1GarageLeaseTokenInfo=(t,r={})=>this.request({path:"/v1/garage/lease-token-info",method:"GET",query:t,secure:!0,format:"json",...r});getV1GarageOwnershipDepreciation=(t,r={})=>this.request({path:"/v1/garage/ownership-depreciation",method:"GET",query:t,secure:!0,format:"json",...r});getV1NftCollections=(t={})=>this.request({path:"/v1/nft/collections",method:"GET",format:"json",...t});getV1Order=(t={})=>this.request({path:"/v1/order",method:"GET",secure:!0,format:"json",...t});getV1OrderById=(t,r={})=>this.request({path:`/v1/order/${t}`,method:"GET",secure:!0,format:"json",...r});getV1OrderUnRevealed=(t={})=>this.request({path:"/v1/order/un-revealed",method:"GET",secure:!0,format:"json",...t});getV1RwaNotice=(t,r={})=>this.request({path:"/v1/rwa-notice",method:"GET",query:t,secure:!0,format:"json",...r});getV1Transactions=(t,r={})=>this.request({path:"/v1/transactions",method:"GET",query:t,secure:!0,format:"json",...r});getV1VehicleProduct=(t,r={})=>this.request({path:"/v1/vehicle-product",method:"GET",query:t,format:"json",...r});getV1VehicleProductByProductId=(t,r,n={})=>this.request({path:`/v1/vehicle-product/${t}`,method:"GET",query:r,format:"json",...n});getV2JpRwaVehicle=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle",method:"GET",query:t,secure:!0,format:"json",...r});getV2JpRwaVehicleAggregatedData=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/aggregated-data",method:"GET",query:t,secure:!0,format:"json",...r});getV2JpRwaVehicleClaimable=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/claimable",method:"GET",query:t,secure:!0,format:"json",...r});getV2JpRwaVehicleCumulativeLeaseFees=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/cumulative-lease-fees",method:"GET",query:t,secure:!0,format:"json",...r});getV2JpRwaVehicleLeaseFeesSummary=(t={})=>this.request({path:"/v2/jp/rwa-vehicle/lease-fees-summary",method:"GET",secure:!0,format:"json",...t});getV2JpRwaVehicleNfts=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/nfts",method:"GET",query:t,secure:!0,format:"json",...r});getV2JpRwaVehicleNftsByTokenId=(t,r,n={})=>this.request({path:`/v2/jp/rwa-vehicle/nfts/${t}`,method:"GET",query:r,secure:!0,format:"json",...n});getV2JpRwaVehicleOdometerHistory=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/odometer-history",method:"GET",query:t,secure:!0,format:"json",...r});getV2RwaIncomes=(t,r={})=>this.request({path:"/v2/rwa/incomes",method:"GET",query:t,secure:!0,format:"json",...r});getV2RwaPublicVehicles=(t,r={})=>this.request({path:"/v2/rwa/public/vehicles",method:"GET",query:t,format:"json",...r});getV2RwaPublicVehiclesDash=(t,r={})=>this.request({path:"/v2/rwa/public/vehicles/dash",method:"GET",query:t,format:"json",...r});getV2RwaVehicle=(t,r={})=>this.request({path:"/v2/rwa-vehicle",method:"GET",query:t,secure:!0,format:"json",...r});getV2RwaVehicleClaimable=(t,r={})=>this.request({path:"/v2/rwa-vehicle/claimable",method:"GET",query:t,secure:!0,format:"json",...r});getV2RwaVehicleRideHailingIncomesByVin=(t,r,n={})=>this.request({path:`/v2/rwa-vehicle/ride-hailing-incomes/${t}`,method:"GET",query:r,secure:!0,format:"json",...n});getV2RwaVehicleStatistics=(t,r={})=>this.request({path:"/v2/rwa-vehicle/statistics",method:"GET",query:t,secure:!0,format:"json",...r});postCustomerServiceContact=(t,r={})=>this.request({path:"/customer-service/contact",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postInvestor=(t={})=>this.request({path:"/investor",method:"POST",secure:!0,format:"json",...t});postOperatorActionConfirmation=(t,r={})=>this.request({path:"/operator/action/confirmation",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postPurchase=(t,r={})=>this.request({path:"/purchase",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postPurchaseRedeem=(t,r={})=>this.request({path:"/purchase/redeem",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postV1Order=(t,r={})=>this.request({path:"/v1/order",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postV1OrderReveal=(t={})=>this.request({path:"/v1/order/reveal",method:"POST",secure:!0,format:"json",...t});postV1TokenTransfer=(t,r={})=>this.request({path:"/v1/token/transfer",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});postV2JpRwaVehicleInvestorMessage=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/investor-message",method:"POST",body:t,secure:!0,type:ht.Json,format:"json",...r});putInvestor=(t,r={})=>this.request({path:"/investor",method:"PUT",body:t,secure:!0,type:ht.Json,format:"json",...r})};v.Api=Rl});var Sl=P(fe=>{"use strict";p();var jC=fe&&fe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fe,"__esModule",{value:!0});fe.Api=fe.HttpClient=fe.ContentType=fe.StockStatus=fe.ProductType=fe.PaymentMethod=fe.OrderStatus=fe.ItemActionType=fe.CouponItemDataTypeEnum=fe.CommonItemDataTypeEnum=fe.CollectionItemDataTypeEnum=void 0;var q_;(function(e){e.COLLECTION="COLLECTION"})(q_||(fe.CollectionItemDataTypeEnum=q_={}));var B_;(function(e){e.COLLECTION="COLLECTION",e.COUPON_CODE="COUPON_CODE"})(B_||(fe.CommonItemDataTypeEnum=B_={}));var V_;(function(e){e.COUPON_CODE="COUPON_CODE"})(V_||(fe.CouponItemDataTypeEnum=V_={}));var G_;(function(e){e.NONE="NONE",e.WEBVIEW="WEBVIEW",e.DAPPVIEW="DAPPVIEW",e.DEEPLINK="DEEPLINK",e.DEEPLINK_WITH_DEFERRED_AUTH="DEEPLINK_WITH_DEFERRED_AUTH"})(G_||(fe.ItemActionType=G_={}));var H_;(function(e){e.DRAFT="DRAFT",e.PAYMENT_PENDING="PAYMENT_PENDING",e.PAYMENT_FAILED="PAYMENT_FAILED",e.CANCEL_REQUESTED="CANCEL_REQUESTED",e.CANCEL_REFUNDED="CANCEL_REFUNDED",e.PAID="PAID",e.SUCCESS="SUCCESS",e.EXPIRED="EXPIRED",e.UNQUALIFIED="UNQUALIFIED"})(H_||(fe.OrderStatus=H_={}));var $_;(function(e){e.BALANCE_TRANSACTION="BALANCE_TRANSACTION"})($_||(fe.PaymentMethod=$_={}));var W_;(function(e){e.ITEM="ITEM",e.REDEEMABLE_ITEM="REDEEMABLE_ITEM"})(W_||(fe.ProductType=W_={}));var J_;(function(e){e.PENDING="PENDING",e.READY="READY",e.USED="USED",e.CANCELED="CANCELED",e.EXPIRED="EXPIRED"})(J_||(fe.StockStatus=J_={}));var qC=jC(Qe()),Br;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Br||(fe.ContentType=Br={}));var la=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=qC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/sale"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Br.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Br.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Br.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};fe.HttpClient=la;var wl=class extends la{deleteV1OrdersById=(t,r={})=>this.request({path:`/v1/orders/${t}`,method:"DELETE",secure:!0,format:"json",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getV1InventoryItems=(t,r={})=>this.request({path:"/v1/inventory/items",method:"GET",query:t,secure:!0,format:"json",...r});getV1InventoryItemsById=(t,r={})=>this.request({path:`/v1/inventory/items/${t}`,method:"GET",secure:!0,format:"json",...r});getV1OrdersById=(t,r={})=>this.request({path:`/v1/orders/${t}`,method:"GET",secure:!0,format:"json",...r});getV1ProductsById=(t,r={})=>this.request({path:`/v1/products/${t}`,method:"GET",format:"json",...r});getV1ProductsFeatured=(t={})=>this.request({path:"/v1/products/featured",method:"GET",secure:!0,format:"json",...t});getV1ProductsPublicFeatured=(t={})=>this.request({path:"/v1/products/public/featured",method:"GET",format:"json",...t});getV1SaleCurrencies=(t={})=>this.request({path:"/v1/sale-currencies",method:"GET",format:"json",...t});postV1InventoryItemsGive=(t={})=>this.request({path:"/v1/inventory/items/give",method:"POST",secure:!0,format:"json",...t});postV1Orders=(t,r={})=>this.request({path:"/v1/orders",method:"POST",body:t,secure:!0,type:Br.Json,format:"json",...r});postV1OrdersByIdPayments=(t,r,n={})=>this.request({path:`/v1/orders/${t}/payments`,method:"POST",body:r,secure:!0,type:Br.Json,format:"json",...n})};fe.Api=wl});var Pl=P(ua=>{"use strict";p();Object.defineProperty(ua,"__esModule",{value:!0});ua.BasicSecurityPolicy=void 0;var BC=wn(),Il=class{securityType=BC.SecurityType.BASIC;basicAuthorization;username;password;setSecurityInfo(t){let r=t;if(r.username===void 0||r.password===void 0)throw new Error("username and password are required");this.basicAuthorization=this.generateBasicAuthorization(r.username,r.password),this.username=r.username,this.password=r.password}getSecurityInfo(){return{username:this.username,password:this.password}}clearSecurityInfo(){this.username=void 0,this.password=void 0,this.basicAuthorization=void 0}securityWorker=()=>({headers:{Authorization:this.basicAuthorization}});onApiRejectedInterceptor=void 0;generateBasicAuthorization(t,r){return`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}};ua.BasicSecurityPolicy=Il});var Ol=P(da=>{"use strict";p();Object.defineProperty(da,"__esModule",{value:!0});da.JwtSecurityPolicy=void 0;var VC=wn(),Vr=bl(),Dl=class{securityType=VC.SecurityType.JWT;apiClient;accessToken;refreshToken;promiseRefresh=null;onChangeSecurityData;onRefreshTokenExpired;isUserServiceAvailable(t){return!!t?.services.userService}constructor(t){let{apiClient:r}=t||{};this.apiClient=r,this.onChangeSecurityData=t?.onChangeSecurityData,this.onRefreshTokenExpired=t?.onRefreshTokenExpired}async requestRefreshToken(t){if(!this.isUserServiceAvailable(this.apiClient))throw(0,Vr.error)("missing userService baseUrl"),new Error("[JwtSecurityPolicy] missing userService baseUrl");let{refreshToken:r}=t;if(!r)throw(0,Vr.error)("missing refreshToken!"),new Error("[JwtSecurityPolicy] missing refreshToken");let n=await this.apiClient.user.postV2AccountsSessionsRefresh({secure:!1,headers:{Authorization:`Bearer ${r}`}});return{accessToken:n.accessToken,refreshToken:n.refreshToken}}async requestConfirmRefreshToken(){this.isUserServiceAvailable(this.apiClient)&&await this.apiClient?.user.postV2AccountsSessionsRefreshConfirm()}setSecurityInfo(t){let r=t;this.accessToken=r.accessToken,this.refreshToken=r.refreshToken}getSecurityInfo(){return{accessToken:this.accessToken,refreshToken:this.refreshToken}}clearSecurityInfo(){this.accessToken=void 0,this.refreshToken=void 0}securityWorker=()=>({headers:{Authorization:`Bearer ${this.accessToken}`}});onApiRejectedInterceptor=(t,r)=>async n=>{let s=n.config,i=s?.url,a=n.response?.data?.code,o=n.response?.status;if((0,Vr.warn)("api rejected! url=%s, status=%d, code=%s",i,o,a),s&&this.refreshToken&&o===401&&a==="EXPIRED_SESSION"&&i!=="/v2/accounts/sessions/refresh"){if(this.promiseRefresh)return(0,Vr.warn)("Wait for refreshing token has been processed. url=%s",i),await this.promiseRefresh?(s.headers.Authorization=`Bearer ${this.accessToken}`,t(s)):((0,Vr.error)("Failed to get refreshed token promised. url=%s",i),Promise.reject(n));let c=()=>{};this.promiseRefresh=new Promise(u=>{c=u});try{let u=await this.requestRefreshToken(this.getSecurityInfo()),l={accessToken:u.accessToken,refreshToken:u.refreshToken},d={accessToken:this.accessToken,refreshToken:this.refreshToken};if(this.setSecurityInfo(l),!r)try{await this.requestConfirmRefreshToken()}catch(m){throw this.setSecurityInfo(d),m}return(0,Vr.warn)("Token refreshed. retry request url=%s",i),this.promiseRefresh=null,this.onChangeSecurityData?.(l),s.headers.Authorization=`Bearer ${l.accessToken}`,c(!0),t(s)}catch(u){u.response.status===401&&((0,Vr.error)("Refresh token is expired"),this.clearSecurityInfo(),this.onRefreshTokenExpired?.()),c(!1)}}return Promise.reject(n)}};da.JwtSecurityPolicy=Dl});var Nl=P(pa=>{"use strict";p();Object.defineProperty(pa,"__esModule",{value:!0});pa.PublicSecurityPolicy=void 0;var GC=wn(),Cl=class{securityType=GC.SecurityType.PUBLIC;securityWorker=void 0;setSecurityInfo(t){}getSecurityInfo(){return{}}clearSecurityInfo(){}onApiRejectedInterceptor=void 0};pa.PublicSecurityPolicy=Cl});var wn=P(yt=>{"use strict";p();var HC=yt&&yt.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),kl=yt&&yt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HC(t,e,r)};Object.defineProperty(yt,"__esModule",{value:!0});yt.SecurityPolicyFactory=yt.SecurityType=void 0;var $C=Pl(),WC=Ol(),JC=Nl();kl(Pl(),yt);kl(Ol(),yt);kl(Nl(),yt);var bs;(function(e){e.JWT="jwt-auth",e.BASIC="basic",e.PUBLIC="public"})(bs||(yt.SecurityType=bs={}));var Ll=class{static create(t){switch(t.type){case bs.JWT:return new WC.JwtSecurityPolicy(t);case bs.BASIC:return new $C.BasicSecurityPolicy;case bs.PUBLIC:return new JC.PublicSecurityPolicy;default:throw new Error("Invalid Security Type")}}};yt.SecurityPolicyFactory=Ll});var Ul=P(ct=>{"use strict";p();var KC=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ct,"__esModule",{value:!0});ct.Api=ct.HttpClient=ct.ContentType=ct.StatisticsTokenType=ct.BlockchainNetwork=void 0;var K_;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(K_||(ct.BlockchainNetwork=K_={}));var Y_;(function(e){e.LP="LP"})(Y_||(ct.StatisticsTokenType=Y_={}));var YC=KC(Qe()),vs;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(vs||(ct.ContentType=vs={}));var ma=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=YC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/statistics"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===vs.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===vs.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==vs.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};ct.HttpClient=ma;var Ml=class extends ma{getHealth=(t={})=>this.request({path:"/health",method:"GET",format:"json",...t});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t})};ct.Api=Ml});var jl=P(G=>{"use strict";p();var zC=G&&G.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(G,"__esModule",{value:!0});G.Api=G.HttpClient=G.ContentType=G.WalletProviderId=G.TadaTonTipRequestStatus=G.TadaRegion=G.TadaCity=G.SendVerificationCodeStatus=G.RideRequestReceiptStatus=G.RideRequestDetailResponseDtoStatusEnum=G.RideHistoryStatus=G.RecommendPlaceType=G.PutMapSessionResultDtoStatusEnum=G.PlaceMatchType=G.PaymentMethod=G.PartnerRestrictType=G.PartnerDisclaimerType=G.DiscountType=G.DepositRelayRequestStatus=G.CouponDiscountType=G.ChatSenderType=G.ChatMessageType=G.CarType=G.BlockchainNetwork=G.AllowanceType=void 0;var z_;(function(e){e.BOTH="BOTH",e.ONLY_PICKUP="ONLY_PICKUP",e.ONLY_DROPOFF="ONLY_DROPOFF"})(z_||(G.AllowanceType=z_={}));var X_;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(X_||(G.BlockchainNetwork=X_={}));var Q_;(function(e){e[e.Value0=0]="Value0",e[e.Value01=0]="Value01",e[e.Value1=1]="Value1",e[e.Value12=1]="Value12",e[e.Value4=4]="Value4",e[e.Value43=4]="Value43",e[e.Value11=11]="Value11",e[e.Value124=12]="Value124",e[e.Value13=13]="Value13",e[e.Value135=13]="Value135",e[e.Value21=21]="Value21",e[e.Value31=31]="Value31",e[e.Value32=32]="Value32",e[e.Value33=33]="Value33",e[e.Value34=34]="Value34",e[e.Value35=35]="Value35",e[e.Value1000=1e3]="Value1000",e[e.Value1001=1001]="Value1001",e[e.Value1002=1002]="Value1002",e[e.Value1003=1003]="Value1003",e[e.Value1004=1004]="Value1004",e[e.Value1005=1005]="Value1005",e[e.Value2000=2e3]="Value2000",e[e.Value3000=3e3]="Value3000",e[e.Value3001=3001]="Value3001",e[e.Value10000=1e4]="Value10000",e[e.Value10001=10001]="Value10001",e[e.Value10002=10002]="Value10002",e[e.Value10003=10003]="Value10003",e[e.Value20000=2e4]="Value20000",e[e.Value20001=20001]="Value20001",e[e.Value20002=20002]="Value20002",e[e.Value30000=3e4]="Value30000",e[e.Value40000=4e4]="Value40000"})(Q_||(G.CarType=Q_={}));var Z_;(function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.SYSTEM="SYSTEM"})(Z_||(G.ChatMessageType=Z_={}));var eE;(function(e){e.RIDER="RIDER",e.DRIVER="DRIVER",e.ADMIN="ADMIN",e.SYSTEM="SYSTEM"})(eE||(G.ChatSenderType=eE={}));var tE;(function(e){e.RATE="RATE",e.AMOUNT="AMOUNT",e.TARGET="TARGET"})(tE||(G.CouponDiscountType=tE={}));var rE;(function(e){e.PENDING="PENDING",e.SUBMITTED="SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(rE||(G.DepositRelayRequestStatus=rE={}));var nE;(function(e){e.FIXED="FIXED",e.PERCENTAGE="PERCENTAGE"})(nE||(G.DiscountType=nE={}));var sE;(function(e){e.NO_WAITING="NO_WAITING"})(sE||(G.PartnerDisclaimerType=sE={}));var iE;(function(e){e.BOTH="BOTH",e.ONLY_PICKUP="ONLY_PICKUP",e.ONLY_DROPOFF="ONLY_DROPOFF"})(iE||(G.PartnerRestrictType=iE={}));var aE;(function(e){e.BASE_PAY="BASE_PAY",e.X402="X402"})(aE||(G.PaymentMethod=aE={}));var oE;(function(e){e.Exact="exact",e.Approximate="approximate"})(oE||(G.PlaceMatchType=oE={}));var cE;(function(e){e.JwtExpired="jwt_expired",e.Cancelled="cancelled"})(cE||(G.PutMapSessionResultDtoStatusEnum=cE={}));var lE;(function(e){e.DEPARTURE="DEPARTURE",e.DESTINATION="DESTINATION",e.ALL="ALL"})(lE||(G.RecommendPlaceType=lE={}));var uE;(function(e){e.Pending="pending",e.InProgress="in_progress",e.Completed="completed",e.RiderCancelled="rider_cancelled",e.DriverCancelled="driver_cancelled",e.Error="error"})(uE||(G.RideHistoryStatus=uE={}));var dE;(function(e){e.WAITPAY="WAITPAY",e.PAYCONFIRMED="PAYCONFIRMED",e.NOT_MATCHED="NOT_MATCHED",e.MATCHED="MATCHED",e.CONFIRMED="CONFIRMED",e.PENDING="PENDING",e.ASSIGNED="ASSIGNED",e.PICKUP="PICKUP",e.PICKUP_ARRIVED="PICKUP_ARRIVED",e.INUSE="INUSE",e.INUSE_WITH_CANCEL_PENDING="INUSE_WITH_CANCEL_PENDING",e.FINISHED="FINISHED",e.USER_CANCELED="USER_CANCELED",e.USER_CANCELED_BEFORE_CALL="USER_CANCELED_BEFORE_CALL",e.USER_CANCELED_NO_FREE="USER_CANCELED_NO_FREE",e.COMPANY_CANCELED="COMPANY_CANCELED",e.COMPANY_CANCELED_RECALLABLE="COMPANY_CANCELED_RECALLABLE",e.DRIVER_CANCELED="DRIVER_CANCELED",e.DRIVER_CANCELED_RECALLABLE="DRIVER_CANCELED_RECALLABLE",e.EXPIRED="EXPIRED",e.EXPIRED_RECALLABLE="EXPIRED_RECALLABLE",e.EXPIRED_BEFORE_PAY="EXPIRED_BEFORE_PAY",e.ERROR_PAYMENT="ERROR_PAYMENT",e.ERROR="ERROR"})(dE||(G.RideRequestDetailResponseDtoStatusEnum=dE={}));var pE;(function(e){e.PENDING="PENDING",e.PAID="PAID",e.FINISHED="FINISHED",e.EXPIRED="EXPIRED",e.FAILED="FAILED",e.REFUND_PENDING="REFUND_PENDING",e.REFUND_PROCESSING="REFUND_PROCESSING",e.REFUND_FAILED="REFUND_FAILED",e.REFUNDED="REFUNDED"})(pE||(G.RideRequestReceiptStatus=pE={}));var mE;(function(e){e.SUCCESS="SUCCESS",e.ALREADY_VERIFIED="ALREADY_VERIFIED"})(mE||(G.SendVerificationCodeStatus=mE={}));var fE;(function(e){e.SIN="SIN",e.HAN="HAN",e.HCM="HCM",e.PNH="PNH",e.REP="REP",e.SEL="SEL",e.ADD="ADD",e.JKT="JKT",e.HKG="HKG",e.BKK="BKK",e.SHV="SHV",e.KPK="KPK",e.DEN="DEN",e.NYC="NYC"})(fE||(G.TadaCity=fE={}));var gE;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.JP="JP",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(gE||(G.TadaRegion=gE={}));var hE;(function(e){e.WAIT_PAY="WAIT_PAY",e.CLIENT_PAY_CONFIRMED="CLIENT_PAY_CONFIRMED",e.TX_CONFIRMED="TX_CONFIRMED",e.REQUESTED="REQUESTED",e.REQUEST_FAILED="REQUEST_FAILED",e.TIP_STATUS_UPDATED="TIP_STATUS_UPDATED",e.COMPLETED="COMPLETED",e.EXPIRED="EXPIRED",e.PAYMENT_CONFIRM_ERROR="PAYMENT_CONFIRM_ERROR"})(hE||(G.TadaTonTipRequestStatus=hE={}));var yE;(function(e){e.NONE="NONE",e.TON_CONNECT="TON_CONNECT",e.TON_CONNECT_TEST="TON_CONNECT_TEST",e.OKX_CONNECT_BSC="OKX_CONNECT_BSC",e.OKX_CONNECT_ETHEREUM="OKX_CONNECT_ETHEREUM",e.OKX_CONNECT_ETHEREUM_SEPOLIA="OKX_CONNECT_ETHEREUM_SEPOLIA",e.WALLET_CONNECT_ETHEREUM="WALLET_CONNECT_ETHEREUM",e.WALLET_CONNECT_ETHEREUM_SEPOLIA="WALLET_CONNECT_ETHEREUM_SEPOLIA",e.WALLET_CONNECT_BSC="WALLET_CONNECT_BSC",e.WALLET_CONNECT_BSC_TEST="WALLET_CONNECT_BSC_TEST",e.BITGET_CONNECT_BSC="BITGET_CONNECT_BSC",e.BASE_PAY_BASE="BASE_PAY_BASE",e.BASE_PAY_BASE_SEPOLIA="BASE_PAY_BASE_SEPOLIA"})(yE||(G.WalletProviderId=yE={}));var XC=zC(Qe()),Le;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Le||(G.ContentType=Le={}));var fa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=XC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/tada-ton"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===Le.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Le.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==Le.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};G.HttpClient=fa;var Fl=class extends fa{getHealth=(t={})=>this.request({path:"/health",method:"GET",format:"json",...t});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getTipConfig=(t,r={})=>this.request({path:"/tip/config",method:"GET",query:t,secure:!0,format:"json",...r});getV1AgentDepositExchangeRate=(t,r={})=>this.request({path:"/v1/agent-deposit/exchange-rate",method:"GET",query:t,secure:!0,format:"json",...r});getV1AgentDepositRelayByRequestId=(t,r={})=>this.request({path:`/v1/agent-deposit/relay/${t}`,method:"GET",secure:!0,format:"json",...r});getV1AgentDepositRelayCapabilities=(t={})=>this.request({path:"/v1/agent-deposit/relay-capabilities",method:"GET",secure:!0,format:"json",...t});getV1BalancePointByRegion=(t,r={})=>this.request({path:`/v1/balance/point/${t}`,method:"GET",secure:!0,format:"json",...r});getV1ChatByRideRequestIdMessages=(t,r,n={})=>this.request({path:`/v1/chat/${t}/messages`,method:"GET",query:r,secure:!0,format:"json",...n});getV1ChatByRideRequestIdMessagesByMessageIdTranslation=(t,r,n,s={})=>this.request({path:`/v1/chat/${t}/messages/${r}/translation`,method:"GET",query:n,secure:!0,format:"json",...s});getV1ChatByRideRequestIdUnreadCount=(t,r={})=>this.request({path:`/v1/chat/${t}/unread-count`,method:"GET",secure:!0,format:"json",...r});getV1Currency=(t={})=>this.request({path:"/v1/currency",method:"GET",secure:!0,format:"json",...t});getV1CurrencyByRegion=(t,r={})=>this.request({path:`/v1/currency/${t}`,method:"GET",secure:!0,format:"json",...r});getV1MapSessionBySessionId=(t,r={})=>this.request({path:`/v1/map-session/${t}`,method:"GET",...r});getV1MapSessionBySessionIdResult=(t,r={})=>this.request({path:`/v1/map-session/${t}/result`,method:"GET",format:"json",...r});getV1PhoneVerificationCheck=(t,r={})=>this.request({path:"/v1/phone-verification/check",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesAirports=(t,r={})=>this.request({path:"/v1/places/airports",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesAttributeByList=(t,r={})=>this.request({path:"/v1/places/attribute-by-list",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesBookmarks=(t,r={})=>this.request({path:"/v1/places/bookmarks",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesById=(t,r={})=>this.request({path:`/v1/places/${t}`,method:"GET",secure:!0,format:"json",...r});getV1PlacesNearby=(t,r={})=>this.request({path:"/v1/places/nearby",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesRecommend=(t,r={})=>this.request({path:"/v1/places/recommend",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesRegionsCurrent=(t,r={})=>this.request({path:"/v1/places/regions/current",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesReverseGeo=(t,r={})=>this.request({path:"/v1/places/reverse-geo",method:"GET",query:t,secure:!0,format:"json",...r});getV1PlacesSearch=(t,r={})=>this.request({path:"/v1/places/search",method:"GET",query:t,secure:!0,format:"json",...r});getV1RidesCancelStatus=(t={})=>this.request({path:"/v1/rides/cancel-status",method:"GET",secure:!0,format:"json",...t});getV1RidesRequestActive=(t={})=>this.request({path:"/v1/rides/request/active",method:"GET",secure:!0,format:"json",...t});getV1RidesRequestById=(t,r={})=>this.request({path:`/v1/rides/request/${t}`,method:"GET",secure:!0,format:"json",...r});getV1RidesRequestByIdPreRequest=(t,r={})=>this.request({path:`/v1/rides/request/${t}/pre-request`,method:"GET",secure:!0,format:"json",...r});getV1WalletProviderByRegion=(t,r={})=>this.request({path:`/v1/wallet-provider/${t}`,method:"GET",secure:!0,format:"json",...r});getV2PlacesAutocomplete=(t,r={})=>this.request({path:"/v2/places/autocomplete",method:"GET",query:t,secure:!0,format:"json",...r});getV2PlacesRestrictedAreas=(t,r={})=>this.request({path:"/v2/places/restricted-areas",method:"GET",query:t,secure:!0,format:"json",...r});getV2RideHistories=(t,r={})=>this.request({path:"/v2/ride-histories",method:"GET",query:t,secure:!0,format:"json",...r});getV2RideHistoriesByRideRequestIdReceiptPdf=(t,r={})=>this.request({path:`/v2/ride-histories/${t}/receipt-pdf`,method:"GET",secure:!0,...r});getV2RideHistoriesDetailByRideRequestId=(t,r={})=>this.request({path:`/v2/ride-histories/detail/${t}`,method:"GET",secure:!0,format:"json",...r});getV2RidesRequestByIdCancelReasons=(t,r={})=>this.request({path:`/v2/rides/request/${t}/cancel-reasons`,method:"GET",secure:!0,format:"json",...r});postPaymentRide=(t={})=>this.request({path:"/payment/ride",method:"POST",secure:!0,format:"json",...t});postPaymentTip=(t={})=>this.request({path:"/payment/tip",method:"POST",secure:!0,format:"json",...t});postV1AgentDepositPriceQuote=(t,r={})=>this.request({path:"/v1/agent-deposit/price-quote",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1AgentDepositRelay=(t,r={})=>this.request({path:"/v1/agent-deposit/relay",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1AuthLogin=(t,r={})=>this.request({path:"/v1/auth/login",method:"POST",body:t,type:Le.Json,format:"json",...r});postV1ChatByRideRequestIdImage=(t,r,n={})=>this.request({path:`/v1/chat/${t}/image`,method:"POST",body:r,secure:!0,type:Le.FormData,format:"json",...n});postV1MapSession=(t,r={})=>this.request({path:"/v1/map-session",method:"POST",body:t,secure:!0,type:Le.Json,...r});postV1PhoneVerificationConfirm=(t,r={})=>this.request({path:"/v1/phone-verification/confirm",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1PhoneVerificationSendCode=(t,r={})=>this.request({path:"/v1/phone-verification/send-code",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1PlacesBookmarksByPlaceId=(t,r={})=>this.request({path:`/v1/places/bookmarks/${t}`,method:"POST",secure:!0,format:"json",...r});postV1PlacesResolveGoogle=(t,r={})=>this.request({path:"/v1/places/resolve-google",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1RidesRequestByIdCancelWait=(t,r={})=>this.request({path:`/v1/rides/request/${t}/cancel-wait`,method:"POST",secure:!0,format:"json",...r});postV1RidesRequestByIdReTry=(t,r={})=>this.request({path:`/v1/rides/request/${t}/re-try`,method:"POST",secure:!0,format:"json",...r});postV2RidesBaseSearch=(t,r={})=>this.request({path:"/v2/rides/base-search",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV2RidesPreRequest=(t,r={})=>this.request({path:"/v2/rides/pre-request",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV2RidesRequestByIdCancel=(t,r,n={})=>this.request({path:`/v2/rides/request/${t}/cancel`,method:"POST",body:r,secure:!0,type:Le.Json,format:"json",...n});postV2RidesRequestByIdTipPayReport=(t,r,n={})=>this.request({path:`/v2/rides/request/${t}/tip/pay-report`,method:"POST",body:r,secure:!0,type:Le.Json,format:"json",...n});postV2RidesRequestByIdTipPreRequest=(t,r,n={})=>this.request({path:`/v2/rides/request/${t}/tip/pre-request`,method:"POST",body:r,secure:!0,type:Le.Json,format:"json",...n});putV1MapSessionBySessionIdResult=(t,r,n={})=>this.request({path:`/v1/map-session/${t}/result`,method:"PUT",body:r,type:Le.Json,...n})};G.Api=Fl});var Bl=P(C=>{"use strict";p();var QC=C&&C.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(C,"__esModule",{value:!0});C.Api=C.HttpClient=C.ContentType=C.WalletStatus=C.VerifiedWalletType=C.UserIdentifierType=C.TokenType=C.ThirdPartySupportedCurrency=C.ThirdPartyIntegrationStatus=C.TadaRegion=C.TadaPointRequestType=C.TadaPointRequestStatus=C.TadaPointActionType=C.TadaPointActionStatus=C.SendTxWalletResultKind=C.SendCallsWalletResultKind=C.QuoteDtoTypeEnum=C.QuorumWalletSessionStatus=C.PurchasableType=C.PurchasablePayMethod=C.PrivyTransactionStatus=C.PartnerType=C.Oauth2TokenType=C.MobileOs=C.KnownAuthClients=C.ForClutchUserIdentifierType=C.EarnEventClaimType=C.EarnEventClaimStatus=C.DepositTrustedDtoTypeEnum=C.CosignSignMethod=C.BlockchainNetwork=C.BalanceSwapType=C.BalanceRequestStatus=C.AppStateEnum=C.AppEventStateResponseDtoStateEnum=void 0;var _E;(function(e){e.REQUIRED="REQUIRED",e.OPTIONAL="OPTIONAL",e.LATEST="LATEST"})(_E||(C.AppEventStateResponseDtoStateEnum=_E={}));var EE;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE"})(EE||(C.AppStateEnum=EE={}));var TE;(function(e){e.INCOMING="INCOMING",e.CONFIRMING="CONFIRMING",e.WAITING_TRANSACTION="WAITING_TRANSACTION",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e.FAILED="FAILED",e.IN_MIGRATION="IN_MIGRATION"})(TE||(C.BalanceRequestStatus=TE={}));var bE;(function(e){e.WITHDRAWAL="WITHDRAWAL",e.DEPOSIT="DEPOSIT"})(bE||(C.BalanceSwapType=bE={}));var vE;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(vE||(C.BlockchainNetwork=vE={}));var xE;(function(e){e.PersonalSign="personal_sign",e.EthSignTypedDataV4="eth_signTypedData_v4"})(xE||(C.CosignSignMethod=xE={}));var RE;(function(e){e.TADA_POINT_TELEGRAM="TADA_POINT_TELEGRAM"})(RE||(C.DepositTrustedDtoTypeEnum=RE={}));var AE;(function(e){e.INCOMING="INCOMING",e.COMPLETED_TRANSFER="COMPLETED_TRANSFER",e.FAILED_TRANSFER="FAILED_TRANSFER",e.FAILED_WITHDRAW="FAILED_WITHDRAW",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED"})(AE||(C.EarnEventClaimStatus=AE={}));var wE;(function(e){e.CONSTANT="CONSTANT",e.RATIO_DIVISION="RATIO_DIVISION"})(wE||(C.EarnEventClaimType=wE={}));var SE;(function(e){e.GOOGLE="GOOGLE",e.APPLE="APPLE"})(SE||(C.ForClutchUserIdentifierType=SE={}));var IE;(function(e){e.Clutch="Clutch",e.DemocopterWeb="DemocopterWeb",e.DemocopterApp="DemocopterApp",e.DemocopterPaymentRedirection="DemocopterPaymentRedirection",e.DiscordRedirection="DiscordRedirection",e.Web3Verification="Web3Verification",e.WorkspaceWeb="WorkspaceWeb",e.TadaTonMiniApp="TadaTonMiniApp",e.TadaCouponVoucher="TadaCouponVoucher",e.MusubiWeb="MusubiWeb",e.DataAttestationTadaDriver="DataAttestationTadaDriver",e.DataAttestationTadaRider="DataAttestationTadaRider",e.BaseMiniApp="BaseMiniApp",e.MVLWeb3Wallet="MVLWeb3Wallet",e.SiweAuth="SiweAuth",e.ArService="ArService",e.TadaRideAiAgent="TadaRideAiAgent",e.MusubiB2B="MusubiB2B"})(IE||(C.KnownAuthClients=IE={}));var PE;(function(e){e.IOS="IOS",e.ANDROID="ANDROID",e.UNKNOWN="UNKNOWN"})(PE||(C.MobileOs=PE={}));var DE;(function(e){e.Bearer="Bearer"})(DE||(C.Oauth2TokenType=DE={}));var OE;(function(e){e.PARTNER="PARTNER",e.OPERATOR="OPERATOR"})(OE||(C.PartnerType=OE={}));var CE;(function(e){e.Broadcasted="broadcasted",e.Confirmed="confirmed",e.ExecutionReverted="execution_reverted",e.Failed="failed",e.Replaced="replaced",e.Finalized="finalized",e.ProviderError="provider_error",e.Pending="pending"})(CE||(C.PrivyTransactionStatus=CE={}));var NE;(function(e){e.BY_BALANCE_DEPOSIT_REQUEST="BY_BALANCE_DEPOSIT_REQUEST",e.BY_BALANCE_TRANSACTION="BY_BALANCE_TRANSACTION",e.BY_HYBRID_BALANCE_TRANSACTION="BY_HYBRID_BALANCE_TRANSACTION",e.IN_MIGRATION="IN_MIGRATION"})(NE||(C.PurchasablePayMethod=NE={}));var LE;(function(e){e.MINT_ITEM="MINT_ITEM",e.MINT_BALANCE="MINT_BALANCE",e.NFT_UPGRADE="NFT_UPGRADE"})(LE||(C.PurchasableType=LE={}));var kE;(function(e){e.Pending="pending",e.Done="done",e.Failed="failed"})(kE||(C.QuorumWalletSessionStatus=kE={}));var ME;(function(e){e.TADA_POINT_TELEGRAM="TADA_POINT_TELEGRAM"})(ME||(C.QuoteDtoTypeEnum=ME={}));var UE;(function(e){e.TransactionId="transaction_id"})(UE||(C.SendCallsWalletResultKind=UE={}));var FE;(function(e){e.TxHash="tx_hash",e.UserOperationHash="user_operation_hash"})(FE||(C.SendTxWalletResultKind=FE={}));var jE;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.SENT="SENT",e.FINISHED="FINISHED",e.FAILED="FAILED",e.FAILED_PARTIAL="FAILED_PARTIAL"})(jE||(C.TadaPointActionStatus=jE={}));var qE;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(qE||(C.TadaPointActionType=qE={}));var BE;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.SENT="SENT",e.FINISHED="FINISHED",e.FAILED="FAILED",e.FAILED_PARTIAL="FAILED_PARTIAL"})(BE||(C.TadaPointRequestStatus=BE={}));var VE;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(VE||(C.TadaPointRequestType=VE={}));var GE;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.JP="JP",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(GE||(C.TadaRegion=GE={}));var HE;(function(e){e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED"})(HE||(C.ThirdPartyIntegrationStatus=HE={}));var $E;(function(e){e.MVP="MVP",e.TADAP="TADAP",e.ONIONP="ONIONP"})($E||(C.ThirdPartySupportedCurrency=$E={}));var WE;(function(e){e.COIN="COIN",e.ERC20="ERC20",e.BEP20="BEP20",e.FA2="FA2",e.FA12="FA1.2",e.SERVERED="SERVERED",e.JETTON="JETTON"})(WE||(C.TokenType=WE={}));var JE;(function(e){e.PASSWORD="PASSWORD",e.FACEBOOK="FACEBOOK",e.GOOGLE="GOOGLE",e.TWITTER="TWITTER",e.DISCORD="DISCORD",e.APPLE="APPLE",e.WEB3="WEB3",e.HMAC="HMAC",e.THIRDPARTYS2S="THIRDPARTY_S2S",e.TELEGRAM_MINIAPP="TELEGRAM_MINIAPP",e.PRIVY="PRIVY",e.TADA_COUPON_VOUCHER="TADA_COUPON_VOUCHER",e.DATA_ATTESTATION_TADA_DRIVER="DATA_ATTESTATION_TADA_DRIVER",e.DATA_ATTESTATION_TADA_RIDER="DATA_ATTESTATION_TADA_RIDER",e.BASE_MINIAPP="BASE_MINIAPP",e.AR_INVESTOR="AR_INVESTOR",e.SIWE="SIWE",e.IN_MIGRATION="IN_MIGRATION"})(JE||(C.UserIdentifierType=JE={}));var KE;(function(e){e.PRIVY_EXTERNAL="PRIVY_EXTERNAL",e.PRIVY_EMBEDDED="PRIVY_EMBEDDED",e.PRIVY_QUORUM="PRIVY_QUORUM",e.CLUTCH="CLUTCH"})(KE||(C.VerifiedWalletType=KE={}));var YE;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE"})(YE||(C.WalletStatus=YE={}));var ZC=QC(Qe()),U;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(U||(C.ContentType=U={}));var ga=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=ZC.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===U.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===U.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==U.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};C.HttpClient=ga;var ql=class extends ga{deleteBalanceWithdrawalsById=(t,r={})=>this.request({path:`/balance/withdrawals/${t}`,method:"DELETE",secure:!0,format:"json",...r});deleteUsersMe=(t={})=>this.request({path:"/users/me",method:"DELETE",secure:!0,format:"json",...t});getAuthDiscord=(t,r={})=>this.request({path:"/auth/discord",method:"GET",query:t,...r});getAuthFacebook=(t,r={})=>this.request({path:"/auth/facebook",method:"GET",query:t,...r});getAuthGoogle=(t,r={})=>this.request({path:"/auth/google",method:"GET",query:t,...r});getAuthSessions=(t={})=>this.request({path:"/auth/sessions",method:"GET",secure:!0,format:"json",...t});getAuthSiweUsersByWalletAddress=(t,r={})=>this.request({path:`/auth/siwe/users/${t}`,method:"GET",format:"json",...r});getAuthTwitter=(t,r={})=>this.request({path:"/auth/twitter",method:"GET",query:t,...r});getBalanceAccountsCurrent=(t,r={})=>this.request({path:"/balance/accounts/current",method:"GET",query:t,secure:!0,format:"json",...r});getBalanceWithdrawalsActive=(t,r={})=>this.request({path:"/balance/withdrawals/active",method:"GET",query:t,secure:!0,format:"json",...r});getBalanceWithdrawalsById=(t,r={})=>this.request({path:`/balance/withdrawals/${t}`,method:"GET",secure:!0,format:"json",...r});getCurrenciesById=(t,r={})=>this.request({path:`/currencies/${t}`,method:"GET",format:"json",...r});getFormsById=(t,r={})=>this.request({path:`/forms/${t}`,method:"GET",format:"json",...r});getGamesById=(t,r={})=>this.request({path:`/games/${t}`,method:"GET",format:"json",...r});getGamesDemocopterActive=(t={})=>this.request({path:"/games/democopter/active",method:"GET",secure:!0,format:"json",...t});getGamesDemocopterById=(t,r={})=>this.request({path:`/games/democopter/${t}`,method:"GET",secure:!0,format:"json",...r});getGamesDemocopterByIdLeaderboard=(t,r={})=>this.request({path:`/games/democopter/${t}/leaderboard`,method:"GET",secure:!0,format:"json",...r});getGamesDemocopterPastResults=(t={})=>this.request({path:"/games/democopter/pastResults",method:"GET",secure:!0,format:"json",...t});getGamesGameResultsById=(t,r={})=>this.request({path:`/games/gameResults/${t}`,method:"GET",format:"json",...r});getGamesGameResultsByIdAbstract=(t,r={})=>this.request({path:`/games/gameResults/${t}/abstract`,method:"GET",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getPurchasables1stSale=(t={})=>this.request({path:"/purchasables/1stSale",method:"GET",format:"json",...t});getPurchasablesGroupBySlug=(t,r,n={})=>this.request({path:`/purchasables/group/${t}`,method:"GET",query:r,secure:!0,format:"json",...n});getQuorumWalletSessionByToken=(t,r={})=>this.request({path:`/quorum-wallet/session/${t}`,method:"GET",format:"json",...r});getQuorumWalletTransactionByTransactionId=(t,r={})=>this.request({path:`/quorum-wallet/transaction/${t}`,method:"GET",format:"json",...r});getUsersAbstractByUserId=(t,r={})=>this.request({path:`/users/abstract/${t}`,method:"GET",secure:!0,format:"json",...r});getUsersCurrent=(t={})=>this.request({path:"/users/current",method:"GET",secure:!0,format:"json",...t});getUsersCurrentWalletMain=(t={})=>this.request({path:"/users/current/wallet/main",method:"GET",secure:!0,format:"json",...t});getUsersEmailMe=(t={})=>this.request({path:"/users/email/me",method:"GET",secure:!0,format:"json",...t});getUsersInvitees=(t={})=>this.request({path:"/users/invitees",method:"GET",secure:!0,format:"json",...t});getV11WalletsBalance=(t,r={})=>this.request({path:"/v1.1/wallets/balance",method:"GET",query:t,...r});getV12WalletsBalance=(t,r={})=>this.request({path:"/v1.2/wallets/balance",method:"GET",query:t,...r});getV1AccountsSs=(t,r={})=>this.request({path:"/v1/accounts/ss",method:"GET",query:t,...r});getV1ThirdPartyByAppIdBalanceCurrent=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/balance/current`,method:"GET",query:r,secure:!0,format:"json",...n});getV1ThirdPartyByAppIdConnectionStatus=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/connection/status`,method:"GET",query:r,secure:!0,format:"json",...n});getV1ThirdPartyByAppIdEarnEvent=(t,r={})=>this.request({path:`/v1/third-party/${t}/earn-event`,method:"GET",secure:!0,...r});getV1ThirdPartyByAppIdEarnEventByEventAliasParticipation=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/earn-event/${r}/participation`,method:"GET",format:"json",...n});getV1ThirdPartyByAppIdEarnEventByEventAliasParticipationCurrentPoint=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/earn-event/${r}/participation/current-point`,method:"GET",...n});getV1ThirdPartyByAppIdEarnEventByEventAliasParticipationFiltered=(t,r,n,s={})=>this.request({path:`/v1/third-party/${r}/earn-event/${t}/participation/filtered`,method:"GET",query:n,secure:!0,format:"json",...s});getV1Wallets=(t,r={})=>this.request({path:"/v1/wallets",method:"GET",query:t,...r});getV1WalletsBalance=(t,r={})=>this.request({path:"/v1/wallets/balance",method:"GET",query:t,...r});getV21AccountsSs=(t,r={})=>this.request({path:"/v2.1/accounts/ss",method:"GET",query:t,secure:!0,format:"json",...r});getV2Accounts=(t={})=>this.request({path:"/v2/accounts",method:"GET",secure:!0,format:"json",...t});getV2AccountsSs=(t,r={})=>this.request({path:"/v2/accounts/ss",method:"GET",query:t,format:"json",...r});getV2AccountsUid=(t={})=>this.request({path:"/v2/accounts/uid",method:"GET",secure:!0,format:"json",...t});getV2BalanceMvpCurrent=(t={})=>this.request({path:"/v2/balance/mvp/current",method:"GET",secure:!0,format:"json",...t});getV2BalanceMvpHistory=(t,r={})=>this.request({path:"/v2/balance/mvp/history",method:"GET",query:t,secure:!0,format:"json",...r});getV2BalanceMvpTransferFee=(t={})=>this.request({path:"/v2/balance/mvp/transfer/fee",method:"GET",secure:!0,format:"json",...t});getV2MobilesCurrent=(t,r={})=>this.request({path:"/v2/mobiles/current",method:"GET",query:t,secure:!0,format:"json",...r});getV2PublicThirdPartyApps=(t={})=>this.request({path:"/v2/public/third-party/apps",method:"GET",format:"json",...t});getV2ThirdPartyApps=(t={})=>this.request({path:"/v2/third-party/apps",method:"GET",secure:!0,format:"json",...t});getV2ThirdPartyByAppIdBalanceCurrent=(t,r,n={})=>this.request({path:`/v2/third-party/${t}/balance/current`,method:"GET",query:r,secure:!0,format:"json",...n});getV2Wallets=(t,r={})=>this.request({path:"/v2/wallets",method:"GET",query:t,secure:!0,format:"json",...r});getV2WalletsBalance=(t,r={})=>this.request({path:"/v2/wallets/balance",method:"GET",query:t,secure:!0,format:"json",...r});getV3BalanceMvpQuote=(t,r={})=>this.request({path:"/v3/balance/mvp/quote",method:"GET",query:t,secure:!0,format:"json",...r});getV3Wallets=(t,r={})=>this.request({path:"/v3/wallets",method:"GET",query:t,secure:!0,format:"json",...r});getWellKnownJwksJson=(t={})=>this.request({path:"/.well-known/jwks.json",method:"GET",secure:!0,...t});postAuthAllowedJwt=(t,r={})=>this.request({path:"/auth/allowed-jwt",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postAuthDeferred=(t={})=>this.request({path:"/auth/deferred",method:"POST",secure:!0,format:"json",...t});postAuthDeferredValidate=(t,r={})=>this.request({path:"/auth/deferred/validate",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postAuthPartnerChangePassword=(t,r={})=>this.request({path:"/auth/partner/change-password",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthPartnerSignin=(t,r={})=>this.request({path:"/auth/partner/signin",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthPrivyArSignin=(t,r={})=>this.request({path:"/auth/privy/ar/signin",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postAuthPrivySignin=(t={})=>this.request({path:"/auth/privy/signin",method:"POST",secure:!0,format:"json",...t});postAuthSessionsRefresh=(t={})=>this.request({path:"/auth/sessions/refresh",method:"POST",secure:!0,format:"json",...t});postAuthSignOut=(t={})=>this.request({path:"/auth/sign-out",method:"POST",secure:!0,format:"json",...t});postAuthSiweNonce=(t,r={})=>this.request({path:"/auth/siwe/nonce",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthSiweToken=(t,r={})=>this.request({path:"/auth/siwe/token",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthSiweUsers=(t,r={})=>this.request({path:"/auth/siwe/users",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthWeb3Request=(t,r={})=>this.request({path:"/auth/web3/request",method:"POST",body:t,type:U.Json,format:"json",...r});postAuthWeb3Validate=(t,r={})=>this.request({path:"/auth/web3/validate",method:"POST",body:t,type:U.Json,format:"json",...r});postBalanceWithdrawals=(t,r={})=>this.request({path:"/balance/withdrawals",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postFormsById=(t,r,n={})=>this.request({path:`/forms/${t}`,method:"POST",body:r,type:U.Json,format:"json",...n});postFormsByIdInventory=(t,r,n={})=>this.request({path:`/forms/${t}/inventory`,method:"POST",body:r,type:U.Json,format:"json",...n});postGamesByIdPayment=(t,r={})=>this.request({path:`/games/${t}/payment`,method:"POST",secure:!0,...r});postGamesDemocopterByIdStart=(t,r={})=>this.request({path:`/games/democopter/${t}/start`,method:"POST",secure:!0,format:"json",...r});postGamesDemocopterMissionsByMissionSlugTwitterRetweetValidate=(t,r,n={})=>this.request({path:`/games/democopter/missions/${t}/twitter/retweet/validate`,method:"POST",body:r,secure:!0,type:U.Json,...n});postGamesDemocopterResultsByGameResultIdTwitterShareValidate=(t,r,n={})=>this.request({path:`/games/democopter/results/${t}/twitter/share/validate`,method:"POST",body:r,secure:!0,type:U.Json,...n});postGamesGameResultsByIdThumbnail=(t,r={})=>this.request({path:`/games/gameResults/${t}/thumbnail`,method:"POST",...r});postGamesResult=(t,r={})=>this.request({path:"/games/result",method:"POST",body:t,type:U.Json,format:"json",...r});postGamesUserResult=(t,r={})=>this.request({path:"/games/user/result",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postMvlchainRpc=(t={})=>this.request({path:"/mvlchain-rpc",method:"POST",format:"json",...t});postQuorumWalletCosign=(t,r={})=>this.request({path:"/quorum-wallet/cosign",method:"POST",body:t,type:U.Json,format:"json",...r});postQuorumWalletQuorum=(t,r={})=>this.request({path:"/quorum-wallet/quorum",method:"POST",body:t,type:U.Json,format:"json",...r});postQuorumWalletRegister=(t,r={})=>this.request({path:"/quorum-wallet/register",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postQuorumWalletSendcalls=(t,r={})=>this.request({path:"/quorum-wallet/sendcalls",method:"POST",body:t,type:U.Json,format:"json",...r});postQuorumWalletSendtx=(t,r={})=>this.request({path:"/quorum-wallet/sendtx",method:"POST",body:t,type:U.Json,format:"json",...r});postQuorumWalletSession=(t,r={})=>this.request({path:"/quorum-wallet/session",method:"POST",body:t,type:U.Json,format:"json",...r});postQuorumWalletValidate=(t,r={})=>this.request({path:"/quorum-wallet/validate",method:"POST",body:t,type:U.Json,format:"json",...r});postUsersCurrentWallet=(t,r={})=>this.request({path:"/users/current/wallet",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postUsersCurrentWalletBidSignature=(t,r={})=>this.request({path:"/users/current/wallet/bidSignature",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postUsersCurrentWalletSign=(t,r={})=>this.request({path:"/users/current/wallet/sign",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postUsersEmailMe=(t,r={})=>this.request({path:"/users/email/me",method:"POST",body:t,secure:!0,type:U.Json,...r});postUsersReferrer=(t,r={})=>this.request({path:"/users/referrer",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1Accounts=(t,r={})=>this.request({path:"/v1/accounts",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1AccountsCheck=(t,r={})=>this.request({path:"/v1/accounts/check",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1AccountsDeferred=(t={})=>this.request({path:"/v1/accounts/deferred",method:"POST",secure:!0,format:"json",...t});postV1AccountsDelete=(t={})=>this.request({path:"/v1/accounts/delete",method:"POST",secure:!0,...t});postV1AccountsRestore=(t,r={})=>this.request({path:"/v1/accounts/restore",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1EarnEventById=(t,r={})=>this.request({path:`/v1/earn-event/${t}`,method:"POST",secure:!0,...r});postV1EarnEventByIdClaimInformation=(t,r={})=>this.request({path:`/v1/earn-event/${t}/claim/information`,method:"POST",secure:!0,format:"json",...r});postV1EarnEventByIdClaimRequest=(t,r={})=>this.request({path:`/v1/earn-event/${t}/claim/request`,method:"POST",secure:!0,format:"json",...r});postV1EarnEventByIdClaimStatus=(t,r={})=>this.request({path:`/v1/earn-event/${t}/claim/status`,method:"POST",secure:!0,format:"json",...r});postV1EarnEventByIdParticipationCurrent=(t,r={})=>this.request({path:`/v1/earn-event/${t}/participation/current`,method:"POST",secure:!0,format:"json",...r});postV1EarnEventList=(t={})=>this.request({path:"/v1/earn-event/list",method:"POST",secure:!0,format:"json",...t});postV1Mobiles=(t,r={})=>this.request({path:"/v1/mobiles",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1MobilesCurrent=(t,r={})=>this.request({path:"/v1/mobiles/current",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV1ThirdPartyByAppIdConnect=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/connect`,method:"POST",body:r,secure:!0,type:U.Json,format:"json",...n});postV1ThirdPartyByAppIdConnectCheck=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/connect/check`,method:"POST",body:r,secure:!0,type:U.Json,format:"json",...n});postV1ThirdPartyByAppIdDisconnect=(t,r={})=>this.request({path:`/v1/third-party/${t}/disconnect`,method:"POST",secure:!0,format:"json",...r});postV1ThirdPartyByAppIdEarnEventByEventAliasParticipation=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/earn-event/${r}/participation`,method:"POST",format:"json",...n});postV1ThirdPartyByAppIdEarnEventByEventAliasParticipationCancel=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/earn-event/${r}/participation/cancel`,method:"POST",format:"json",...n});postV1Wallets=(t,r={})=>this.request({path:"/v1/wallets",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV21Accounts=(t,r={})=>this.request({path:"/v2.1/accounts",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV21AccountsRestore=(t,r={})=>this.request({path:"/v2.1/accounts/restore",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2Accounts=(t,r={})=>this.request({path:"/v2/accounts",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2AccountsCheck=(t,r={})=>this.request({path:"/v2/accounts/check",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2AccountsDeferred=(t={})=>this.request({path:"/v2/accounts/deferred",method:"POST",secure:!0,format:"json",...t});postV2AccountsDelete=(t={})=>this.request({path:"/v2/accounts/delete",method:"POST",secure:!0,format:"json",...t});postV2AccountsRestore=(t,r={})=>this.request({path:"/v2/accounts/restore",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2AccountsSessionsRefresh=(t={})=>this.request({path:"/v2/accounts/sessions/refresh",method:"POST",secure:!0,format:"json",...t});postV2AccountsSessionsRefreshConfirm=(t={})=>this.request({path:"/v2/accounts/sessions/refresh/confirm",method:"POST",secure:!0,format:"json",...t});postV2AccountsTokenHmac=(t={})=>this.request({path:"/v2/accounts/token/hmac",method:"POST",secure:!0,format:"json",...t});postV2AccountsUidByUidCheck=(t,r={})=>this.request({path:`/v2/accounts/uid/${t}/check`,method:"POST",secure:!0,format:"json",...r});postV2AppEventState=(t,r={})=>this.request({path:"/v2/app-event/state",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2AuthAllowedJwt=(t,r={})=>this.request({path:"/v2/auth/allowed-jwt",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2BalanceMvpSwapWithdrawalRequests=(t,r={})=>this.request({path:"/v2/balance/mvp/swap/withdrawal-requests",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2BalanceMvpTransfer=(t,r={})=>this.request({path:"/v2/balance/mvp/transfer",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2Mobiles=(t,r={})=>this.request({path:"/v2/mobiles",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV2ThirdPartyByAppIdConnect=(t,r,n={})=>this.request({path:`/v2/third-party/${t}/connect`,method:"POST",body:r,secure:!0,type:U.Json,format:"json",...n});postV2ThirdPartyByAppIdConnectCheck=(t,r,n={})=>this.request({path:`/v2/third-party/${t}/connect/check`,method:"POST",body:r,secure:!0,type:U.Json,format:"json",...n});postV2ThirdPartyByAppIdDisconnect=(t,r={})=>this.request({path:`/v2/third-party/${t}/disconnect`,method:"POST",secure:!0,format:"json",...r});postV2Wallets=(t,r={})=>this.request({path:"/v2/wallets",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3BalanceMvpSwapDepositRequests=(t,r={})=>this.request({path:"/v3/balance/mvp/swap/deposit-requests",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3BalanceMvpSwapDepositRequestsPrecheck=(t,r={})=>this.request({path:"/v3/balance/mvp/swap/deposit-requests/precheck",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3ThirdPartyBalanceCurrent=(t,r={})=>this.request({path:"/v3/third-party/balance/current",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3ThirdPartyUsersBalanceCurrent=(t,r={})=>this.request({path:"/v3/third-party/users/balance/current",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3ThirdPartyUsersBalanceTransfer=(t,r={})=>this.request({path:"/v3/third-party/users/balance/transfer",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postV3Wallets=(t,r={})=>this.request({path:"/v3/wallets",method:"POST",body:t,secure:!0,type:U.Json,format:"json",...r});postWaitinglistSignature=(t,r={})=>this.request({path:"/waitinglist/signature",method:"POST",body:t,type:U.Json,format:"json",...r});putV1AccountsSs=(t,r={})=>this.request({path:"/v1/accounts/ss",method:"PUT",body:t,secure:!0,type:U.Json,...r});putV2AccountsSs=(t,r={})=>this.request({path:"/v2/accounts/ss",method:"PUT",body:t,secure:!0,type:U.Json,...r})};C.Api=ql});var Gl=P(z=>{"use strict";p();var eN=z&&z.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(z,"__esModule",{value:!0});z.Api=z.HttpClient=z.ContentType=z.VehicleSubscriptionStatus=z.VehicleStatisticsType=z.TadaRideAbstractV2DtoRegionEnum=z.TadaRideAbstractDtoRegionEnum=z.TadaRegion=z.RwaNoticeCategory=z.RideStatusAbstract=z.RidePointTypeEnum=z.Period=z.OnionStationType=z.OnionStationStatus=z.GetV1DepinVehiclesDashParamsVehicleSeriesEnum=z.DepinVehiclesFilterEnum=z.DepinVehicleType=z.ChargerStatus=z.BlockchainNetwork=void 0;var zE;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(zE||(z.BlockchainNetwork=zE={}));var XE;(function(e){e.FULLY_CHARGED="FULLY_CHARGED",e.CHARGING="CHARGING",e.PROBLEM="PROBLEM",e.NO_BATTERY="NO_BATTERY",e.OFF="OFF"})(XE||(z.ChargerStatus=XE={}));var QE;(function(e){e.X1="X1",e.T1="T1",e.X2="X2"})(QE||(z.DepinVehicleType=QE={}));var ZE;(function(e){e.ALL="ALL",e.VEHICLE_ON="VEHICLE_ON",e.VEHICLE_OFF="VEHICLE_OFF"})(ZE||(z.DepinVehiclesFilterEnum=ZE={}));var eT;(function(e){e.ALL="ALL",e.T1="T1",e.X="X"})(eT||(z.GetV1DepinVehiclesDashParamsVehicleSeriesEnum=eT={}));var tT;(function(e){e.ON="ON",e.OFF="OFF"})(tT||(z.OnionStationStatus=tT={}));var rT;(function(e){e.HUB="HUB",e.PARTNER="PARTNER",e.FACTORY="FACTORY",e.SERVICE_CENTER="SERVICE_CENTER",e.MEGA="MEGA",e.MINI="MINI"})(rT||(z.OnionStationType=rT={}));var nT;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(nT||(z.Period=nT={}));var sT;(function(e){e.PICKUP="PICKUP",e.DROPOFF="DROPOFF"})(sT||(z.RidePointTypeEnum=sT={}));var iT;(function(e){e.PENDING="PENDING",e.MATCHED="MATCHED"})(iT||(z.RideStatusAbstract=iT={}));var aT;(function(e){e.NEW_RELEASE="NEW_RELEASE",e.MEDIA_COVERAGE="MEDIA_COVERAGE",e.ETC="ETC"})(aT||(z.RwaNoticeCategory=aT={}));var oT;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(oT||(z.TadaRegion=oT={}));var cT;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(cT||(z.TadaRideAbstractDtoRegionEnum=cT={}));var lT;(function(e){e.SG="SG",e.VN="VN",e.KH="KH",e.KR="KR",e.ET="ET",e.ID="ID",e.HK="HK",e.TH="TH",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(lT||(z.TadaRideAbstractV2DtoRegionEnum=lT={}));var uT;(function(e){e.ODOMETER="ODOMETER",e.BATTERY="BATTERY"})(uT||(z.VehicleStatisticsType=uT={}));var dT;(function(e){e.ON_TIME="ON_TIME",e.OVERDUE="OVERDUE",e.FINISHED="FINISHED",e.CANCELLED="CANCELLED"})(dT||(z.VehicleSubscriptionStatus=dT={}));var tN=eN(Qe()),tr;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(tr||(z.ContentType=tr={}));var ha=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=tN.default.create({...s,baseURL:s.baseURL||"https://backend.clutchwalletstaging.xyz/vehicle"}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===tr.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===tr.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==tr.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};z.HttpClient=ha;var Vl=class extends ha{getChainMetricsTxCountByNetworkByContractAddress=(t,r,n={})=>this.request({path:`/chain-metrics/tx-count/${t}/${r}`,method:"GET",format:"json",...n});getMetadataByTokenId=(t,r={})=>this.request({path:`/metadata/${t}`,method:"GET",format:"json",...r});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});getSaleBySaleId=(t,r={})=>this.request({path:`/sale/${t}`,method:"GET",format:"json",...r});getTokenByNftNoByNftNo=(t,r={})=>this.request({path:`/tokenByNftNo/${t}`,method:"GET",...r});getTokenByTokenId=(t,r={})=>this.request({path:`/token/${t}`,method:"GET",...r});getV1DepinBatteryChargers=(t={})=>this.request({path:"/v1/depin/battery/chargers",method:"GET",secure:!0,format:"json",...t});getV1DepinBatteryChargersCounts=(t={})=>this.request({path:"/v1/depin/battery/chargers/counts",method:"GET",secure:!0,format:"json",...t});getV1DepinBatteryDash=(t={})=>this.request({path:"/v1/depin/battery/dash",method:"GET",secure:!0,format:"json",...t});getV1DepinBatteryInventory=(t={})=>this.request({path:"/v1/depin/battery/inventory",method:"GET",secure:!0,format:"json",...t});getV1DepinBatteryStations=(t={})=>this.request({path:"/v1/depin/battery/stations",method:"GET",secure:!0,format:"json",...t});getV1DepinBatteryStationsById=(t,r={})=>this.request({path:`/v1/depin/battery/stations/${t}`,method:"GET",secure:!0,format:"json",...r});getV1DepinBatterySwap=(t={})=>this.request({path:"/v1/depin/battery/swap",method:"GET",secure:!0,format:"json",...t});getV1DepinRides=(t,r={})=>this.request({path:"/v1/depin/rides",method:"GET",query:t,format:"json",...r});getV1DepinRidesHeatmap=(t,r={})=>this.request({path:"/v1/depin/rides/heatmap",method:"GET",query:t,format:"json",...r});getV1DepinVehiclesByNum=(t,r={})=>this.request({path:`/v1/depin/vehicles/${t}`,method:"GET",secure:!0,format:"json",...r});getV1DepinVehiclesDash=(t,r={})=>this.request({path:"/v1/depin/vehicles/dash",method:"GET",query:t,secure:!0,format:"json",...r});getV1RwaNotice=(t,r={})=>this.request({path:"/v1/rwa-notice",method:"GET",query:t,secure:!0,format:"json",...r});getV2DepinRides=(t,r={})=>this.request({path:"/v2/depin/rides",method:"GET",query:t,format:"json",...r});getV2DepinVehicleUpdates=(t,r={})=>this.request({path:"/v2/depin/vehicle-updates",method:"GET",query:t,format:"json",...r});getVehicleTestS2SHmac=(t={})=>this.request({path:"/vehicle-test/s2s-hmac",method:"GET",secure:!0,format:"json",...t});getVehicleTestSentry=(t={})=>this.request({path:"/vehicle-test/sentry",method:"GET",format:"json",...t});postVehicle=(t,r={})=>this.request({path:"/vehicle",method:"POST",body:t,secure:!0,type:tr.Json,format:"json",...r});postVehicleBatterySwap=(t,r={})=>this.request({path:"/vehicle/battery/swap",method:"POST",body:t,secure:!0,type:tr.Json,format:"json",...r});postVehicleSubscription=(t,r={})=>this.request({path:"/vehicle/subscription",method:"POST",body:t,secure:!0,type:tr.Json,format:"json",...r});postVehicleSubscriptionUpdate=(t,r={})=>this.request({path:"/vehicle/subscription/update",method:"POST",body:t,secure:!0,type:tr.Json,format:"json",...r});postVehicleTestS2SHmac=(t={})=>this.request({path:"/vehicle-test/s2s-hmac",method:"POST",secure:!0,format:"json",...t})};z.Api=Vl});var $l=P(lt=>{"use strict";p();var rN=lt&&lt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(lt,"__esModule",{value:!0});lt.Api=lt.HttpClient=lt.ContentType=lt.CheckPointId=lt.BlockchainNetwork=void 0;var pT;(function(e){e.SERVERED="SERVERED",e.MVL="MVL",e.MVL_TEST="MVL_TEST",e.MVL_POODLE="MVL_POODLE",e.MVL_BEAGLE="MVL_BEAGLE",e.TADA_PROTOCOL_TEST="TADA_PROTOCOL_TEST",e.TADA_PROTOCOL="TADA_PROTOCOL",e.ETHEREUM="ETHEREUM",e.ETHEREUM_ROPSTEN="ETHEREUM_ROPSTEN",e.ETHEREUM_KOVAN="ETHEREUM_KOVAN",e.ETHEREUM_RINKEBY="ETHEREUM_RINKEBY",e.ETHEREUM_GOERLI="ETHEREUM_GOERLI",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA",e.ETHEREUM_LOCAL="ETHEREUM_LOCAL",e.BSC="BSC",e.BSC_TEST="BSC_TEST",e.POLYGON="POLYGON",e.POLYGON_TEST="POLYGON_TEST",e.SOLANA="SOLANA",e.SOLANA_DEV="SOLANA_DEV",e.BITCOIN="BITCOIN",e.BITCOIN_TEST="BITCOIN_TEST",e.XTZ="XTZ",e.XTZ_GHOST="XTZ_GHOST",e.KLAYTN="KLAYTN",e.KLAYTN_BAOBAB="KLAYTN_BAOBAB",e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.TON="TON",e.TON_TEST="TON_TEST",e.IN_MIGRATION="IN_MIGRATION",e.ARBITRUM="ARBITRUM",e.ARBITRUM_TEST="ARBITRUM_TEST",e.POLYGON_ZKEVM="POLYGON_ZKEVM",e.OP_SEPOLIA="OP_SEPOLIA"})(pT||(lt.BlockchainNetwork=pT={}));var mT;(function(e){e.CONFIRMED="CONFIRMED",e.LATEST="LATEST",e.PARSED_LATEST="PARSED_LATEST"})(mT||(lt.CheckPointId=mT={}));var nN=rN(Qe()),xs;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(xs||(lt.ContentType=xs={}));var ya=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=nN.default.create({...s,baseURL:s.baseURL||""}),this.secure=r,this.format=n,this.securityWorker=t}setSecurityData=t=>{this.securityData=t};mergeRequestParams(t,r){let n=t.method||r&&r.method;return{...this.instance.defaults,...t,...r||{},headers:{...n&&this.instance.defaults.headers[n.toLowerCase()]||{},...t.headers||{},...r&&r.headers||{}}}}stringifyFormItem(t){return typeof t=="object"&&t!==null?JSON.stringify(t):`${t}`}createFormData(t){return Object.keys(t||{}).reduce((r,n)=>{let s=t[n],i=s instanceof Array?s:[s];for(let a of i){let o=a instanceof Blob||a instanceof File;r.append(n,o?a:this.stringifyFormItem(a))}return r},new FormData)}request=async({secure:t,path:r,type:n,query:s,format:i,body:a,...o})=>{let c=(typeof t=="boolean"?t:this.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},u=this.mergeRequestParams(o,c),l=i||this.format||void 0;return n===xs.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===xs.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...u,headers:{...u.headers||{},...n&&n!==xs.FormData?{"Content-Type":n}:{}},params:s,responseType:l,data:a,url:r}).then(d=>d.data)}};lt.HttpClient=ya;var Hl=class extends ya{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t})};lt.Api=Hl});var gT=P(Q=>{"use strict";p();var fT=Q&&Q.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),sN=Q&&Q.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ut=Q&&Q.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),s=0;s<n.length;s++)n[s]!=="default"&&fT(r,t,n[s]);return sN(r,t),r}})(),iN=Q&&Q.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&fT(t,e,r)};Object.defineProperty(Q,"__esModule",{value:!0});Q.DataAttestationService=Q.StatisticsService=Q.MusubiService=Q.TadaTonService=Q.WatcherWorker=Q.VehicleOracleService=Q.UserService=Q.SaleService=Q.PushService=Q.ImageFactoryService=Q.ClutchService=Q.AmbTelemetryService=Q.ActivityService=Q.Bep20SwapService=void 0;var aN=ul(),oN=pl(),cN=fl(),lN=hl(),uN=_l(),dN=Tl(),pN=bl(),mN=xl(),fN=Al(),gN=Sl(),hN=wn(),yN=Ul(),_N=jl(),EN=Bl(),TN=Gl(),bN=$l();Q.Bep20SwapService=ut(fl());Q.ActivityService=ut(ul());Q.AmbTelemetryService=ut(pl());Q.ClutchService=ut(hl());Q.ImageFactoryService=ut(Tl());Q.PushService=ut(xl());Q.SaleService=ut(Sl());Q.UserService=ut(Bl());Q.VehicleOracleService=ut(Gl());Q.WatcherWorker=ut($l());Q.TadaTonService=ut(jl());Q.MusubiService=ut(Al());Q.StatisticsService=ut(Ul());Q.DataAttestationService=ut(_l());iN(wn(),Q);var vN="en",Wl=class e{securityPolicy;clientId;clientVersion;interceptors;services;static getServiceApiConstructor(t){switch(t){case"userService":return EN.Api;case"activityService":return aN.Api;case"ambTelemetryService":return oN.Api;case"saleService":return gN.Api;case"clutchService":return lN.Api;case"pushService":return mN.Api;case"imageFactoryService":return dN.Api;case"vehicleOracleService":return TN.Api;case"watcherWorker":return bN.Api;case"bep20SwapService":return cN.Api;case"tadaTonService":return _N.Api;case"musubiService":return fN.Api;case"statisticsService":return yN.Api;case"dataAttestationService":return uN.Api;default:throw new Error("[apiClient] getServiceApiConstructor: Unknown client key")}}setAcceptLanguage(t){let r="Accept-Language";for(let n in this.services)this.services[n]&&(this.services[n].instance.defaults.headers[r]=t)}constructor(t){this.clientId=t.clientId,this.clientVersion=t.clientVersion,(0,pN.log)("init, securityType=%s, clientId=%s, clientVersion=%s, baseUrls=%j",t.securityType,t.clientId,t.clientVersion,t.baseUrls),this.interceptors=t.interceptors,this.securityPolicy=hN.SecurityPolicyFactory.create({type:t.securityType,apiClient:this,onChangeSecurityData:t.onChangeSecurityData,onRefreshTokenExpired:t.onRefreshTokenExpired});let{securityWorker:r}=this.securityPolicy,n={securityWorker:r,secure:!!r,headers:{"X-Auth-Client-Id":this.clientId,"X-Auth-Client-Version":`${this.clientVersion}`,"Accept-Language":t.acceptLanguage??vN}};this.services=Object.keys(t.baseUrls).reduce((s,i)=>{let a=t.baseUrls[i];if(a){let o=e.getServiceApiConstructor(i);s[i]=new o({...n,baseURL:a})}else s[i]=void 0;return s},{}),Object.values(this.services).forEach(s=>{if(!s)return;let{instance:i}=s;this.interceptors?.request&&this.interceptors.request.forEach(o=>{let{onFulfilled:c=d=>d,onRejected:u,options:l}=o;i.interceptors.request.use(c,u,l)}),this.interceptors?.response&&this.interceptors.response.forEach(o=>{let{onFulfilled:c=d=>d,onRejected:u,options:l}=o;i.interceptors.response.use(c,u,l)});let a=this.securityPolicy.onApiRejectedInterceptor;a&&i.interceptors.response.use(o=>o,a(i,s===this.user))})}setSecurityInfo(t){this.securityPolicy.setSecurityInfo(t)}get user(){return this.services.userService}get activity(){return this.services.activityService}get ambTelemetry(){return this.services.ambTelemetryService}get sale(){return this.services.saleService}get clutch(){return this.services.clutchService}get push(){return this.services.pushService}get imageFactory(){return this.services.imageFactoryService}get vehicleOracle(){return this.services.vehicleOracleService}get watcherWorker(){return this.services.watcherWorker}get bep20Swap(){return this.services.bep20SwapService}get tadaTon(){return this.services.tadaTonService}get musubi(){return this.services.musubiService}get statistics(){return this.services.statisticsService}get dataAttestation(){return this.services.dataAttestationService}};Q.default=Wl});p();p();p();import CT from"fs";import{spawn as YN}from"child_process";p();function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lo(e){return e==null?"null":String(e)}function td(e,t){let r=" ".repeat(t),n=[];for(let s of e)if(No(s)||Array.isArray(s)){let i=ko(s,t+1),a=i[0].slice((t+1)*2);n.push(`${r}- ${a}`,...i.slice(1))}else typeof s=="string"&&s.includes(`
3
25
  `)?n.push(`${r}- |`,...s.split(`
4
- `).map(i=>`${r} ${i}`)):s===""?n.push(`${r}- (none)`):n.push(`${r}- ${Sn(s)}`);return n}function An(e,t){let r=" ".repeat(t);if(Tn(e)){let n=Object.keys(e);if(n.length===0)return[`${r}(none)`];let s=[];for(let i of n){let o=e[i];Tn(o)?Object.keys(o).length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...An(o,t+1))):Array.isArray(o)?o.length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...Ws(o,t+1))):typeof o=="string"&&o.includes(`
5
- `)?s.push(`${r}${i}: |`,...o.split(`
6
- `).map(a=>`${r} ${a}`)):o===""?s.push(`${r}${i}: (none)`):s.push(`${r}${i}: ${Sn(o)}`)}return s}return Array.isArray(e)?e.length===0?[`${r}(none)`]:Ws(e,t):typeof e=="string"&&e.includes(`
26
+ `).map(i=>`${r} ${i}`)):s===""?n.push(`${r}- (none)`):n.push(`${r}- ${Lo(s)}`);return n}function ko(e,t){let r=" ".repeat(t);if(No(e)){let n=Object.keys(e);if(n.length===0)return[`${r}(none)`];let s=[];for(let i of n){let a=e[i];No(a)?Object.keys(a).length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...ko(a,t+1))):Array.isArray(a)?a.length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...td(a,t+1))):typeof a=="string"&&a.includes(`
27
+ `)?s.push(`${r}${i}: |`,...a.split(`
28
+ `).map(o=>`${r} ${o}`)):a===""?s.push(`${r}${i}: (none)`):s.push(`${r}${i}: ${Lo(a)}`)}return s}return Array.isArray(e)?e.length===0?[`${r}(none)`]:td(e,t):typeof e=="string"&&e.includes(`
7
29
  `)?[`${r}|`,...e.split(`
8
- `).map(n=>`${r} ${n}`)]:[`${r}${Sn(e)}`]}function Vs(e){return An(e,0).join(`
9
- `)}var Jt="json";function Js(e){Jt=e}function wt(){return Jt}function Ks(e){return{json:e.includes("--json"),argv:e.filter(t=>t!=="--json")}}function w(e){console.log(Jt==="json"?JSON.stringify(e,null,2):Vs(e))}function g(e){console.error(Jt==="json"?JSON.stringify(e):Vs(e))}import Fn from"fs";import Ge from"path";import{fileURLToPath as Qd}from"url";import Ys from"os";import Ze from"path";function pd(e){return e.startsWith("~/")?Ze.join(Ys.homedir(),e.slice(2)):Ze.resolve(e)}function F(){return pd(process.env.AMB_RIDE_STATE_DIR??Ze.join(Ys.homedir(),".amb"))}function et(){return Ze.join(F(),"state","data")}function Xs(){return Ze.join(F(),"state","keys")}function Kt(e){return Ze.join(e,".tada-state")}import D from"fs";import le from"path";import jd from"crypto";import Ln from"crypto";import S from"fs";import x from"path";function zs(e,t){let r=t(e.legacyRoot),n=t(e.ambientRoot),s=t(e.backupRoot);return t(e.stagingRoot)?"conflict":!r&&!n&&!s?"fresh":r&&!n&&!s?"legacy_candidate":!r&&n&&!s?"ambient_fresh":!r&&n&&s?"already_migrated":r&&n&&!s?"resume_before_backup":"conflict"}var md={fresh:["initialize_ambient"],legacy_candidate:["migrate_legacy"],ambient_fresh:["use_ambient"],already_migrated:["validate_migrated"],resume_before_backup:["resume_backup"]};function Qs(e,t){if(t==="conflict")throw new Error("MIGRATION_CONFLICT: filesystem state is not safe to migrate");return{state:t,paths:{...e},actions:[...md[t]]}}var ei={TADA_AGENT_PASSPHRASE:"AMB_RIDE_PASSPHRASE",TADA_AGENT_STATE_DIR:"AMB_RIDE_STATE_DIR",TADA_AGENT_LOG_LEVEL:"AMB_RIDE_LOG_LEVEL",TADA_OPENCLAW_CLI:"AMB_RIDE_OPENCLAW_CLI"},Zs=new Set(Object.values(ei)),gd=/^(?:TADA_AGENT_|TADA_OPENCLAW_)/,fd=/^TADA_AGENT_DEPOSIT_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,_d=/^TADA_AGENT_BRIDGE_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,yd=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function Ne(e,t){throw new Error(`${e}: ${t}`)}function Et(e){if(typeof e.env!="string")return{...e.env};let t={};for(let[r,n]of e.env.split(/\r?\n/).entries()){let s=n.trim();if(s===""||s.startsWith("#"))continue;let i=s.indexOf("=");i<=0&&Ne("INVALID_ENV_LINE",`source=${e.name} line=${r+1}`);let o=s.slice(0,i).trim(),a=s.slice(i+1).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)||Ne("INVALID_ENV_KEY",`source=${e.name} line=${r+1}`),Object.hasOwn(t,o)&&Ne("DUPLICATE_ENV_KEY",`source=${e.name} key=${o}`),t[o]=a}return t}function hd(e){let t=Array.isArray(e)?e:[{name:"input",env:e}],r=[],n=new Map;for(let s of t){let i=Et(s);for(let[o,a]of Object.entries(i)){if(a===void 0)continue;let c=n.get(o);if(c&&c.value!==a&&Ne("ENV_SOURCE_CONFLICT",`key=${o} sources=${c.source},${s.name}`),!c){let l={key:o,value:a,source:s.name};n.set(o,l),r.push(l)}}}return r}function wd(e,t){let r=fd.exec(e);if(r)return r[1];let n=_d.exec(e);if(n)return n[1];if(e==="TADA_AGENT_PAYMENT_RPC_URL")return t}function He(e,t){if(!yd.test(t))throw new Error(`INVALID_PAYMENT_NETWORK: network=${t}`);let r=hd(e),n={},s=new Map,i=new Map,o=[],a=[],c=(l,d)=>{let u=s.get(d);u&&u.value!==l.value&&Ne("ENV_TARGET_CONFLICT",`target=${d} keys=${u.key},${l.key} sources=${u.source},${l.source}`),u||(s.set(d,l),n[d]=l.value),a.push({from:l.key,to:d})};for(let l of r){let d=ei[l.key];if(d){c(l,d);continue}let u=wd(l.key,t);if(u){let m=i.get(u)??[];m.push(l),i.set(u,m);continue}if(Zs.has(l.key)||/^AMB_RIDE_RPC_URL_/.test(l.key)){!Zs.has(l.key)&&!/^AMB_RIDE_RPC_URL_[A-Z0-9]+(?:_[A-Z0-9]+)*$/.test(l.key)&&Ne("UNKNOWN_AMBIENT_ENV_KEY",`key=${l.key} source=${l.source}`),c(l,l.key);continue}l.key.startsWith("AMB_RIDE_")&&Ne("UNKNOWN_AMBIENT_ENV_KEY",`key=${l.key} source=${l.source}`),gd.test(l.key)&&o.push(l.key)}for(let[l,d]of i){new Set(d.map(p=>p.value)).size>1&&Ne("RPC_CONFIG_CONFLICT",`network=${l} keys=${d.map(p=>p.key).join(",")} sources=${d.map(p=>p.source).join(",")}`);let m=`AMB_RIDE_RPC_URL_${l}`;for(let p of d)c(p,m)}return{env:n,droppedLegacyConfig:[...new Set(o)].sort(),mappedLegacyConfig:a}}import qe from"fs";import be from"path";import vd from"better-sqlite3";import Re from"crypto";import X_ from"fs";import Q_ from"path";var ti=Buffer.from("RAGK"),ri=1,Yt=4,ni=1,Xt=32,zt=12,In=16,Ed=Yt+ni+Xt+zt+In,Rd=16384,bd=8,Td=1,Sd=32;function si(){let{publicKey:e,privateKey:t}=Re.generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}}function ii(e){return Re.createPublicKey(e).export({type:"spki",format:"der"}).toString("base64")}function Qt(e){let t=Re.createPrivateKey(e);return Re.createPublicKey(t).export({type:"spki",format:"der"}).toString("base64")}function oi(e,t){return Re.scryptSync(e,t,Sd,{N:Rd,r:bd,p:Td})}function ai(e,t){let r=Re.randomBytes(Xt),n=Re.randomBytes(zt),s=oi(t,r),i=Re.createCipheriv("aes-256-gcm",s,n),o=Buffer.concat([i.update(e),i.final()]),a=i.getAuthTag();return Buffer.concat([ti,Buffer.from([ri]),r,n,a,o])}function fe(e,t){if(e.length<Ed)throw new Error("Invalid encrypted data: too short");if(!e.subarray(0,Yt).equals(ti))throw new Error("Invalid encrypted data: bad magic");let n=e[Yt];if(n!==ri)throw new Error(`Unsupported encrypted data version: ${n}`);let s=Yt+ni,i=e.subarray(s,s+Xt);s+=Xt;let o=e.subarray(s,s+zt);s+=zt;let a=e.subarray(s,s+In);s+=In;let c=e.subarray(s),l=oi(t,i),d=Re.createDecipheriv("aes-256-gcm",l,o);return d.setAuthTag(a),Buffer.concat([d.update(c),d.final()])}function ne(e){e.fill(0)}import Zt from"path";import Ad from"fs";import Id from"better-sqlite3";function Q(e,t){return Zt.join(e,Zt.basename(t))}function er(e){return Zt.basename(e)}var xd=[{table:"privy_wallet_meta",id:"wallet_address"},{table:"pending_sessions",id:"session_token"}];function ci(e){if(!Ad.existsSync(e))return{normalized:0};let t=null;try{return t=new Id(e),t.transaction(()=>{let n=new Map,s=0;for(let i of xd){if(!t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(i.table))continue;let a=t.prepare(`SELECT ${i.id} AS id, k_i_key_path FROM ${i.table}`).all(),c=t.prepare(`UPDATE ${i.table} SET k_i_key_path = ? WHERE ${i.id} = ?`);for(let l of a){let d=l.k_i_key_path.replace(/\\/g,"/"),u=Zt.posix.basename(d);if(!u||u==="."||u==="..")throw new Error(`INVALID_KEY_PATH: ${i.table}.${i.id}=${l.id}`);let m=n.get(u);if(m!==void 0&&m!==d)throw new Error(`KEY_PATH_COLLISION: ${u}`);n.set(u,d),l.k_i_key_path!==u&&(c.run(u,l.id),s++)}}return{normalized:s}})()}finally{t?.close()}}var pi=["identity","wallets","privy_wallet_meta","pending_sessions","jwt_cache","ride_requests","tada_members","places","bridge_jobs","member_login_sessions"];function W(e,t){throw new Error(t?`${e}: ${t}`:e)}function li(e){try{return new vd(e,{readonly:!0,fileMustExist:!0})}catch(t){return W("SQLITE_OPEN_FAILED",String(t))}}function xn(e,t){return!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(t)}function di(e){return Object.fromEntries(pi.map(t=>{if(!xn(e,t))return[t,"absent"];let r=e.prepare(`SELECT COUNT(*) AS count FROM ${t}`).get();return[t,r.count]}))}function Nd(e){let t=[];if(xn(e,"privy_wallet_meta")){let r=e.prepare("SELECT wallet_address AS id, k_i_pub AS publicKey, k_i_key_path AS storedPath FROM privy_wallet_meta").all();t.push(...r.map(n=>({table:"privy_wallet_meta",...n})))}if(xn(e,"pending_sessions")){let r=e.prepare("SELECT session_token AS id, k_i_pub AS publicKey, k_i_key_path AS storedPath FROM pending_sessions").all();t.push(...r.map(n=>({table:"pending_sessions",...n})))}return t}function ui(e){let t;try{t=e.pragma("integrity_check")}catch(r){W("SQLITE_INTEGRITY_FAILED",String(r))}(t.length!==1||t[0]?.integrity_check!=="ok")&&W("SQLITE_INTEGRITY_FAILED",t.map(r=>r.integrity_check).join("; "))}function kd(e,t){for(let r of pi)e[r]!==t[r]&&W("ROW_COUNT_MISMATCH",`${r}: source=${e[r]} staged=${t[r]}`)}function vn(e){let t=be.resolve(e.dataDir),r=be.resolve(e.keysDir),n=be.resolve(e.dbPath);for(let[a,c]of[["DATA_DIR",t],["KEYS_DIR",r]]){let l;try{l=qe.lstatSync(c)}catch{W(`MISSING_${a}`)}(!l.isDirectory()||l.isSymbolicLink())&&W(`INVALID_${a}`)}be.dirname(n)!==t&&W("DB_OUTSIDE_DATA_DIR"),qe.existsSync(n)||W("MISSING_DATABASE");let s=qe.lstatSync(n);(!s.isFile()||s.isSymbolicLink())&&W("INVALID_DATABASE_FILE");let i;if(e.sourceDbPath){let a=be.resolve(e.sourceDbPath);a===n&&W("SOURCE_EQUALS_STAGED");let c=li(a);try{ui(c),i=di(c)}finally{c.close()}}try{ci(n)}catch(a){let c=String(a);c.includes("KEY_PATH_COLLISION")&&W("KEY_PATH_COLLISION",c),/malformed|not a database|database disk image/i.test(c)&&W("SQLITE_INTEGRITY_FAILED",c),W("KEY_PATH_NORMALIZATION_FAILED",c)}let o=li(n);try{ui(o);let a=di(o);i&&kd(i,a);let c=Nd(o),l=0;for(let d of c){let u=Q(r,d.storedPath),m=be.relative(r,u);(m.startsWith("..")||be.isAbsolute(m))&&W("KEY_OUTSIDE_KEYS_DIR",`${d.table}:${d.id}`);let p;try{p=qe.lstatSync(u)}catch{W("MISSING_KEY_FILE",`${d.table}:${d.id}`)}(!p.isFile()||p.isSymbolicLink())&&W("INVALID_KEY_FILE",`${d.table}:${d.id}`);let f=qe.realpathSync(u),_=qe.realpathSync(r),h=be.relative(_,f);(h.startsWith("..")||be.isAbsolute(h))&&W("KEY_OUTSIDE_KEYS_DIR",`${d.table}:${d.id}`);let I;try{I=fe(qe.readFileSync(u),Buffer.from(e.passphrase,"utf8")),Qt(I.toString("utf8"))!==d.publicKey&&W("KEY_PUBLIC_MISMATCH",`${d.table}:${d.id}`)}catch(E){if(String(E).includes("KEY_PUBLIC_MISMATCH"))throw E;W("KEY_DECRYPT_FAILED",`${d.table}:${d.id}`)}finally{I&&ne(I)}l++}return{sqliteIntegrity:"ok",criticalRowCounts:a,referencedKeys:c.length,openedKeys:l}}finally{o.close()}}var nr=".amb-migration-provenance.json",Cn=".amb-migration-attempt",gi=".amb-migration-report.json",Nn=".env.legacy",tt=384;function rr(e){return`${e.stagingRoot}.owner`}function B(e,t){return new Error(t?`${e}: ${t}`:e)}function Cd(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[r,x.resolve(n)]));if(new Set(Object.values(t)).size!==Object.keys(t).length)throw B("MIGRATION_CONFLICT","migration paths must be distinct");if(x.dirname(t.stagingRoot)!==x.dirname(t.ambientRoot))throw B("MIGRATION_CONFLICT","staging must be an Ambient sibling");if(x.dirname(t.backupRoot)!==x.dirname(t.legacyRoot))throw B("MIGRATION_CONFLICT","backup must be a legacy sibling");for(let r of[t.legacyRoot,t.ambientRoot,t.stagingRoot,t.backupRoot]){let n=x.relative(r,t.lockPath);if(n===""||!n.startsWith("..")&&!x.isAbsolute(n))throw B("MIGRATION_CONFLICT","lock must be outside state trees")}}function kn(e,t,r){let n=e.lstat(t);if(!n.isDirectory()||n.isSymbolicLink())throw B(r)}function Dd(e,t,r){let n=e.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw B(r)}function fi(e){return`${JSON.stringify(e,null,2)}
10
- `}function _i(e,t){let r=Ln.createHash("sha256"),n=0;for(let s of[t,`${t}-wal`,`${t}-journal`]){if(!e.exists(s))continue;let i=e.readFile(s);r.update(x.basename(s)),r.update(i),n+=i.length}return{size:n,sha256:r.digest("hex")}}function ir(e){return x.join(e.oldDataDir,"tada-ride-agent.db")}function _e(e){return x.join(e.stagingRoot,"state","data")}function tr(e){return x.join(e.stagingRoot,"state","keys")}function Dn(e){return x.join(e.ambientRoot,"state","data")}function Pd(e){return x.join(e.ambientRoot,"state","keys")}function On(e,t,r){try{return JSON.parse(e.readFile(t).toString("utf8"))}catch{throw B(r)}}function rt(e,t,r){e.fsyncDirectory(x.dirname(t)),e.rename(t,r),e.fsyncDirectory(x.dirname(r))}function yi(e,t,r,n){if(e.exists(t))return;let s=`${t}.${n}.tmp`;e.writeFileExclusive(s,fi(r),tt),e.fsyncFile(s),rt(e,s,t),e.fsyncFile(t)}function Ld(e,t){let r=x.join(_e(e.paths),".env"),n=e.transformEnv??He,s=t.exists(r)?Et({name:"legacy-state",env:t.readFile(r).toString("utf8")}):{},i=n(s,e.paymentNetwork);if(t.exists(r)){let a=x.join(_e(e.paths),Nn);if(t.exists(a))throw B("MIGRATION_COLLISION");rt(t,r,a)}let o=Object.entries(i.env).sort(([a],[c])=>a.localeCompare(c)).map(([a,c])=>`${a}=${c}`);return t.writeFileExclusive(r,`${o.join(`
11
- `)}${o.length?`
12
- `:""}`,tt),t.fsyncFile(r),t.exists(x.join(_e(e.paths),Nn))&&t.unlink(x.join(_e(e.paths),Nn)),t.fsyncDirectory(x.dirname(r)),i}function Od(e,t,r,n,s){let i=_i(e,t);return{schemaVersion:1,attemptId:s,sourcePath:e.realpath(t),sourceDbSize:i.size,sourceDbSha256:i.sha256,criticalRowCounts:r.criticalRowCounts,mappedLegacyConfig:n.mappedLegacyConfig,droppedLegacyConfig:n.droppedLegacyConfig}}function hi(e,t,r){let n=x.join(t.ambientRoot,nr);if(!e.exists(n))throw B("MIGRATION_INTERRUPTED","missing provenance");let s=On(e,n,"MIGRATION_INTERRUPTED"),i=_i(e,r);if(s.schemaVersion!==1||s.sourcePath!==e.realpath(r)||s.sourceDbSize!==i.size||s.sourceDbSha256!==i.sha256)throw B("MIGRATION_INTERRUPTED","source provenance mismatch");return s}function wi(e,t,r){let n=x.join(t.ambientRoot,Cn);if(e.exists(n)){if(e.readFile(n).toString("utf8").trim()!==r)throw B("MIGRATION_INTERRUPTED","attempt provenance mismatch");e.unlink(n),e.fsyncDirectory(t.ambientRoot)}}function Md(e,t){if(!t.exists(e.managedLegacyLink)||!t.lstat(e.managedLegacyLink).isSymbolicLink())return;let n,s;try{n=t.realpath(e.managedLegacyLink),s=t.realpath(e.expectedLegacyLinkTarget)}catch{return}n===s&&(t.unlink(e.managedLegacyLink),t.fsyncDirectory(x.dirname(e.managedLegacyLink)))}function sr(e,t){let r=x.join(t,"state","data"),n=x.join(r,"ambient-ride.db"),s=x.join(r,".env");for(let i of[n,`${n}-wal`,`${n}-shm`,s])e.exists(i)&&e.fsyncFile(i);for(let i of[r,x.join(t,"state","keys"),x.join(t,"state"),t])e.fsyncDirectory(i)}function Pn(e,t){let r=e.validate??vn;try{return r({dataDir:x.join(t,"state","data"),keysDir:x.join(t,"state","keys"),dbPath:x.join(t,"state","data","ambient-ride.db"),sourceDbPath:ir(e),passphrase:Ei(e,t)})}catch{throw B("MIGRATION_VALIDATION_FAILED")}}function Ei(e,t){let r=x.join(t,"state","data",".env"),s=Et({name:"ambient-state",env:e.fs?.readFile(r).toString("utf8")??S.readFileSync(r,"utf8")}).AMB_RIDE_PASSPHRASE;if(!s)throw B("MIGRATION_VALIDATION_FAILED","missing passphrase");return s}function Ri(e,t,r,n){return{schemaVersion:1,status:e,sourcePath:t.paths.legacyRoot,sourceDataPath:t.oldDataDir,sourceKeysPath:t.oldKeysDir,backupPath:t.paths.backupRoot,mappedLegacyConfig:r.mappedLegacyConfig,droppedLegacyConfig:r.droppedLegacyConfig,validation:n}}function Ud(e,t){let r=Et({name:"ambient-state",env:e.readFile(x.join(Dn(t),".env")).toString("utf8")});return{env:Object.fromEntries(Object.entries(r).filter(n=>n[1]!==void 0)),droppedLegacyConfig:[],mappedLegacyConfig:[]}}function bi(e,t){let r=/^(?:TADA_AGENT_|TADA_OPENCLAW_)[A-Z0-9_]+$/,n=/^AMB_RIDE_[A-Z0-9_]+$/;return e.every(s=>typeof s=="object"&&s!==null&&typeof s.from=="string"&&typeof s.to=="string"&&(r.test(s.from)||n.test(s.from))&&n.test(s.to))&&t.every(s=>typeof s=="string"&&r.test(s))}function Ti(e,t){let r=On(e,x.join(t.ambientRoot,nr),"MIGRATION_INTERRUPTED");if(!Array.isArray(r.mappedLegacyConfig)||!Array.isArray(r.droppedLegacyConfig)||!bi(r.mappedLegacyConfig,r.droppedLegacyConfig))throw B("MIGRATION_INTERRUPTED","invalid provenance");return{...Ud(e,t),mappedLegacyConfig:r.mappedLegacyConfig,droppedLegacyConfig:r.droppedLegacyConfig}}function Si(e,t,r,n,s,i){if(e.installManagedCli(),e.smoke(e.paths.ambientRoot),hi(t,e.paths,ir(e)),t.exists(e.paths.backupRoot))throw B("MIGRATION_BACKUP_EXISTS");Md(e,t),rt(t,e.paths.legacyRoot,e.paths.backupRoot);let o=Ri(r,e,s,i);return yi(t,x.join(e.paths.ambientRoot,gi),o,n),o}function Bd(e,t,r){kn(t,e.paths.legacyRoot,"INVALID_LEGACY_ROOT"),kn(t,e.oldDataDir,"INVALID_LEGACY_DATA_DIR"),kn(t,e.oldKeysDir,"INVALID_LEGACY_KEYS_DIR");let n=ir(e);Dd(t,n,"INVALID_LEGACY_DATABASE");let s=e.quiesceLegacy(),i=!1;try{t.writeFileExclusive(rr(e.paths),`${r}
13
- `,tt),t.fsyncFile(rr(e.paths)),t.fsyncDirectory(x.dirname(e.paths.stagingRoot)),i=!0,t.copyTreeExclusive(e.paths.legacyRoot,e.paths.stagingRoot,["cli"]),t.writeFileExclusive(x.join(e.paths.stagingRoot,Cn),`${r}
14
- `,tt),t.fsyncFile(x.join(e.paths.stagingRoot,Cn));let o=x.join(e.paths.stagingRoot,x.relative(e.paths.legacyRoot,e.oldDataDir)),a=x.join(e.paths.stagingRoot,x.relative(e.paths.legacyRoot,e.oldKeysDir));if(x.resolve(o)!==x.resolve(_e(e.paths))){let f=x.join(e.paths.stagingRoot,"state");t.exists(f)||t.mkdirExclusive(f,448),t.exists(_e(e.paths))&&t.removeOwnedPath(_e(e.paths)),t.copyTreeExclusive(e.oldDataDir,_e(e.paths))}if(x.resolve(a)!==x.resolve(tr(e.paths))){let f=x.join(e.paths.stagingRoot,"state");t.exists(f)||t.mkdirExclusive(f,448),t.exists(tr(e.paths))&&t.removeOwnedPath(tr(e.paths)),t.copyTreeExclusive(e.oldKeysDir,tr(e.paths))}let c=Ld(e,t),l=x.join(_e(e.paths),"tada-ride-agent.db"),d=x.join(_e(e.paths),"ambient-ride.db");if(t.exists(d))throw B("MIGRATION_COLLISION");rt(t,l,d);for(let f of["-wal","-shm","-journal"]){let _=`${l}${f}`,h=`${d}${f}`;if(t.exists(_)){if(t.exists(h))throw B("MIGRATION_COLLISION");rt(t,_,h)}}let u=Pn(e,e.paths.stagingRoot);sr(t,e.paths.stagingRoot);let m=Od(t,n,u,c,r);t.writeFileExclusive(x.join(e.paths.stagingRoot,nr),fi(m),tt),t.fsyncFile(x.join(e.paths.stagingRoot,nr)),t.fsyncDirectory(e.paths.stagingRoot),rt(t,e.paths.stagingRoot,e.paths.ambientRoot),i=!1,t.unlink(rr(e.paths)),t.fsyncDirectory(x.dirname(e.paths.stagingRoot)),wi(t,e.paths,r);let p=Pn(e,e.paths.ambientRoot);return sr(t,e.paths.ambientRoot),Si(e,t,"migrated",r,c,p)}catch(o){if(i)try{t.removeOwnedStaging(e.paths.stagingRoot,r)}catch{throw B("MIGRATION_INTERRUPTED","staging cleanup failed")}throw o}finally{s.release()}}function Fd(e,t,r){let n=e.quiesceLegacy();try{let s=ir(e),i=hi(t,e.paths,s);wi(t,e.paths,i.attemptId);let o=Pn(e,e.paths.ambientRoot);return sr(t,e.paths.ambientRoot),Si(e,t,"resumed",r,Ti(t,e.paths),o)}finally{n.release()}}function $d(e,t){let r=rr(t);if(!e.exists(r))return;let n=e.readFile(r).toString("utf8").trim();if(!n||n.includes(`
15
- `))throw B("MIGRATION_CONFLICT","invalid staging owner");e.removeOwnedStaging(t.stagingRoot,n)}function Hd(e,t,r){let n=x.join(e.paths.ambientRoot,gi),s;try{s=(e.validate??vn)({dataDir:Dn(e.paths),keysDir:Pd(e.paths),dbPath:x.join(Dn(e.paths),"ambient-ride.db"),passphrase:Ei(e,e.paths.ambientRoot)})}catch{throw B("MIGRATION_VALIDATION_FAILED")}sr(t,e.paths.ambientRoot);let i=Ti(t,e.paths);if(t.exists(n)){let a=On(t,n,"MIGRATION_INTERRUPTED");if(a.schemaVersion!==1||!["migrated","resumed","already_migrated"].includes(a.status)||!Array.isArray(a.mappedLegacyConfig)||!Array.isArray(a.droppedLegacyConfig)||!bi(a.mappedLegacyConfig,a.droppedLegacyConfig))throw B("MIGRATION_INTERRUPTED","invalid report");return{schemaVersion:1,status:a.status,sourcePath:a.sourcePath,sourceDataPath:a.sourceDataPath,sourceKeysPath:a.sourceKeysPath,backupPath:a.backupPath,mappedLegacyConfig:a.mappedLegacyConfig,droppedLegacyConfig:a.droppedLegacyConfig,validation:s}}let o=Ri("already_migrated",e,i,s);return yi(t,n,o,r),o}function Mn(e){let t=e.fs??Ii,r=e.attemptId??Ln.randomUUID();Cd(e.paths);let n;try{n=t.acquireLock(e.paths.lockPath)}catch{throw B("MIGRATION_CONFLICT","migration lock is held")}try{try{$d(t,e.paths);let s=zs(e.paths,o=>t.exists(o));switch(Qs(e.paths,s).state){case"fresh":return{schemaVersion:1,status:"fresh",mappedLegacyConfig:[],droppedLegacyConfig:[]};case"ambient_fresh":return{schemaVersion:1,status:"ambient_fresh",mappedLegacyConfig:[],droppedLegacyConfig:[]};case"legacy_candidate":return Bd(e,t,r);case"resume_before_backup":return Fd(e,t,r);case"already_migrated":return Hd(e,t,r)}}catch(s){throw/\b(?:MIGRATION_|INVALID_|UNSAFE_|STAGING_)[A-Z_]+/.test(String(s))?s:B("MIGRATION_INTERRUPTED")}}finally{n.release()}}function Ai(e,t,r=[]){let n=S.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw B("UNSAFE_STATE_ENTRY");S.mkdirSync(t,{mode:n.mode&511,recursive:!1});try{for(let i of S.readdirSync(e)){if(r.includes(i))continue;let o=x.join(e,i),a=x.join(t,i),c=S.lstatSync(o);if(c.isSymbolicLink()||!c.isDirectory()&&!c.isFile())throw B("UNSAFE_STATE_ENTRY");if(c.isDirectory())Ai(o,a);else{S.copyFileSync(o,a,S.constants.COPYFILE_EXCL),S.chmodSync(a,c.mode&511),S.chownSync(a,c.uid,c.gid);let l=S.openSync(a,"r");try{S.fsyncSync(l)}finally{S.closeSync(l)}}}S.chmodSync(t,n.mode&511),S.chownSync(t,n.uid,n.gid);let s=S.openSync(t,"r");try{S.fsyncSync(s)}finally{S.closeSync(s)}}catch(s){throw S.rmSync(t,{recursive:!0}),s}}function qd(e,t){let r=`${e}.owner`;if(!S.existsSync(r)||S.readFileSync(r,"utf8").trim()!==t)throw B("STAGING_NOT_OWNED");S.existsSync(e)&&S.rmSync(e,{recursive:!0}),S.unlinkSync(r);let n=S.openSync(x.dirname(e),"r");try{S.fsyncSync(n)}finally{S.closeSync(n)}}function mi(e){let t=S.openSync(e,"r");try{S.fsyncSync(t)}finally{S.closeSync(t)}}var Ii={exists:S.existsSync,lstat:S.lstatSync,mkdirExclusive(e,t){S.mkdirSync(e,{mode:t,recursive:!1})},copyTreeExclusive:Ai,removeOwnedPath(e){S.rmSync(e,{recursive:!0})},rename(e,t){if(S.existsSync(t))throw B("MIGRATION_COLLISION");S.renameSync(e,t)},removeOwnedStaging:qd,writeFileExclusive(e,t,r){S.writeFileSync(e,t,{flag:"wx",mode:r})},readFile:S.readFileSync,readlink:S.readlinkSync,realpath:S.realpathSync,unlink:S.unlinkSync,fsyncFile:mi,fsyncDirectory:mi,acquireLock(e){let t=`${e}.reclaim`,r=(a,c)=>a.dev===c.dev&&a.ino===c.ino,n=()=>{let a=new Error(`EEXIST: migration lock is held, open '${e}'`);return a.code="EEXIST",a},s=(a=!1)=>{if(!a&&S.existsSync(t))throw n();let c;try{return c=S.openSync(e,"wx",tt),S.writeFileSync(c,`${process.pid}
16
- ${Ln.randomUUID()}
17
- `,"utf8"),S.fsyncSync(c),{descriptor:c,identity:S.fstatSync(c)}}catch(l){if(c!==void 0){try{let d=S.lstatSync(e),u=S.fstatSync(c);r(d,u)&&S.unlinkSync(e)}catch{}S.closeSync(c)}throw l}},i;try{i=s()}catch(a){if(a.code!=="EEXIST"||S.existsSync(t))throw a;let c,l;try{c=S.openSync(e,"r"),l=S.fstatSync(c);let u=Number(S.readFileSync(c,"utf8").trim().split(/\s+/u)[0]);throw!Number.isSafeInteger(u)||u<=0||process.kill(u,0),a}catch(u){if(!(u instanceof Error)||!("code"in u)||u.code!=="ESRCH")throw u}finally{c!==void 0&&S.closeSync(c)}try{S.linkSync(e,t)}catch{throw a}let d=S.lstatSync(t);try{let u=S.lstatSync(e);if(l===void 0||!r(l,d)||!r(u,d))throw a;S.unlinkSync(e),i=s(!0)}finally{try{let u=S.lstatSync(t);r(u,d)&&S.unlinkSync(t)}catch{}}}let o=!1;return{release(){if(!o){o=!0,S.closeSync(i.descriptor);try{let a=S.lstatSync(e);r(a,i.identity)&&S.unlinkSync(e)}catch(a){if(a.code!=="ENOENT")throw a}}}}}};function xi(e){return jd.createHash("sha256").update(D.readFileSync(e)).digest("hex")}function Ni(e,t){let r=D.readdirSync(e).sort(),n=D.readdirSync(t).sort();if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("MIGRATION_VALIDATION_FAILED: skill-local entry mismatch");for(let s of r){let i=le.join(e,s),o=le.join(t,s),a=D.lstatSync(i),c=D.lstatSync(o);if(a.isSymbolicLink()||c.isSymbolicLink())throw new Error("UNSAFE_STATE_ENTRY: skill-local symlink");if(a.isDirectory()&&c.isDirectory()){Ni(i,o);continue}if(!a.isFile()||!c.isFile()||xi(i)!==xi(o))throw new Error("MIGRATION_VALIDATION_FAILED: skill-local content mismatch")}}function ki(e){for(let r of D.readdirSync(e)){let n=le.join(e,r);if(D.lstatSync(n).isDirectory())ki(n);else{let i=D.openSync(n,"r");try{D.fsyncSync(i)}finally{D.closeSync(i)}}}let t=D.openSync(e,"r");try{D.fsyncSync(t)}finally{D.closeSync(t)}}function vi(e){let t=`${e}.${process.pid}.tmp`;D.writeFileSync(t,new Date().toISOString(),{flag:"wx",mode:384});let r=D.openSync(t,"r");try{D.fsyncSync(r)}finally{D.closeSync(r)}D.renameSync(t,e);let n=D.openSync(le.dirname(e),"r");try{D.fsyncSync(n)}finally{D.closeSync(n)}}function or(e,t){let r=le.join(t,".migrated-from-legacy");if(D.existsSync(r))return{migrated:!1,reason:"already-migrated"};if(!D.existsSync(e))return{migrated:!1,reason:"no-legacy"};let n=le.join(t,"data");if(D.existsSync(le.join(n,"tada-ride-agent.db")))return D.mkdirSync(t,{recursive:!0}),vi(r),{migrated:!1,reason:"target-already-populated"};if(D.existsSync(t))throw new Error("MIGRATION_CONFLICT: partial intermediate legacy state");let s=`${t}.skill-migrating`;D.mkdirSync(le.dirname(t),{recursive:!0,mode:448}),D.existsSync(s)&&D.rmSync(s,{recursive:!0}),D.mkdirSync(s,{recursive:!1,mode:448});try{for(let o of["data","keys"]){let a=le.join(e,o);if(!D.existsSync(a))continue;let c=le.join(s,o);D.cpSync(a,c,{recursive:!0,errorOnExist:!0,force:!1}),Ni(a,c)}ki(s),D.renameSync(s,t);let i=D.openSync(le.dirname(t),"r");try{D.fsyncSync(i)}finally{D.closeSync(i)}}catch(i){throw D.existsSync(s)&&D.rmSync(s,{recursive:!0}),i}return vi(r),{migrated:!0,reason:"copied"}}var Gd=/^\d+\.\d+\.\d+$/,Ci=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Z(e,t){return new Error(`Invalid AmbBuildConfig at ${e}: ${t}`)}function Te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Z(t,"expected an object");return e}function ke(e,t,r){let n=new Set(t),s=Object.keys(e).filter(o=>!n.has(o)),i=t.filter(o=>!Ci(e,o));if(s.length>0)throw Z(r,`unknown field ${s[0]}`);if(i.length>0)throw Z(`${r}.${i[0]}`,"is required")}function q(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw Z(t,r?"expected a string":"expected a non-empty string");return e}function Un(e,t){let r=q(e,t);if(!Gd.test(r))throw Z(t,"expected stable three-part SemVer");return r}function Rt(e,t,r={}){if(typeof e!="number"||!Number.isFinite(e))throw Z(t,"expected a finite number");if(r.integer&&!Number.isInteger(e))throw Z(t,"expected an integer");if(r.min!==void 0&&e<r.min)throw Z(t,`must be >= ${r.min}`);if(r.max!==void 0&&e>r.max)throw Z(t,`must be <= ${r.max}`);return e}function Wd(e,t){if(!Array.isArray(e)||e.length===0)throw Z(t,"expected a non-empty string array");return e.map((r,n)=>q(r,`${t}[${n}]`))}function Vd(e,t){let r=Te(e,t),n={};for(let[s,i]of Object.entries(r)){if(s.length===0)throw Z(t,"contains an empty key");n[s]=q(i,`${t}.${s}`)}return n}function Jd(e){let t=Te(e,"bridgePolicy");ke(t,["minimumUsdc","maxFeeBufferPct","burnGraceBlocks","mintMaxAttempts","leaseSeconds","logChunkBlocks"],"bridgePolicy");let r=q(t.minimumUsdc,"bridgePolicy.minimumUsdc"),n=Number(r);if(!Number.isFinite(n)||n<0)throw Z("bridgePolicy.minimumUsdc","expected a non-negative decimal number");return{minimumUsdc:r,maxFeeBufferPct:Rt(t.maxFeeBufferPct,"bridgePolicy.maxFeeBufferPct",{min:0,max:100}),burnGraceBlocks:Rt(t.burnGraceBlocks,"bridgePolicy.burnGraceBlocks",{integer:!0,min:1}),mintMaxAttempts:Rt(t.mintMaxAttempts,"bridgePolicy.mintMaxAttempts",{integer:!0,min:1}),leaseSeconds:Rt(t.leaseSeconds,"bridgePolicy.leaseSeconds",{integer:!0,min:1}),logChunkBlocks:Rt(t.logChunkBlocks,"bridgePolicy.logChunkBlocks",{integer:!0,min:1})}}function Di(e){if(typeof e!="object"||e===null||Object.isFrozen(e))return e;for(let t of Object.values(e))Di(t);return Object.freeze(e)}function Kd(e){let t=Te(e,"buildConfig");ke(t,["services","networks","providers","artifact","install","bridgePolicy"],"buildConfig");let r=Te(t.services,"services");ke(r,["authServerUrl","authWebappUrl","privyAppId","cryptoGatewayUrl","memberGatewayUrls","defaultRegion"],"services");let n=Te(t.networks,"networks");ke(n,["depositNetworks","paymentNetwork","paymentCurrency","paymentUsdcAddress","bridgeSource","bridgeDestination"],"networks");let s=Te(t.providers,"providers");ke(s,["tada"],"providers");let i=Te(s.tada,"providers.tada");ke(i,["memberClientId","memberClientSecret"],"providers.tada");let o=Te(t.artifact,"artifact");ke(o,["cliVersion","gitSha"],"artifact");let a=Te(t.install,"install"),c=q(a.mode,"install.mode");if(c!=="git"&&c!=="npm")throw Z("install.mode","expected git or npm");ke(a,c==="git"?["mode","repoBranch","repoUrl","expectedCliSha","minimumCliVersion"]:["mode","repoBranch","expectedCliSha","minimumCliVersion"],"install");let l=q(a.expectedCliSha,"install.expectedCliSha",c==="npm"),d=Vd(r.memberGatewayUrls,"services.memberGatewayUrls"),u=q(r.defaultRegion,"services.defaultRegion");if(!Ci(d,u))throw Z("services.defaultRegion","must name a memberGatewayUrls entry");return Di({services:{authServerUrl:q(r.authServerUrl,"services.authServerUrl"),authWebappUrl:q(r.authWebappUrl,"services.authWebappUrl"),privyAppId:q(r.privyAppId,"services.privyAppId"),cryptoGatewayUrl:q(r.cryptoGatewayUrl,"services.cryptoGatewayUrl"),memberGatewayUrls:d,defaultRegion:u},networks:{depositNetworks:Wd(n.depositNetworks,"networks.depositNetworks"),paymentNetwork:q(n.paymentNetwork,"networks.paymentNetwork"),paymentCurrency:q(n.paymentCurrency,"networks.paymentCurrency"),paymentUsdcAddress:q(n.paymentUsdcAddress,"networks.paymentUsdcAddress"),bridgeSource:q(n.bridgeSource,"networks.bridgeSource",!0),bridgeDestination:q(n.bridgeDestination,"networks.bridgeDestination",!0)},providers:{tada:{memberClientId:q(i.memberClientId,"providers.tada.memberClientId",!0),memberClientSecret:q(i.memberClientSecret,"providers.tada.memberClientSecret",!0)}},artifact:{cliVersion:Un(o.cliVersion,"artifact.cliVersion"),gitSha:q(o.gitSha,"artifact.gitSha")},install:c==="git"?{mode:"git",repoBranch:q(a.repoBranch,"install.repoBranch"),repoUrl:q(a.repoUrl,"install.repoUrl"),expectedCliSha:l,minimumCliVersion:Un(a.minimumCliVersion,"install.minimumCliVersion")}:{mode:"npm",repoBranch:q(a.repoBranch,"install.repoBranch"),expectedCliSha:l,minimumCliVersion:Un(a.minimumCliVersion,"install.minimumCliVersion")},bridgePolicy:Jd(t.bridgePolicy)})}var Yd,ar;function z(){return ar||(ar=Kd(Yd??y),ar)}var Xd={AMB_RIDE_STATE_DIR:"stateDir",AMB_RIDE_PASSPHRASE:"passphrase",AMB_RIDE_LOG_LEVEL:"logLevel",AMB_RIDE_OPENCLAW_CLI:"openclawCli"},zd=/^AMB_RIDE_RPC_URL_([A-Z0-9_]+)$/,Pi=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function cr(e){let t=e.toUpperCase();if(!Pi.test(t))throw new Error(`Invalid Ambient Ride RPC network: ${e}`);return`AMB_RIDE_RPC_URL_${t}`}function je(e=process.env){let t={rpcUrls:{}};for(let[r,n]of Object.entries(e)){if(!r.startsWith("AMB_RIDE_"))continue;let s=Xd[r];if(s!==void 0){n!==void 0&&(t[s]=n);continue}let i=zd.exec(r);if(i&&Pi.test(i[1])){n!==void 0&&(t.rpcUrls[i[1]]=n);continue}throw new Error(`Unknown Ambient Ride runtime environment variable: ${r}`)}return t}function Bn(e,t,r){return t.rpcUrls[e]??r[e]}function Zd(e){let t=e;for(;;){if(Fn.existsSync(Ge.join(t,"SKILL.md")))return t;let r=Ge.dirname(t);if(r===t)break;t=r}return Ge.dirname(Ge.dirname(e))}function eu(){let e=Ge.dirname(Qd(import.meta.url));return Zd(e)}function tu(e){if(!Fn.existsSync(e))return{};let t={};for(let r of Fn.readFileSync(e,"utf8").split(`
18
- `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");s<=0||(t[n.slice(0,s).trim()]=n.slice(s+1).trim())}return t}var nt={BASE_SEPOLIA:84532,BASE:8453,ETHEREUM:1,ETHEREUM_SEPOLIA:11155111},$n={BASE_SEPOLIA:"https://sepolia.base.org",BASE:"https://mainnet.base.org",ETHEREUM:"https://eth.drpc.org",ETHEREUM_SEPOLIA:"https://sepolia.drpc.org"},ru={BASE_SEPOLIA:"0xcC1F1b0C7b505D94ee04E028eA19f81464AdefA9",ETHEREUM:"0xA4bAE3CeFA30F6A263402D388261c611663b2683"},nu={BASE_SEPOLIA:"0x3B7E10b1AEA923E13e2716b538789b6EC9F0A4c1",ETHEREUM:"0x5c23a543963A181267d5790d61eBa55b66246f0a"},Hn={ETHEREUM:{domain:0,tokenMessengerV2:"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",messageTransmitterV2:"0x81D40F21F12A8F0E3252Bccb954D722d4c464B64",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",irisBaseUrl:"https://iris-api.circle.com",testnet:!1},ETHEREUM_SEPOLIA:{domain:0,tokenMessengerV2:"0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA",messageTransmitterV2:"0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275",usdc:"0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",irisBaseUrl:"https://iris-api-sandbox.circle.com",testnet:!0},BASE:{domain:6,tokenMessengerV2:"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",messageTransmitterV2:"0x81D40F21F12A8F0E3252Bccb954D722d4c464B64",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",testnet:!1},BASE_SEPOLIA:{domain:6,tokenMessengerV2:"0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA",messageTransmitterV2:"0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275",usdc:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",testnet:!0}};function su(e){return Hn[e]}var iu=Object.entries(Hn).filter(([,e])=>e.irisBaseUrl).map(([e])=>e);function ou(e,t=je()){return Bn(e,t,$n)}function Li(e,t,r,n=je()){if(!t)return{error:`${e} is not set \u2014 this build has no USDC bridge configured.`};let s=su(t);if(!s)return{error:`${e}=${t} is not a CCTP network. Known networks: ${Object.keys(Hn).join(", ")}.`};let i=nt[t];if(i===void 0)return{error:`${e}=${t} has no chain id configured. Known networks: ${Object.keys(nt).join(", ")}.`};if(r==="source"&&!s.irisBaseUrl)return{error:`${e}=${t} is not supported as a bridge source (no Circle attestation host). Supported sources: ${iu.join(", ")}.`};let o=ou(t,n);if(!o)return{error:`No RPC URL for ${t}. Set ${cr(t)}.`};let a={name:t,chainId:i,rpcUrl:o,usdcAddress:s.usdc,cctpDomain:s.domain,tokenMessengerV2:s.tokenMessengerV2};return r==="source"?{endpoint:{...a,role:"source"},net:s}:{endpoint:{...a,role:"dest",messageTransmitterV2:s.messageTransmitterV2},net:s}}function au(e=z().networks.bridgeSource,t=z().networks.bridgeDestination,r=je()){let n=Li("bridge source",e,"source",r);if(!n.endpoint||!n.net)return{error:n.error??"Bridge source could not be resolved."};let s=Li("bridge destination",t,"dest",r);if(!s.endpoint||!s.net)return{error:s.error??"Bridge destination could not be resolved."};if(n.endpoint.name===s.endpoint.name)return{error:`Bridge source and destination are both ${n.endpoint.name} \u2014 a bridge needs two different networks.`};let i=n.net,o=s.net;if(i.testnet!==o.testnet){let a=c=>c.testnet?"testnet":"mainnet";return{error:`Bridge source ${n.endpoint.name} (${a(i)}) and destination ${s.endpoint.name} (${a(o)}) are on different network environments \u2014 mainnet vs testnet cannot be bridged. CCTP domains do not distinguish the two, so this would burn on ${a(i)} and mint on the ${a(i)} chain with domain ${o.domain}, not on ${s.endpoint.name}.`}}return{bridge:{source:n.endpoint,dest:s.endpoint,irisBaseUrl:i.irisBaseUrl}}}function R(){let e=z(),t=eu();or(Kt(t),Ge.join(F(),"state"));let r=et(),n=Xs(),s=tu(Ge.join(r,".env"));for(let[f,_]of Object.entries(s))process.env[f]===void 0&&(process.env[f]=_);let i=je();function o(f,_){if(f)return f;g({error:`Missing required environment variable: ${_} \u2014 local state is not initialised. Run \`amb install\`.`}),process.exit(1)}let c=e.networks.depositNetworks.map(f=>{let _=i.rpcUrls[f]??$n[f];_||(g({error:`Missing ${cr(f)} and no default RPC URL for network ${f}`}),process.exit(1));let h=ru[f];h||(g({error:`No v2 DepositRouter address configured for network ${f}. Mainnet \uC8FC\uC18C\uB294 Kaelie \uCE21 v2 \uBC30\uD3EC \uD6C4 \uCD94\uAC00.`}),process.exit(1));let I=nu[f];I||(g({error:`No v2 AgentDepositV2 ledger address for network ${f}.`}),process.exit(1));let E=nt[f];return E===void 0&&(g({error:`Unknown network name: ${f}. Known networks: ${Object.keys(nt).join(", ")}`}),process.exit(1)),{name:f,rpcUrl:_,chainId:E,depositContract:h,agentDepositLedger:I}}),l=e.networks.paymentNetwork,d=nt[l];d===void 0&&(g({error:`Unknown payment network name: ${l}. Known networks: ${Object.keys(nt).join(", ")}`}),process.exit(1));let u=Bn(l,i,$n);u||(g({error:`Missing ${cr(l)} and no default RPC URL for payment network ${l}`}),process.exit(1));let m=au(e.networks.bridgeSource,e.networks.bridgeDestination,i),p=e.bridgePolicy;return{appServerUrl:e.services.authServerUrl,webappUrl:e.services.authWebappUrl,privyAppId:e.services.privyAppId,dataDir:r,keysDir:n,depositNetworks:c,gatewayServerUrl:e.services.cryptoGatewayUrl,passphrase:o(i.passphrase,"AMB_RIDE_PASSPHRASE"),payCurrency:e.networks.paymentCurrency,paymentNetwork:l,paymentRpcUrl:u,paymentChainId:d,paymentUsdcAddress:e.networks.paymentUsdcAddress,cliGatewayHost:e.services.memberGatewayUrls[e.services.defaultRegion],cliGatewayHosts:e.services.memberGatewayUrls,riderCliApp:{clientId:e.providers.tada.memberClientId,clientSecret:e.providers.tada.memberClientSecret},bridge:m.bridge,bridgeConfigError:m.error,bridgeMinUsdc:p.minimumUsdc,bridgeMaxFeeBufferPct:p.maxFeeBufferPct,bridgeBurnGraceBlocks:p.burnGraceBlocks,bridgeMintMaxAttempts:p.mintMaxAttempts,bridgeLeaseSec:p.leaseSeconds,bridgeLogChunkBlocks:p.logChunkBlocks}}function Oi(e){return e.riderCliApp.clientId!==""&&e.riderCliApp.clientSecret!==""}function bt(){let e=z(),t=e.providers.tada.memberClientId,r=e.providers.tada.memberClientSecret,n=e.services.memberGatewayUrls[e.services.defaultRegion]??"";return t!==""&&r!==""&&n!==""}import du from"better-sqlite3";import dr from"fs";import ur from"path";import Se from"fs";import lr from"path";import cu from"better-sqlite3";var Ui="tada-ride-agent.db",Mi="ambient-ride.db",Bi=["","-wal","-shm","-journal"];function lu(e){let t=Se.openSync(e,"r");try{Se.fsyncSync(t)}finally{Se.closeSync(t)}}function Tt(e){return Bi.some(t=>Se.existsSync(lr.join(e,`${Ui}${t}`)))}function Fi(e){if(!Tt(e))return!1;Se.mkdirSync(e,{recursive:!0,mode:448});for(let n of Bi){let s=lr.join(e,`${Ui}${n}`),i=lr.join(e,`${Mi}${n}`);if(Se.existsSync(s)){if(Se.existsSync(i))throw new Error(`MIGRATION_CONFLICT: both database names exist (${n||"main"})`);Se.renameSync(s,i),lu(e)}}let t=lr.join(e,Mi);if(!Se.existsSync(t))throw new Error("MIGRATION_INTERRUPTED: database sidecar exists without main database");let r=new cu(t,{readonly:!0,fileMustExist:!0});try{if(r.pragma("integrity_check",{simple:!0})!=="ok")throw new Error("MIGRATION_VALIDATION_FAILED: database integrity")}finally{r.close()}return!0}var $i=je().logLevel==="debug";function Hi(){return $i}function oe(e){$i&&process.stderr.write(e)}function st(e){return e.placeId?`gid:${e.placeId}`:Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)?`coord:${e.latitude.toFixed(4)},${e.longitude.toFixed(4)}`:null}var L;function b(e){let t=ur.dirname(e),r=ur.basename(t)==="state"?ur.dirname(t):t;if(dr.existsSync(`${r}.amb-migration-quiesced`))throw new Error("MIGRATION_CONFLICT: runtime state is being migrated");dr.existsSync(e)||dr.mkdirSync(e,{recursive:!0});let n=ur.join(e,"ambient-ride.db");if(!dr.existsSync(n)&&Tt(e))throw new Error("LEGACY_AMBIENT_DATABASE: run `amb install` before using the CLI");L=new du(n),L.pragma("journal_mode = WAL"),L.pragma("foreign_keys = ON"),L.exec(`
30
+ `).map(n=>`${r} ${n}`)]:[`${r}${Lo(e)}`]}function rd(e){return ko(e,0).join(`
31
+ `)}var Xs="json";function nd(e){Xs=e}function Kn(){return Xs}function sd(e){return{json:e.includes("--json"),argv:e.filter(t=>t!=="--json")}}function w(e){console.log(Xs==="json"?JSON.stringify(e,null,2):rd(e))}function b(e){console.error(Xs==="json"?JSON.stringify(e):rd(e))}p();import Fo from"fs";import wr from"path";import{fileURLToPath as UA}from"url";p();import id from"os";import tn from"path";function SA(e){return e.startsWith("~/")?tn.join(id.homedir(),e.slice(2)):tn.resolve(e)}function ge(){return SA(process.env.AMB_RIDE_STATE_DIR??tn.join(id.homedir(),".amb"))}function rn(){return tn.join(ge(),"state","data")}function ad(){return tn.join(ge(),"state","keys")}function Qs(e){return tn.join(e,".tada-state")}p();import ee from"fs";import It from"path";import IA from"crypto";function od(e){return IA.createHash("sha256").update(ee.readFileSync(e)).digest("hex")}function ld(e,t){let r=ee.readdirSync(e).sort(),n=ee.readdirSync(t).sort();if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("MIGRATION_VALIDATION_FAILED: skill-local entry mismatch");for(let s of r){let i=It.join(e,s),a=It.join(t,s),o=ee.lstatSync(i),c=ee.lstatSync(a);if(o.isSymbolicLink()||c.isSymbolicLink())throw new Error("UNSAFE_STATE_ENTRY: skill-local symlink");if(o.isDirectory()&&c.isDirectory()){ld(i,a);continue}if(!o.isFile()||!c.isFile()||od(i)!==od(a))throw new Error("MIGRATION_VALIDATION_FAILED: skill-local content mismatch")}}function ud(e){for(let r of ee.readdirSync(e)){let n=It.join(e,r);if(ee.lstatSync(n).isDirectory())ud(n);else{let i=ee.openSync(n,"r");try{ee.fsyncSync(i)}finally{ee.closeSync(i)}}}let t=ee.openSync(e,"r");try{ee.fsyncSync(t)}finally{ee.closeSync(t)}}function cd(e){let t=`${e}.${process.pid}.tmp`;ee.writeFileSync(t,new Date().toISOString(),{flag:"wx",mode:384});let r=ee.openSync(t,"r");try{ee.fsyncSync(r)}finally{ee.closeSync(r)}ee.renameSync(t,e);let n=ee.openSync(It.dirname(e),"r");try{ee.fsyncSync(n)}finally{ee.closeSync(n)}}function Zs(e,t){let r=It.join(t,".migrated-from-legacy");if(ee.existsSync(r))return{migrated:!1,reason:"already-migrated"};if(!ee.existsSync(e))return{migrated:!1,reason:"no-legacy"};let n=It.join(t,"data");if(ee.existsSync(It.join(n,"tada-ride-agent.db")))return ee.mkdirSync(t,{recursive:!0}),cd(r),{migrated:!1,reason:"target-already-populated"};if(ee.existsSync(t))throw new Error("MIGRATION_CONFLICT: partial intermediate legacy state");let s=`${t}.skill-migrating`;ee.mkdirSync(It.dirname(t),{recursive:!0,mode:448}),ee.existsSync(s)&&ee.rmSync(s,{recursive:!0}),ee.mkdirSync(s,{recursive:!1,mode:448});try{for(let a of["data","keys"]){let o=It.join(e,a);if(!ee.existsSync(o))continue;let c=It.join(s,a);ee.cpSync(o,c,{recursive:!0,errorOnExist:!0,force:!1}),ld(o,c)}ud(s),ee.renameSync(s,t);let i=ee.openSync(It.dirname(t),"r");try{ee.fsyncSync(i)}finally{ee.closeSync(i)}}catch(i){throw ee.existsSync(s)&&ee.rmSync(s,{recursive:!0}),i}return cd(r),{migrated:!0,reason:"copied"}}p();var PA=/^\d+\.\d+\.\d+$/,dd=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function et(e,t){return new Error(`Invalid AmbBuildConfig at ${e}: ${t}`)}function Yt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw et(t,"expected an object");return e}function or(e,t,r){let n=new Set(t),s=Object.keys(e).filter(a=>!n.has(a)),i=t.filter(a=>!dd(e,a));if(s.length>0)throw et(r,`unknown field ${s[0]}`);if(i.length>0)throw et(`${r}.${i[0]}`,"is required")}function be(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw et(t,r?"expected a string":"expected a non-empty string");return e}function Mo(e,t){let r=be(e,t);if(!PA.test(r))throw et(t,"expected stable three-part SemVer");return r}function Yn(e,t,r={}){if(typeof e!="number"||!Number.isFinite(e))throw et(t,"expected a finite number");if(r.integer&&!Number.isInteger(e))throw et(t,"expected an integer");if(r.min!==void 0&&e<r.min)throw et(t,`must be >= ${r.min}`);if(r.max!==void 0&&e>r.max)throw et(t,`must be <= ${r.max}`);return e}function DA(e,t){if(!Array.isArray(e)||e.length===0)throw et(t,"expected a non-empty string array");return e.map((r,n)=>be(r,`${t}[${n}]`))}function OA(e,t){let r=Yt(e,t),n={};for(let[s,i]of Object.entries(r)){if(s.length===0)throw et(t,"contains an empty key");n[s]=be(i,`${t}.${s}`)}return n}function CA(e){let t=Yt(e,"bridgePolicy");or(t,["minimumUsdc","maxFeeBufferPct","burnGraceBlocks","mintMaxAttempts","leaseSeconds","logChunkBlocks"],"bridgePolicy");let r=be(t.minimumUsdc,"bridgePolicy.minimumUsdc"),n=Number(r);if(!Number.isFinite(n)||n<0)throw et("bridgePolicy.minimumUsdc","expected a non-negative decimal number");return{minimumUsdc:r,maxFeeBufferPct:Yn(t.maxFeeBufferPct,"bridgePolicy.maxFeeBufferPct",{min:0,max:100}),burnGraceBlocks:Yn(t.burnGraceBlocks,"bridgePolicy.burnGraceBlocks",{integer:!0,min:1}),mintMaxAttempts:Yn(t.mintMaxAttempts,"bridgePolicy.mintMaxAttempts",{integer:!0,min:1}),leaseSeconds:Yn(t.leaseSeconds,"bridgePolicy.leaseSeconds",{integer:!0,min:1}),logChunkBlocks:Yn(t.logChunkBlocks,"bridgePolicy.logChunkBlocks",{integer:!0,min:1})}}function pd(e){if(typeof e!="object"||e===null||Object.isFrozen(e))return e;for(let t of Object.values(e))pd(t);return Object.freeze(e)}function NA(e){let t=Yt(e,"buildConfig");or(t,["services","networks","providers","artifact","install","bridgePolicy"],"buildConfig");let r=Yt(t.services,"services");or(r,["authServerUrl","ambTelemetryServiceUrl","authWebappUrl","privyAppId","cryptoGatewayUrl","memberGatewayUrls","defaultRegion"],"services");let n=Yt(t.networks,"networks");or(n,["depositNetworks","paymentNetwork","paymentCurrency","paymentUsdcAddress","bridgeSource","bridgeDestination"],"networks");let s=Yt(t.providers,"providers");or(s,["tada"],"providers");let i=Yt(s.tada,"providers.tada");or(i,["memberClientId","memberClientSecret"],"providers.tada");let a=Yt(t.artifact,"artifact");or(a,["cliVersion","gitSha"],"artifact");let o=Yt(t.install,"install"),c=be(o.mode,"install.mode");if(c!=="git"&&c!=="npm")throw et("install.mode","expected git or npm");or(o,c==="git"?["mode","repoBranch","repoUrl","expectedCliSha","minimumCliVersion"]:["mode","repoBranch","expectedCliSha","minimumCliVersion"],"install");let u=be(o.expectedCliSha,"install.expectedCliSha",c==="npm"),l=OA(r.memberGatewayUrls,"services.memberGatewayUrls"),d=be(r.defaultRegion,"services.defaultRegion");if(!dd(l,d))throw et("services.defaultRegion","must name a memberGatewayUrls entry");return pd({services:{authServerUrl:be(r.authServerUrl,"services.authServerUrl"),ambTelemetryServiceUrl:be(r.ambTelemetryServiceUrl,"services.ambTelemetryServiceUrl"),authWebappUrl:be(r.authWebappUrl,"services.authWebappUrl"),privyAppId:be(r.privyAppId,"services.privyAppId"),cryptoGatewayUrl:be(r.cryptoGatewayUrl,"services.cryptoGatewayUrl"),memberGatewayUrls:l,defaultRegion:d},networks:{depositNetworks:DA(n.depositNetworks,"networks.depositNetworks"),paymentNetwork:be(n.paymentNetwork,"networks.paymentNetwork"),paymentCurrency:be(n.paymentCurrency,"networks.paymentCurrency"),paymentUsdcAddress:be(n.paymentUsdcAddress,"networks.paymentUsdcAddress"),bridgeSource:be(n.bridgeSource,"networks.bridgeSource",!0),bridgeDestination:be(n.bridgeDestination,"networks.bridgeDestination",!0)},providers:{tada:{memberClientId:be(i.memberClientId,"providers.tada.memberClientId",!0),memberClientSecret:be(i.memberClientSecret,"providers.tada.memberClientSecret",!0)}},artifact:{cliVersion:Mo(a.cliVersion,"artifact.cliVersion"),gitSha:be(a.gitSha,"artifact.gitSha")},install:c==="git"?{mode:"git",repoBranch:be(o.repoBranch,"install.repoBranch"),repoUrl:be(o.repoUrl,"install.repoUrl"),expectedCliSha:u,minimumCliVersion:Mo(o.minimumCliVersion,"install.minimumCliVersion")}:{mode:"npm",repoBranch:be(o.repoBranch,"install.repoBranch"),expectedCliSha:u,minimumCliVersion:Mo(o.minimumCliVersion,"install.minimumCliVersion")},bridgePolicy:CA(t.bridgePolicy)})}var LA,ei;function De(){return ei||(ei=NA(LA??y),ei)}p();var kA={AMB_RIDE_STATE_DIR:"stateDir",AMB_RIDE_PASSPHRASE:"passphrase",AMB_RIDE_LOG_LEVEL:"logLevel",AMB_RIDE_OPENCLAW_CLI:"openclawCli"},MA=/^AMB_RIDE_RPC_URL_([A-Z0-9_]+)$/,md=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function ti(e){let t=e.toUpperCase();if(!md.test(t))throw new Error(`Invalid Ambient Ride RPC network: ${e}`);return`AMB_RIDE_RPC_URL_${t}`}function Ar(e=process.env){let t={rpcUrls:{}};for(let[r,n]of Object.entries(e)){if(!r.startsWith("AMB_RIDE_"))continue;let s=kA[r];if(s!==void 0){n!==void 0&&(t[s]=n);continue}let i=MA.exec(r);if(i&&md.test(i[1])){n!==void 0&&(t.rpcUrls[i[1]]=n);continue}throw new Error(`Unknown Ambient Ride runtime environment variable: ${r}`)}return t}p();function Uo(e,t,r){return t.rpcUrls[e]??r[e]}function FA(e){let t=e;for(;;){if(Fo.existsSync(wr.join(t,"SKILL.md")))return t;let r=wr.dirname(t);if(r===t)break;t=r}return wr.dirname(wr.dirname(e))}function jA(){let e=wr.dirname(UA(import.meta.url));return FA(e)}function qA(e){if(!Fo.existsSync(e))return{};let t={};for(let r of Fo.readFileSync(e,"utf8").split(`
32
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");s<=0||(t[n.slice(0,s).trim()]=n.slice(s+1).trim())}return t}var nn={BASE_SEPOLIA:84532,BASE:8453,ETHEREUM:1,ETHEREUM_SEPOLIA:11155111},jo={BASE_SEPOLIA:"https://sepolia.base.org",BASE:"https://mainnet.base.org",ETHEREUM:"https://eth.drpc.org",ETHEREUM_SEPOLIA:"https://sepolia.drpc.org"},BA={BASE_SEPOLIA:"0xcC1F1b0C7b505D94ee04E028eA19f81464AdefA9",ETHEREUM:"0xA4bAE3CeFA30F6A263402D388261c611663b2683"},VA={BASE_SEPOLIA:"0x3B7E10b1AEA923E13e2716b538789b6EC9F0A4c1",ETHEREUM:"0x5c23a543963A181267d5790d61eBa55b66246f0a"},qo={ETHEREUM:{domain:0,tokenMessengerV2:"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",messageTransmitterV2:"0x81D40F21F12A8F0E3252Bccb954D722d4c464B64",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",irisBaseUrl:"https://iris-api.circle.com",testnet:!1},ETHEREUM_SEPOLIA:{domain:0,tokenMessengerV2:"0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA",messageTransmitterV2:"0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275",usdc:"0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",irisBaseUrl:"https://iris-api-sandbox.circle.com",testnet:!0},BASE:{domain:6,tokenMessengerV2:"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",messageTransmitterV2:"0x81D40F21F12A8F0E3252Bccb954D722d4c464B64",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",testnet:!1},BASE_SEPOLIA:{domain:6,tokenMessengerV2:"0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA",messageTransmitterV2:"0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275",usdc:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",testnet:!0}};function GA(e){return qo[e]}var HA=Object.entries(qo).filter(([,e])=>e.irisBaseUrl).map(([e])=>e);function $A(e,t=Ar()){return Uo(e,t,jo)}function fd(e,t,r,n=Ar()){if(!t)return{error:`${e} is not set \u2014 this build has no USDC bridge configured.`};let s=GA(t);if(!s)return{error:`${e}=${t} is not a CCTP network. Known networks: ${Object.keys(qo).join(", ")}.`};let i=nn[t];if(i===void 0)return{error:`${e}=${t} has no chain id configured. Known networks: ${Object.keys(nn).join(", ")}.`};if(r==="source"&&!s.irisBaseUrl)return{error:`${e}=${t} is not supported as a bridge source (no Circle attestation host). Supported sources: ${HA.join(", ")}.`};let a=$A(t,n);if(!a)return{error:`No RPC URL for ${t}. Set ${ti(t)}.`};let o={name:t,chainId:i,rpcUrl:a,usdcAddress:s.usdc,cctpDomain:s.domain,tokenMessengerV2:s.tokenMessengerV2};return r==="source"?{endpoint:{...o,role:"source"},net:s}:{endpoint:{...o,role:"dest",messageTransmitterV2:s.messageTransmitterV2},net:s}}function WA(e=De().networks.bridgeSource,t=De().networks.bridgeDestination,r=Ar()){let n=fd("bridge source",e,"source",r);if(!n.endpoint||!n.net)return{error:n.error??"Bridge source could not be resolved."};let s=fd("bridge destination",t,"dest",r);if(!s.endpoint||!s.net)return{error:s.error??"Bridge destination could not be resolved."};if(n.endpoint.name===s.endpoint.name)return{error:`Bridge source and destination are both ${n.endpoint.name} \u2014 a bridge needs two different networks.`};let i=n.net,a=s.net;if(i.testnet!==a.testnet){let o=c=>c.testnet?"testnet":"mainnet";return{error:`Bridge source ${n.endpoint.name} (${o(i)}) and destination ${s.endpoint.name} (${o(a)}) are on different network environments \u2014 mainnet vs testnet cannot be bridged. CCTP domains do not distinguish the two, so this would burn on ${o(i)} and mint on the ${o(i)} chain with domain ${a.domain}, not on ${s.endpoint.name}.`}}return{bridge:{source:n.endpoint,dest:s.endpoint,irisBaseUrl:i.irisBaseUrl}}}function D(){let e=De(),t=jA();Zs(Qs(t),wr.join(ge(),"state"));let r=rn(),n=ad(),s=qA(wr.join(r,".env"));for(let[g,_]of Object.entries(s))process.env[g]===void 0&&(process.env[g]=_);let i=Ar();function a(g,_){if(g)return g;b({error:`Missing required environment variable: ${_} \u2014 local state is not initialised. Run \`amb install\`.`}),process.exit(1)}let c=e.networks.depositNetworks.map(g=>{let _=i.rpcUrls[g]??jo[g];_||(b({error:`Missing ${ti(g)} and no default RPC URL for network ${g}`}),process.exit(1));let E=BA[g];E||(b({error:`No v2 DepositRouter address configured for network ${g}. Mainnet \uC8FC\uC18C\uB294 Kaelie \uCE21 v2 \uBC30\uD3EC \uD6C4 \uCD94\uAC00.`}),process.exit(1));let T=VA[g];T||(b({error:`No v2 AgentDepositV2 ledger address for network ${g}.`}),process.exit(1));let x=nn[g];return x===void 0&&(b({error:`Unknown network name: ${g}. Known networks: ${Object.keys(nn).join(", ")}`}),process.exit(1)),{name:g,rpcUrl:_,chainId:x,depositContract:E,agentDepositLedger:T}}),u=e.networks.paymentNetwork,l=nn[u];l===void 0&&(b({error:`Unknown payment network name: ${u}. Known networks: ${Object.keys(nn).join(", ")}`}),process.exit(1));let d=Uo(u,i,jo);d||(b({error:`Missing ${ti(u)} and no default RPC URL for payment network ${u}`}),process.exit(1));let m=WA(e.networks.bridgeSource,e.networks.bridgeDestination,i),f=e.bridgePolicy;return{appServerUrl:e.services.authServerUrl,webappUrl:e.services.authWebappUrl,privyAppId:e.services.privyAppId,dataDir:r,keysDir:n,depositNetworks:c,gatewayServerUrl:e.services.cryptoGatewayUrl,passphrase:a(i.passphrase,"AMB_RIDE_PASSPHRASE"),payCurrency:e.networks.paymentCurrency,paymentNetwork:u,paymentRpcUrl:d,paymentChainId:l,paymentUsdcAddress:e.networks.paymentUsdcAddress,cliGatewayHost:e.services.memberGatewayUrls[e.services.defaultRegion],cliGatewayHosts:e.services.memberGatewayUrls,riderCliApp:{clientId:e.providers.tada.memberClientId,clientSecret:e.providers.tada.memberClientSecret},bridge:m.bridge,bridgeConfigError:m.error,bridgeMinUsdc:f.minimumUsdc,bridgeMaxFeeBufferPct:f.maxFeeBufferPct,bridgeBurnGraceBlocks:f.burnGraceBlocks,bridgeMintMaxAttempts:f.mintMaxAttempts,bridgeLeaseSec:f.leaseSeconds,bridgeLogChunkBlocks:f.logChunkBlocks}}function gd(e){return e.riderCliApp.clientId!==""&&e.riderCliApp.clientSecret!==""}function zn(){let e=De(),t=e.providers.tada.memberClientId,r=e.providers.tada.memberClientSecret,n=e.services.memberGatewayUrls[e.services.defaultRegion]??"";return t!==""&&r!==""&&n!==""}p();import YA from"better-sqlite3";import ni from"fs";import si from"path";p();import zt from"fs";import ri from"path";import JA from"better-sqlite3";var yd="tada-ride-agent.db",hd="ambient-ride.db",_d=["","-wal","-shm","-journal"];function KA(e){let t=zt.openSync(e,"r");try{zt.fsyncSync(t)}finally{zt.closeSync(t)}}function Xn(e){return _d.some(t=>zt.existsSync(ri.join(e,`${yd}${t}`)))}function Ed(e){if(!Xn(e))return!1;zt.mkdirSync(e,{recursive:!0,mode:448});for(let n of _d){let s=ri.join(e,`${yd}${n}`),i=ri.join(e,`${hd}${n}`);if(zt.existsSync(s)){if(zt.existsSync(i))throw new Error(`MIGRATION_CONFLICT: both database names exist (${n||"main"})`);zt.renameSync(s,i),KA(e)}}let t=ri.join(e,hd);if(!zt.existsSync(t))throw new Error("MIGRATION_INTERRUPTED: database sidecar exists without main database");let r=new JA(t,{readonly:!0,fileMustExist:!0});try{if(r.pragma("integrity_check",{simple:!0})!=="ok")throw new Error("MIGRATION_VALIDATION_FAILED: database integrity")}finally{r.close()}return!0}p();var Td=Ar().logLevel==="debug";function bd(){return Td}function Tt(e){Td&&process.stderr.write(e)}var ae;function O(e){let t=si.dirname(e),r=si.basename(t)==="state"?si.dirname(t):t;if(ni.existsSync(`${r}.amb-migration-quiesced`))throw new Error("MIGRATION_CONFLICT: runtime state is being migrated");ni.existsSync(e)||ni.mkdirSync(e,{recursive:!0});let n=si.join(e,"ambient-ride.db");if(!ni.existsSync(n)&&Xn(e))throw new Error("LEGACY_AMBIENT_DATABASE: run `amb install` before using the CLI");ae=new YA(n),ae.pragma("journal_mode = WAL"),ae.pragma("foreign_keys = ON"),ae.exec(`
19
33
  CREATE TABLE IF NOT EXISTS identity (
20
34
  id INTEGER PRIMARY KEY,
21
35
  privy_user_id TEXT NOT NULL UNIQUE,
@@ -78,6 +92,8 @@ ${Ln.randomUUID()}
78
92
 
79
93
  CREATE TABLE IF NOT EXISTS ride_requests (
80
94
  request_id TEXT PRIMARY KEY,
95
+ journey_id TEXT,
96
+ ride_id TEXT,
81
97
  wallet_address TEXT,
82
98
  member_id TEXT,
83
99
  region TEXT NOT NULL,
@@ -124,6 +140,36 @@ ${Ln.randomUUID()}
124
140
  last_active_at INTEGER NOT NULL
125
141
  );
126
142
 
143
+ CREATE TABLE IF NOT EXISTS telemetry_accounts (
144
+ account_id TEXT PRIMARY KEY,
145
+ installation_id TEXT NOT NULL,
146
+ auth_type TEXT NOT NULL CHECK(auth_type IN ('member', 'wallet')),
147
+ first_ride_created_at INTEGER,
148
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
149
+ );
150
+
151
+ CREATE TABLE IF NOT EXISTS telemetry_journeys (
152
+ journey_id TEXT PRIMARY KEY,
153
+ account_id TEXT NOT NULL,
154
+ payment_mode TEXT NOT NULL CHECK(payment_mode IN ('card', 'wallet_usdc')),
155
+ region TEXT NOT NULL CHECK(region IN ('SG', 'US')),
156
+ market_code TEXT,
157
+ status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open', 'closed')),
158
+ started_at INTEGER NOT NULL,
159
+ expires_at INTEGER NOT NULL,
160
+ closed_at INTEGER
161
+ );
162
+
163
+ CREATE TABLE IF NOT EXISTS telemetry_journey_links (
164
+ link_type TEXT NOT NULL CHECK(link_type IN ('search', 'request', 'ride')),
165
+ link_id TEXT NOT NULL,
166
+ journey_id TEXT NOT NULL,
167
+ backend_id TEXT,
168
+ created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
169
+ PRIMARY KEY (link_type, link_id),
170
+ FOREIGN KEY (journey_id) REFERENCES telemetry_journeys(journey_id) ON DELETE CASCADE
171
+ );
172
+
127
173
  CREATE TABLE IF NOT EXISTS places (
128
174
  id INTEGER PRIMARY KEY AUTOINCREMENT,
129
175
  wallet_address TEXT NOT NULL,
@@ -193,7 +239,7 @@ ${Ln.randomUUID()}
193
239
  expires_at INTEGER NOT NULL,
194
240
  created_at INTEGER NOT NULL
195
241
  );
196
- `),L.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='saved_places'").get()&&L.transaction(()=>{L.exec(`
242
+ `),ae.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='saved_places'").get()&&ae.transaction(()=>{ae.exec(`
197
243
  INSERT INTO places (
198
244
  id, wallet_address, label, name, formatted_address,
199
245
  latitude, longitude, google_place_id, city, region,
@@ -214,14 +260,14 @@ ${Ln.randomUUID()}
214
260
  END AS dedup_key
215
261
  FROM saved_places;
216
262
  DROP TABLE saved_places;
217
- `)})(),L.prepare("PRAGMA table_info(ride_events)").all().some(h=>h.name==="read")||L.exec("ALTER TABLE ride_events ADD COLUMN read INTEGER DEFAULT 0");let o=L.prepare("PRAGMA table_info(jwt_cache)").all();o.some(h=>h.name==="kind")||L.exec("ALTER TABLE jwt_cache ADD COLUMN kind TEXT NOT NULL DEFAULT 'siwe'"),o.some(h=>h.name==="refresh_token")||L.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_token TEXT"),o.some(h=>h.name==="refresh_expires_at")||L.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_expires_at INTEGER"),L.prepare("PRAGMA table_info(bridge_jobs)").all().some(h=>h.name==="relay_request_id")||L.exec("ALTER TABLE bridge_jobs ADD COLUMN relay_request_id TEXT"),L.prepare("PRAGMA table_info(wallets)").all().some(h=>h.name==="is_active")&&L.exec("ALTER TABLE wallets DROP COLUMN is_active"),L.prepare("PRAGMA table_info(phone_verifications)").all().some(h=>h.name==="wallet_address")||L.exec(`DROP TABLE phone_verifications;
263
+ `)})(),ae.prepare("PRAGMA table_info(ride_events)").all().some(T=>T.name==="read")||ae.exec("ALTER TABLE ride_events ADD COLUMN read INTEGER DEFAULT 0");let a=ae.prepare("PRAGMA table_info(jwt_cache)").all();a.some(T=>T.name==="kind")||ae.exec("ALTER TABLE jwt_cache ADD COLUMN kind TEXT NOT NULL DEFAULT 'siwe'"),a.some(T=>T.name==="refresh_token")||ae.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_token TEXT"),a.some(T=>T.name==="refresh_expires_at")||ae.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_expires_at INTEGER"),ae.prepare("PRAGMA table_info(bridge_jobs)").all().some(T=>T.name==="relay_request_id")||ae.exec("ALTER TABLE bridge_jobs ADD COLUMN relay_request_id TEXT"),ae.prepare("PRAGMA table_info(wallets)").all().some(T=>T.name==="is_active")&&ae.exec("ALTER TABLE wallets DROP COLUMN is_active"),ae.prepare("PRAGMA table_info(phone_verifications)").all().some(T=>T.name==="wallet_address")||ae.exec(`DROP TABLE phone_verifications;
218
264
  CREATE TABLE phone_verifications (
219
265
  wallet_address TEXT NOT NULL,
220
266
  phone TEXT NOT NULL,
221
267
  verified_at DATETIME DEFAULT CURRENT_TIMESTAMP,
222
268
  PRIMARY KEY (wallet_address, phone),
223
269
  FOREIGN KEY (wallet_address) REFERENCES wallets(wallet_address) ON DELETE CASCADE
224
- );`),L.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='active_listeners'").get()&&L.exec("DROP TABLE active_listeners");let m=L.prepare("PRAGMA table_info(tada_members)").all().find(h=>h.name==="phone");m&&m.notnull===1&&L.exec(`
270
+ );`),ae.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='active_listeners'").get()&&ae.exec("DROP TABLE active_listeners");let m=ae.prepare("PRAGMA table_info(tada_members)").all().find(T=>T.name==="phone");m&&m.notnull===1&&ae.exec(`
225
271
  CREATE TABLE tada_members__new (
226
272
  id TEXT PRIMARY KEY,
227
273
  phone TEXT,
@@ -233,9 +279,11 @@ ${Ln.randomUUID()}
233
279
  INSERT INTO tada_members__new SELECT id, phone, display_name, region, created_at, last_active_at FROM tada_members;
234
280
  DROP TABLE tada_members;
235
281
  ALTER TABLE tada_members__new RENAME TO tada_members;
236
- `);let p=L.prepare("PRAGMA table_info(ride_requests)").all();p.length>0&&!p.some(h=>h.name==="member_id")&&L.exec(`
282
+ `);let f=ae.prepare("PRAGMA table_info(ride_requests)").all();f.length>0&&!f.some(T=>T.name==="member_id")&&ae.exec(`
237
283
  CREATE TABLE ride_requests__new (
238
284
  request_id TEXT PRIMARY KEY,
285
+ journey_id TEXT,
286
+ ride_id TEXT,
239
287
  wallet_address TEXT,
240
288
  member_id TEXT,
241
289
  region TEXT NOT NULL,
@@ -263,87 +311,185 @@ ${Ln.randomUUID()}
263
311
  FROM ride_requests;
264
312
  DROP TABLE ride_requests;
265
313
  ALTER TABLE ride_requests__new RENAME TO ride_requests;
266
- `),L.exec(`
314
+ `);let g=ae.prepare("PRAGMA table_info(ride_requests)").all();g.some(T=>T.name==="journey_id")||ae.exec("ALTER TABLE ride_requests ADD COLUMN journey_id TEXT"),g.some(T=>T.name==="ride_id")||ae.exec("ALTER TABLE ride_requests ADD COLUMN ride_id TEXT"),ae.exec(`
267
315
  CREATE UNIQUE INDEX IF NOT EXISTS idx_places_dedup ON places(wallet_address, dedup_key);
268
316
  CREATE INDEX IF NOT EXISTS idx_places_wallet ON places(wallet_address);
269
317
  CREATE INDEX IF NOT EXISTS idx_places_label ON places(wallet_address, label);
270
318
  CREATE INDEX IF NOT EXISTS idx_places_hit ON places(wallet_address, hit_count DESC, last_used_at DESC);
271
319
  CREATE INDEX IF NOT EXISTS idx_bridge_jobs_wallet_status ON bridge_jobs (wallet_address, status);
272
- `);let f=Math.floor(Date.now()/1e3),_=L.prepare(`
320
+ CREATE INDEX IF NOT EXISTS idx_telemetry_links_journey ON telemetry_journey_links(journey_id);
321
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_telemetry_journey_singletons
322
+ ON telemetry_journey_links(journey_id, link_type)
323
+ WHERE link_type IN ('request', 'ride');
324
+ `);let _=Math.floor(Date.now()/1e3),E=ae.prepare(`
273
325
  DELETE FROM jwt_cache
274
326
  WHERE (kind != 'member' AND expires_at <= ?)
275
327
  OR (kind = 'member' AND refresh_expires_at IS NOT NULL AND refresh_expires_at <= ?)
276
- `).run(f,f);L.prepare("DELETE FROM search_cache WHERE expires_at <= ?").run(Date.now()),L.prepare("DELETE FROM payment_cache WHERE expires_at <= ?").run(Date.now()),oe(`[jwt-debug] INIT db=${n} now=${f} cleanup_removed_jwt=${_.changes} pid=${process.pid}
277
- `)}function T(){if(!L)throw new Error("DB not initialized. Call initDb() first.");return L}function mr(e){T().prepare(`
328
+ `).run(_,_);ae.prepare("DELETE FROM search_cache WHERE expires_at <= ?").run(Date.now()),ae.prepare("DELETE FROM payment_cache WHERE expires_at <= ?").run(Date.now()),Tt(`[jwt-debug] INIT db=${n} now=${_} cleanup_removed_jwt=${E.changes} pid=${process.pid}
329
+ `)}function S(){if(!ae)throw new Error("DB not initialized. Call initDb() first.");return ae}p();function ii(e){S().prepare(`
278
330
  INSERT OR REPLACE INTO wallets (wallet_address, wallet_type, label)
279
331
  VALUES (?, 'privy', ?)
280
- `).run(e.wallet_address,e.label??null),T().prepare(`
332
+ `).run(e.wallet_address,e.label??null),S().prepare(`
281
333
  INSERT OR REPLACE INTO privy_wallet_meta (wallet_address, wallet_id, quorum_id, k_i_pub, k_i_key_path)
282
334
  VALUES (?, ?, ?, ?, ?)
283
- `).run(e.wallet_address,e.wallet_id,e.quorum_id,e.k_i_pub,e.k_i_key_path)}function qi(e){T().prepare(`
335
+ `).run(e.wallet_address,e.wallet_id,e.quorum_id,e.k_i_pub,e.k_i_key_path)}function vd(e){S().prepare(`
284
336
  INSERT OR REPLACE INTO wallets (wallet_address, wallet_type, label)
285
337
  VALUES (?, 'external', ?)
286
- `).run(e.wallet_address,e.label??null)}function gr(){return T().prepare("SELECT * FROM wallets ORDER BY created_at ASC").all()}function fr(){return T().prepare("SELECT * FROM wallets WHERE last_valid = 1").all()}function ye(e){return T().prepare("SELECT * FROM wallets WHERE wallet_address = ?").get(e)}function ae(e){return T().prepare("SELECT * FROM privy_wallet_meta WHERE wallet_address = ?").get(e)}function Ae(e,t){T().prepare(`
338
+ `).run(e.wallet_address,e.label??null)}function ai(){return S().prepare("SELECT * FROM wallets ORDER BY created_at ASC").all()}function oi(){return S().prepare("SELECT * FROM wallets WHERE last_valid = 1").all()}function jt(e){return S().prepare("SELECT * FROM wallets WHERE wallet_address = ?").get(e)}function bt(e){return S().prepare("SELECT * FROM privy_wallet_meta WHERE wallet_address = ?").get(e)}function Xt(e,t){S().prepare(`
287
339
  UPDATE wallets SET last_valid = 0, invalid_reason = ?, last_validity_check_at = CURRENT_TIMESTAMP
288
340
  WHERE wallet_address = ?
289
- `).run(t,e)}function _r(e){T().prepare(`
341
+ `).run(t,e)}function ci(e){S().prepare(`
290
342
  UPDATE wallets SET last_valid = 1, invalid_reason = NULL, last_validity_check_at = CURRENT_TIMESTAMP
291
343
  WHERE wallet_address = ?
292
- `).run(e)}function yr(){return T().prepare("SELECT * FROM pending_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function ji(e){T().prepare(`
344
+ `).run(e)}p();var xd;function le(e){xd=e.replace(/\/$/,"")}async function Pt(e,t,r,n,s){let i={"Content-Type":"application/json","x-auth-client-id":"TadaRideAiAgent"};n&&(i.Authorization=`Bearer ${n}`);let a=await fetch(`${xd}${t}`,{method:e,headers:i,body:r!==void 0?JSON.stringify(r):void 0,...s?{signal:s}:{}});if(!a.ok){let o=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status} ${a.statusText} on ${e} ${t}: ${o}`)}return a.json()}function Rd(e){return Pt("POST","/quorum-wallet/session",{kIPub:e})}async function li(e){let t=await Pt("GET",`/quorum-wallet/session/${e}`);return{...t,status:String(t.status).toUpperCase()}}function ui(e){return Pt("POST","/quorum-wallet/validate",e)}function Ad(e,t){return Pt("POST","/quorum-wallet/cosign",e,void 0,t)}function wd(e){return Pt("POST","/quorum-wallet/sendtx",e)}function Sd(e){return Pt("POST","/quorum-wallet/sendcalls",e)}function Id(e,t){return Pt("POST","/auth/siwe/nonce",e,void 0,t)}function Pd(e,t){return Pt("POST","/auth/siwe/token",e,void 0,t)}function Dd(e,t){return Pt("POST","/auth/siwe/users",e,void 0,t)}function Od(e){return Pt("GET",`/quorum-wallet/transaction/${e}`)}function Cd(e,t){return Pt("GET",`/auth/siwe/users/${e}`,void 0,void 0,t)}p();import Dt from"fs";import Zn from"path";p();import di from"path";import zA from"fs";import XA from"better-sqlite3";function tt(e,t){return di.join(e,di.basename(t))}function pi(e){return di.basename(e)}var QA=[{table:"privy_wallet_meta",id:"wallet_address"},{table:"pending_sessions",id:"session_token"}];function Nd(e){if(!zA.existsSync(e))return{normalized:0};let t=null;try{return t=new XA(e),t.transaction(()=>{let n=new Map,s=0;for(let i of QA){if(!t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(i.table))continue;let o=t.prepare(`SELECT ${i.id} AS id, k_i_key_path FROM ${i.table}`).all(),c=t.prepare(`UPDATE ${i.table} SET k_i_key_path = ? WHERE ${i.id} = ?`);for(let u of o){let l=u.k_i_key_path.replace(/\\/g,"/"),d=di.posix.basename(l);if(!d||d==="."||d==="..")throw new Error(`INVALID_KEY_PATH: ${i.table}.${i.id}=${u.id}`);let m=n.get(d);if(m!==void 0&&m!==l)throw new Error(`KEY_PATH_COLLISION: ${d}`);n.set(d,l),u.k_i_key_path!==d&&(c.run(d,u.id),s++)}}return{normalized:s}})()}finally{t?.close()}}p();function Qn(e,t,r){return`${e}?handle=${t}&pub=${encodeURIComponent(r)}`}p();import Qt from"crypto";var Ld=Buffer.from("RAGK"),kd=1,mi=4,Md=1,fi=32,gi=12,Bo=16,ZA=mi+Md+fi+gi+Bo,ew=16384,tw=8,rw=1,nw=32;function Ud(){let{publicKey:e,privateKey:t}=Qt.generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}}function Fd(e){return Qt.createPublicKey(e).export({type:"spki",format:"der"}).toString("base64")}function hi(e){let t=Qt.createPrivateKey(e);return Qt.createPublicKey(t).export({type:"spki",format:"der"}).toString("base64")}function jd(e,t){return Qt.scryptSync(e,t,nw,{N:ew,r:tw,p:rw})}function qd(e,t){let r=Qt.randomBytes(fi),n=Qt.randomBytes(gi),s=jd(t,r),i=Qt.createCipheriv("aes-256-gcm",s,n),a=Buffer.concat([i.update(e),i.final()]),o=i.getAuthTag();return Buffer.concat([Ld,Buffer.from([kd]),r,n,o,a])}function qt(e,t){if(e.length<ZA)throw new Error("Invalid encrypted data: too short");if(!e.subarray(0,mi).equals(Ld))throw new Error("Invalid encrypted data: bad magic");let n=e[mi];if(n!==kd)throw new Error(`Unsupported encrypted data version: ${n}`);let s=mi+Md,i=e.subarray(s,s+fi);s+=fi;let a=e.subarray(s,s+gi);s+=gi;let o=e.subarray(s,s+Bo);s+=Bo;let c=e.subarray(s),u=jd(t,i),l=Qt.createDecipheriv("aes-256-gcm",u,a);return l.setAuthTag(o),Buffer.concat([l.update(c),l.final()])}function gt(e){e.fill(0)}p();function yi(){return S().prepare("SELECT * FROM pending_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function Bd(e){S().prepare(`
293
345
  INSERT INTO pending_sessions (session_token, k_i_pub, k_i_key_path)
294
346
  VALUES (@session_token, @k_i_pub, @k_i_key_path)
295
- `).run(e)}function We(e){T().prepare("DELETE FROM pending_sessions WHERE session_token = ?").run(e)}function Gi(e,t){T().prepare("INSERT OR REPLACE INTO member_login_sessions (session_token, expires_at, created_at) VALUES (?, ?, ?)").run(e,t,Math.floor(Date.now()/1e3))}function Wi(){return T().prepare("SELECT * FROM member_login_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function hr(e){T().prepare("DELETE FROM member_login_sessions WHERE session_token = ?").run(e)}function Vi(){T().prepare("DELETE FROM member_login_sessions").run()}function Ji(e,t,r,n="siwe"){T().prepare(`
347
+ `).run(e)}function Sr(e){S().prepare("DELETE FROM pending_sessions WHERE session_token = ?").run(e)}async function Vd(e,t,r=!1){let n=r?[]:oi();if(n.length>0){let m=[],f=[];for(let g of n){let _=bt(g.wallet_address);if(!_){f.push(g.wallet_address);continue}try{let E=tt(e.keysDir,_.k_i_key_path);if(!Dt.existsSync(E)){f.push(g.wallet_address);continue}let T=Dt.readFileSync(E),x=qt(T,t),R=x.toString("utf8"),I=hi(R);if(gt(x),I!==_.k_i_pub){f.push(g.wallet_address);continue}m.push({wallet_address:g.wallet_address,wallet_id:_.wallet_id})}catch{f.push(g.wallet_address)}}if(m.length>0){if(f.length>0)for(let g of f)Xt(g,"Local validation failed");return{status:"ready",wallets:m}}for(let g of f)Xt(g,"Local validation failed")}let s=yi();if(s){try{let m=await li(s.session_token);if(m.status==="PENDING")return{status:"auth_pending",auth_url:Qn(e.webappUrl,s.session_token,s.k_i_pub),next_action:"AFTER_USER_COMPLETES_AUTH_CALL_wallet_check_auth"};if(m.status==="DONE"){let{quorumId:f,walletId:g,walletAddress:_}=m,E=e.keysDir,T=tt(E,s.k_i_key_path),x=Zn.join(E,`${_}_private.enc`);return Dt.renameSync(T,x),Dt.rmSync(Zn.join(E,`${s.session_token}_public.pem`),{force:!0}),ii({wallet_address:_,wallet_id:g,quorum_id:f,k_i_pub:s.k_i_pub,k_i_key_path:pi(x)}),ci(_),Sr(s.session_token),{status:"ready",wallets:[{wallet_address:_,wallet_id:g}]}}}catch{}Dt.rmSync(tt(e.keysDir,s.k_i_key_path),{force:!0}),Dt.rmSync(Zn.join(e.keysDir,`${s.session_token}_public.pem`),{force:!0}),Sr(s.session_token)}let{publicKeyPem:i,privateKeyPem:a}=Ud(),o=Fd(i),{sessionToken:c}=await Rd(o),u=Qn(e.webappUrl,c,o),l=Zn.join(e.keysDir,`${c}_private.enc`),d=Zn.join(e.keysDir,`${c}_public.pem`);try{Dt.mkdirSync(e.keysDir,{recursive:!0,mode:448});let m=Buffer.from(a,"utf8"),f=qd(m,t);gt(m),Dt.writeFileSync(l,f,{mode:384}),Dt.writeFileSync(d,i,{mode:420}),Bd({session_token:c,k_i_pub:o,k_i_key_path:l})}catch(m){throw Dt.rmSync(l,{force:!0}),Dt.rmSync(d,{force:!0}),m}return{status:"auth_required",auth_url:u,next_action:"SHOW_AUTH_URL_TO_USER_THEN_IMMEDIATELY_CALL_wallet_check_auth_WITHOUT_WAITING_FOR_USER_CONFIRMATION"}}p();import Gd from"fs";import Hd from"path";var sw=1e3;async function Vo(e,t={}){let r=yi();if(!r)return{status:"no_pending"};let{session_token:n,k_i_pub:s,k_i_key_path:i}=r,a=Qn(e.webappUrl,n,s),o=Date.now()+(t.waitMs??0),c;for(;c=await li(n),c.status==="PENDING";){if(Date.now()>=o)return{status:"pending",auth_url:a};await new Promise(E=>setTimeout(E,sw))}if(c.status!=="DONE")return Sr(n),{status:"failed",reason:c.status==="FAILED"?c.reason:`Unexpected session status: ${c.status}`};let{quorumId:u,walletId:l,walletAddress:d}=c,m=e.keysDir,f=tt(m,i),g=Hd.join(m,`${d}_private.enc`),_=Hd.join(m,`${n}_public.pem`);try{Gd.renameSync(f,g)}catch(E){throw Sr(n),new Error(`Failed to rename key file: ${E}`)}return Gd.rmSync(_,{force:!0}),ii({wallet_address:d,wallet_id:l,quorum_id:u,k_i_pub:s,k_i_key_path:pi(g)}),ci(d),Sr(n),{status:"ready",wallet_address:d}}p();p();function $d(e,t,r,n="siwe"){S().prepare(`
296
348
  INSERT OR REPLACE INTO jwt_cache (cache_key, token, expires_at, kind, refresh_token, refresh_expires_at)
297
349
  VALUES (?, ?, ?, ?, NULL, NULL)
298
- `).run(e,t,r,n)}function Ki(e,t,r,n,s){T().prepare(`
350
+ `).run(e,t,r,n)}function Wd(e,t,r,n,s){S().prepare(`
299
351
  INSERT OR REPLACE INTO jwt_cache (cache_key, token, expires_at, kind, refresh_token, refresh_expires_at)
300
352
  VALUES (?, ?, ?, 'member', ?, ?)
301
- `).run(e,t,r,n,s)}function P(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return T().prepare(`
353
+ `).run(e,t,r,n,s)}function ie(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return S().prepare(`
302
354
  SELECT token FROM jwt_cache WHERE cache_key = ? AND kind = ? AND expires_at > ?
303
- `).get(e,t,r)?.token??null}function wr(e){let t=Math.floor(Date.now()/1e3);return T().prepare(`
355
+ `).get(e,t,r)?.token??null}function _i(e){let t=Math.floor(Date.now()/1e3);return S().prepare(`
304
356
  SELECT refresh_token, refresh_expires_at
305
357
  FROM jwt_cache
306
358
  WHERE cache_key = ? AND kind = 'member'
307
359
  AND refresh_token IS NOT NULL
308
360
  AND (refresh_expires_at IS NULL OR refresh_expires_at > ?)
309
- `).get(e,t)??null}function Yi(e,t,r=18e4){let n=Date.now()+r;T().prepare(`
310
- INSERT OR REPLACE INTO search_cache (check_sum, raw, expires_at)
311
- VALUES (?, ?, ?)
312
- `).run(e,t,n)}function Xi(e){let t=Date.now();return T().prepare(`
313
- SELECT raw FROM search_cache WHERE check_sum = ? AND expires_at > ?
314
- `).get(e,t)?.raw??null}function zi(e,t,r=6e5){let n=Date.now()+r;T().prepare(`
315
- INSERT OR REPLACE INTO payment_cache (request_id, data, expires_at)
316
- VALUES (?, ?, ?)
317
- `).run(e,JSON.stringify(t),n)}function Qi(e){let t=Date.now(),r=T().prepare(`
318
- SELECT data FROM payment_cache WHERE request_id = ? AND expires_at > ?
319
- `).get(e,t);return r?JSON.parse(r.data):null}function Er(e){T().prepare(`
361
+ `).get(e,t)??null}function Jd(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return S().prepare(`
362
+ SELECT token, expires_at FROM jwt_cache WHERE cache_key = ? AND kind = ? AND expires_at > ?
363
+ `).get(e,t,r)??null}function J(e){jt(e)||(b({error:"WALLET_NOT_FOUND",message:`Wallet ${e} is not registered.`,action:"Run `amb wallet-setup --no-wait` first to create the built-in wallet."}),process.exit(1))}function he(e){let t=ie(e),r=Math.floor(Date.now()/1e3);Tt(`[jwt-debug] GET cache_key=${e} now=${r} found=${!!t} pid=${process.pid}
364
+ `),t||(b({error:"JWT_NOT_FOUND",message:`No valid JWT for wallet ${e}.`,action:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1))}p();import{createPublicClient as ww,http as Sw,formatUnits as Wo,parseAbi as Iw}from"viem";import{baseSepolia as Xd,base as Pw,mainnet as Dw,sepolia as Ow}from"viem/chains";p();function Kd(e){let t=new Map,r=(i,a,o)=>{let c=t.get(i);if(c)return c;let u={network:i,chainId:a,rpcUrl:o,tokens:[{kind:"native"}]};return t.set(i,u),u},n=(i,a)=>{i.tokens.some(c=>c.kind==="erc20"&&c.address.toLowerCase()===a.toLowerCase())||i.tokens.push({kind:"erc20",symbol:"USDC",decimals:6,address:a})};n(r(e.paymentNetwork,e.paymentChainId,e.paymentRpcUrl),e.paymentUsdcAddress);let s=e.bridge?.source;s&&n(r(s.name,s.chainId,s.rpcUrl),s.usdcAddress);for(let i of e.depositNetworks)r(i.name,i.chainId,i.rpcUrl).tokens.push({kind:"mvl",deposit:i});return[...t.values()]}p();import{createPublicClient as ow,http as cw,parseAbi as lw}from"viem";import{baseSepolia as uw,base as dw,mainnet as pw,sepolia as mw}from"viem/chains";p();import{parseAbi as iw}from"viem";var sn=iw(["function mvlReserve() view returns (uint256)","function supportedTokens() view returns (address[])","function isAllowedToken(address token) view returns (bool)","function maxDeposit(address token) view returns (uint256)","function tokenDeposits(address agent, address token) view returns (uint256)","function maxPriceAge() view returns (uint256)","function isQuoteNonceUsed(address agent, uint256 nonce) view returns (bool)","function isDepositNonceUsed(address agent, uint256 nonce) view returns (bool)","function DOMAIN_SEPARATOR() view returns (bytes32)","function depositMVL(address agent, uint256 amount)","function withdraw()"]);p();import{parseAbi as aw}from"viem";var an=aw(["function deposits(address agent) view returns (uint256)","function isAgentActive(address agent) view returns (bool)","function nextWithdrawAt(address agent) view returns (uint256)","function minRequiredBalance() view returns (uint256)","function withdrawCooldown() view returns (uint256)","function router() view returns (address)","function mvlToken() view returns (address)","function treasury() view returns (uint256)"]);var fw={84532:uw,8453:dw,1:pw,11155111:mw},_j=lw(["function allowance(address owner, address spender) view returns (uint256)"]);function gw(e){let t=fw[e];if(!t)throw new Error(`Unsupported chainId: ${e}`);return t}function Ir(e){return ow({chain:gw(e.chainId),transport:cw(e.rpcUrl)})}async function Ei(e,t){return await Ir(e).readContract({address:e.agentDepositLedger,abi:an,functionName:"deposits",args:[t]})}async function Ti(e,t){return await Ir(e).readContract({address:e.agentDepositLedger,abi:an,functionName:"isAgentActive",args:[t]})}async function Go(e){return(await Ir(e).readContract({address:e.depositContract,abi:sn,functionName:"supportedTokens"})).filter(r=>!/^0x0{40}$/i.test(r))}async function bi(e,t){return await Ir(e).readContract({address:e.agentDepositLedger,abi:an,functionName:"nextWithdrawAt",args:[t]})}async function es(e){return await Ir(e).readContract({address:e.agentDepositLedger,abi:an,functionName:"minRequiredBalance"})}async function Pr(e){return await Ir(e).readContract({address:e.agentDepositLedger,abi:an,functionName:"mvlToken"})}async function Yd(e){return await Ir(e).readContract({address:e.depositContract,abi:sn,functionName:"mvlReserve"})}p();import{createPublicClient as hw,http as yw,parseAbi as _w}from"viem";import{baseSepolia as Ew,base as Tw,mainnet as bw,sepolia as vw}from"viem/chains";var xw={84532:Ew,8453:Tw,1:bw,11155111:vw},Ho=_w(["function symbol() view returns (string)","function name() view returns (string)","function decimals() view returns (uint8)"]),Rw={BASE_SEPOLIA:{"0x036cbd53842c5426634e7929541ec2318f3dcf7e":{symbol:"USDC",name:"USDC",decimals:6}},BASE:{"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":{symbol:"USDC",name:"USD Coin",decimals:6}},ETHEREUM_SEPOLIA:{"0x3cf4ccf7ec4bb094d1504d1315057a46005d5065":{symbol:"MVL",name:"Mass Vehicle Ledger Token",decimals:18}},ETHEREUM:{"0xa849eaae994fb86afa73382e9bd88c2b6b18dc71":{symbol:"MVL",name:"Mass Vehicle Ledger Token",decimals:18}}},$o=new Map;function Aw(e,t){return`${e}:${t.toLowerCase()}`}async function Dr(e,t){let r=Aw(e.name,t),n=$o.get(r);if(n)return n;let s=Rw[e.name]?.[t.toLowerCase()];if(s)return $o.set(r,s),s;let i=xw[e.chainId],a=hw({chain:i,transport:yw(e.rpcUrl)}),o=t,[c,u,l]=await Promise.all([a.readContract({address:o,abi:Ho,functionName:"symbol"}),a.readContract({address:o,abi:Ho,functionName:"name"}),a.readContract({address:o,abi:Ho,functionName:"decimals"})]),d={symbol:c,name:u,decimals:l};return $o.set(r,d),d}var Qd={84532:Xd,8453:Pw,1:Dw,11155111:Ow},Cw=Iw(["function balanceOf(address account) view returns (uint256)"]),Nw=(e,t)=>ww({chain:Qd[e]??Xd,transport:Sw(t)});function zd(e,t,r){return e.readContract({address:t,abi:Cw,functionName:"balanceOf",args:[r]})}async function Zd(e,t,r={}){let n=r.makeClient??Nw,s=r.mvlTokenReader??Pr,i=r.tokenMetadata??Dr,a=Kd(t),o=await Promise.all(a.map(async m=>{let f;try{f=n(m.chainId,m.rpcUrl)}catch(g){return m.tokens.map(_=>({status:"rejected",network:m.network,symbol:l(_),error:g.message}))}return await Promise.all(m.tokens.map(async g=>{try{return{status:"fulfilled",row:await d(g,m,f)}}catch(_){return{status:"rejected",network:m.network,symbol:l(g),error:_.message}}}))})),c=[],u=[];for(let m of o.flat())m.status==="fulfilled"?c.push(m.row):u.push({network:m.network,symbol:m.symbol,error:m.error});return{balances:c,errors:u};function l(m){return m.kind==="erc20"?m.symbol:m.kind==="mvl"?"MVL":"native"}async function d(m,f,g){let _=f.network;if(m.kind==="native"){let R=await g.getBalance({address:e}),I=Qd[f.chainId]?.nativeCurrency.symbol??"ETH";return{network:_,symbol:I,amount:Wo(R,18)}}if(m.kind==="erc20"){let R=await zd(g,m.address,e);return{network:_,symbol:m.symbol,amount:Wo(R,m.decimals),address:m.address}}let E=await s(m.deposit),T=await i(m.deposit,E),x=await zd(g,E,e);return{network:_,symbol:T.symbol,amount:Wo(x,T.decimals),address:E}}}p();import tp from"fs";p();import{p256 as Lw}from"@noble/curves/p256";import{sha256 as kw}from"@noble/hashes/sha2";import{formatRequestForAuthorizationSignature as Mw}from"@privy-io/node";import Uw from"crypto";function ep(e,t){let n=Uw.createPrivateKey(t).export({format:"jwk"}),s=Buffer.from(n.d,"base64url"),i=Lw.sign(kw(typeof e=="string"?Buffer.from(e):e),s);return Buffer.from(i.toDERRawBytes()).toString("base64")}function on(e,t,r,n,s){let i={version:1,method:"POST",url:`https://api.privy.io/v1/wallets/${e}/rpc`,body:t,headers:{"privy-app-id":n,...s}},a=Mw(i);return ep(a,r)}function vi(e,t){return ep(`${e}`,t)}async function cr(e,t,r,n){let{wallet_address:s,sign_method:i,message:a}=e;if(!jt(s))throw new Error(`Wallet not found: ${s}`);let c=bt(s);if(!c)throw new Error("External wallet: signing must be done externally");let u=tt(t.keysDir,c.k_i_key_path);if(!tp.existsSync(u))throw new Error(`Key file not found: ${u}`);let l=tp.readFileSync(u),d=qt(l,r),m=d.toString("utf8");if(i==="personal_sign"&&typeof a!="string")throw gt(d),new Error("personal_sign requires a string message");if(i==="eth_signTypedData_v4"&&typeof a=="string")throw gt(d),new Error("eth_signTypedData_v4 requires a typed data object");let f=i==="personal_sign"?{method:"personal_sign",params:{encoding:"utf-8",message:a}}:{method:"eth_signTypedData_v4",params:{typed_data:{domain:a.domain,message:a.message,primary_type:a.primaryType,types:a.types}}},g=on(c.wallet_id,f,m,t.privyAppId),{walletSignature:_}=await Ad({signMethod:i,message:a,walletId:c.wallet_id,kISig:g},n);return gt(d),{wallet_signature:_}}p();import rp from"fs";var Fw={1:"https://etherscan.io/tx",11155111:"https://sepolia.etherscan.io/tx",8453:"https://basescan.org/tx",84532:"https://sepolia.basescan.org/tx"};function jw(e){let[t,r=""]=e.split("."),n=r.padEnd(18,"0").slice(0,18);return"0x"+(BigInt(t)*BigInt("1000000000000000000")+BigInt(n)).toString(16)}async function lr(e,t,r){let{wallet_address:n,to:s,value_eth:i,chain_id:a,data:o,sponsor:c}=e,u=jw(i),l=jt(n);if(!l)throw new Error(`Wallet not found: ${n}`);let d=bt(n);if(!d)throw new Error("External wallet: signing must be done externally");let m=tt(t.keysDir,d.k_i_key_path);if(!rp.existsSync(m))throw new Error(`Key file not found: ${m}`);let f=rp.readFileSync(m),g=qt(f,r),_=g.toString("utf8");try{let E=Date.now(),T=vi(E,_),x;try{x=await ui({walletId:d.wallet_id,quorumId:d.quorum_id,kIPub:d.k_i_pub,timestamp:E,kISig:T})}catch(q){throw(q instanceof Error?q.message:String(q)).includes("HTTP 401")&&Xt(l.wallet_address,"Unauthorized (401)"),q}if(!x.valid)throw Xt(l.wallet_address,x.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${x.reason??"unknown reason"}`);let R={method:"eth_sendTransaction",caip2:`eip155:${a}`,params:{transaction:{to:s,value:u,...o?{data:o}:{}}},...c?{sponsor:!0}:{}},I=`${Date.now()}:${crypto.randomUUID()}`,N=on(d.wallet_id,R,_,t.privyAppId,{"privy-idempotency-key":I}),k=await wd({walletId:d.wallet_id,caip2:`eip155:${a}`,transaction:{to:s,value:u,...o?{data:o}:{}},idempotencyKey:I,kISig:N,...c?{sponsor:!0}:{}}),B=k.transactionId?{transactionId:k.transactionId}:{};if(k.kind==="user_operation_hash")return{kind:"user_operation_hash",user_operation_hash:k.userOperationHash,...B};let Y=k.txHash,re=Fw[a];return{kind:"tx_hash",tx_hash:Y,...re?{explorer_url:`${re}/${Y}`}:{},...B}}finally{gt(g)}}p();import{createHash as qw}from"crypto";var Bw=/^member:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Vw=/^wallet:[0-9a-f]{24}$/;function ur(e){return`member:${e}`}function vt(e){return`wallet:${qw("sha256").update(e.toLowerCase()).digest("hex").slice(0,24)}`}function np(e){return typeof e=="string"&&(Bw.test(e)||Vw.test(e))}function sp(e,t,r){try{let n=S(),s=e.startsWith("member:")?"member":"wallet";n.prepare(`
365
+ INSERT OR IGNORE INTO telemetry_accounts (account_id, installation_id, auth_type)
366
+ VALUES (?, ?, ?)
367
+ `).run(e,t,s);let i=n.prepare(`
368
+ SELECT a.first_ride_created_at, j.started_at AS journey_started_at
369
+ FROM telemetry_accounts a
370
+ LEFT JOIN telemetry_journeys j ON j.journey_id = ?
371
+ WHERE a.account_id = ?
372
+ `).get(r??null,e);return i?.first_ride_created_at==null||i.journey_started_at!=null&&i.first_ride_created_at>=i.journey_started_at?"new":"existing"}catch{return}}function Jo(e,t=Date.now()){try{S().prepare(`
373
+ UPDATE telemetry_accounts
374
+ SET first_ride_created_at = COALESCE(first_ride_created_at, ?)
375
+ WHERE account_id = ?
376
+ `).run(t,e)}catch{}}p();import{createHash as jN,randomUUID as qN}from"crypto";p();var xi=class{constructor(t,r){this.transport=t;this.context=r}transport;context;capture(t){let r,n;"error_code"in t&&(r=t.error_code,n=t.failure_reason);let s={...this.context,event_id:t.event_id,search_id:t.search_id??this.context.search_id,request_id:t.request_id??this.context.request_id,ride_id:t.ride_id??this.context.ride_id,stage:t.stage,outcome:t.outcome,duration_ms:t.duration_ms,error_code:r,failure_reason:n};if(s.command!=="activation"&&(!s.region||!s.payment_mode)||s.account_id!==void 0&&!np(s.account_id))return!1;try{return this.transport.capture({event:t.event,properties:s},t.occurredAt),!0}catch{return!1}}async shutdown(){try{return await this.transport.shutdown(),!0}catch{return!1}}};p();var rr=AA(gT(),1);var xN=2e3,RN=typeof rr.default=="function"?rr.default:rr.default.default;function AN(){let e=De(),t=e.services.ambTelemetryServiceUrl.replace(/\/+$/,""),r=process.env.AMB_TELEMETRY_SERVICE_URL?.trim().replace(/\/+$/,"");if(r&&r!==t){if(e.install.repoBranch==="main")throw new Error("Production Ambient Hailing telemetry endpoint cannot be overridden");if(e.install.repoBranch!=="dev")throw new Error("Only development Ambient Hailing telemetry endpoints can be overridden")}let n=r||t,s=new URL(n),i=e.install.repoBranch==="dev"&&s.protocol==="http:";if(s.protocol!=="https:"&&!i)throw new Error("Ambient Hailing telemetry requires HTTPS outside development builds");return n}function wN(){let t={ambTelemetryService:AN()};return new RN({securityType:rr.SecurityType.PUBLIC,baseUrls:t,clientId:"RideAgentSkill",clientVersion:De().artifact.cliVersion}).ambTelemetry}function SN(e,t){let r=e.properties,n={eventId:r.event_id,eventName:e.event,installationId:r.installation_id,command:r.command,stage:r.stage,outcome:r.outcome,durationMs:r.duration_ms,cliVersion:r.cli_version,buildEnv:r.build_env,occurredAt:t};return r.account_id&&(n.accountId=r.account_id),r.journey_id&&(n.journeyId=r.journey_id),r.search_id&&(n.searchId=r.search_id),r.request_id&&(n.requestId=r.request_id),r.ride_id&&(n.rideId=r.ride_id),r.market_code&&(n.marketCode=r.market_code),r.sub_market&&(n.subMarket=r.sub_market),r.ah_user_type&&(n.ahUserType=r.ah_user_type),r.lifecycle_status&&(n.lifecycleStatus=r.lifecycle_status),r.journey_outcome&&(n.journeyOutcome=r.journey_outcome),r.cancellation_actor&&(n.cancellationActor=r.cancellation_actor),r.cancellation_stage&&(n.cancellationStage=r.cancellation_stage),r.dispatch_outcome&&(n.dispatchOutcome=r.dispatch_outcome),r.region&&(n.region=r.region),r.payment_mode&&(n.paymentMode=r.payment_mode),r.error_code&&(n.errorCode=r.error_code),r.failure_reason&&(n.failureReason=r.failure_reason),n}var _a=class{constructor(t=wN()){this.api=t}api;pending=[];capture(t,r=new Date().toISOString()){this.pending.push({event:t,occurredAt:r})}async shutdown(){let t=this.pending.splice(0,this.pending.length);if(t.length===0)return 0;let r=await this.api.postV1Events({schemaVersion:rr.AmbTelemetryService.AmbientHailingTelemetryBatchDtoSchemaVersionEnum.Value1,source:rr.AmbTelemetryService.AmbientHailingTelemetryBatchDtoSourceEnum.AmbientHailing,events:t.map(({event:n,occurredAt:s})=>SN(n,s))},{timeout:xN});if(r.accepted!==t.length)throw new Error(`Ambient Hailing telemetry accepted ${r.accepted} of ${t.length} events`);return r.accepted}};p();var IN={401:"unauthorized",404:"agent_session_not_found",409:"agent_session_already_decided",410:"agent_session_expired"},Be=class extends Error{constructor(r,n,s){super(`gateway ${r} ${n}`);this.status=r;this.code=n;this.detail=s;this.name="GatewayError"}status;code;detail},mr=class extends Error{code="coupon_not_applicable";constructor(){super("The coupon is not applicable to the latest quote."),this.name="CouponQuoteError"}},Ea=class extends Error{code="coupon_price_changed";constructor(){super("The coupon total changed after confirmation. Re-quote before booking."),this.name="CouponPriceChangedError"}},hT={coupon_not_found:"Coupon not found.",coupon_cannot_apply:"The coupon cannot be applied to this ride. Re-run the quote.",coupon_not_usable:"This coupon is not usable.",coupon_issue_not_allowed:"This promotion code cannot issue a coupon for this member.",coupon_api_error:"Coupon service is temporarily unavailable. Please try again."};function Ta(e){if(!(typeof e!="string"||!Object.hasOwn(hT,e)))return hT[e]}function dt(e,t){let r=IN[e]??"unknown",n;try{let s=JSON.parse(t);if(s&&typeof s.code=="string"&&(r=s.code),s&&typeof s.message=="string"){let i=s.message.replace(/[\u0000-\u001f\u007f]/g," ").trim();i&&(n=i.slice(0,500))}}catch{}return new Be(e,r,n)}p();import{randomUUID as PN}from"crypto";import Rs from"fs";import DN from"path";var ON=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ba=new Map;function yT(e){try{let t=Rs.readFileSync(e,"utf8").trim();return ON.test(t)?t:void 0}catch{return}}function _T(e){let t=DN.join(e,"telemetry-installation-id"),r=yT(t);if(r)return r;let n=ba.get(t)??PN();ba.set(t,n);let s=`${t}.${n}.tmp`;try{return Rs.mkdirSync(e,{recursive:!0,mode:448}),Rs.writeFileSync(s,`${n}
377
+ `,{mode:384,flag:"wx"}),Rs.linkSync(s,t),ba.delete(t),n}catch(i){if(i.code==="EEXIST"){let a=yT(t);if(a)return ba.delete(t),a}return n}finally{try{Rs.unlinkSync(s)}catch{}}}p();import{randomBytes as CN}from"crypto";var pt=class{constructor(t=Date.now){this.now=t}now;create(t){let r=this.now(),n={journey_id:NN(r),account_id:t.account_id,payment_mode:t.payment_mode,region:t.region,market_code:t.market_code??null,status:"open",started_at:r,expires_at:r+(t.ttl_ms??10*6e4),closed_at:null};return S().prepare(`
378
+ INSERT INTO telemetry_journeys (
379
+ journey_id, account_id, payment_mode, region, market_code,
380
+ status, started_at, expires_at, closed_at
381
+ ) VALUES (
382
+ @journey_id, @account_id, @payment_mode, @region, @market_code,
383
+ @status, @started_at, @expires_at, @closed_at
384
+ )
385
+ `).run(n),n}findOrCreate(t){let r=S();return r.transaction(()=>r.prepare(`
386
+ SELECT j.* FROM telemetry_journeys j
387
+ WHERE j.account_id = ? AND j.payment_mode = ? AND j.region = ?
388
+ AND (j.market_code = ? OR (j.market_code IS NULL AND ? IS NULL))
389
+ AND j.status = 'open' AND j.expires_at > ?
390
+ AND NOT EXISTS (
391
+ SELECT 1 FROM telemetry_journey_links l
392
+ WHERE l.journey_id = j.journey_id AND l.link_type = 'request'
393
+ )
394
+ ORDER BY j.started_at DESC LIMIT 1
395
+ `).get(t.account_id,t.payment_mode,t.region,t.market_code??null,t.market_code??null,this.now())??this.create(t)).immediate()}link(t,r,n){let s=S();try{s.transaction(()=>{this.requireOpen({journey_id:t},r);let i=s.prepare(`
396
+ SELECT journey_id, backend_id FROM telemetry_journey_links
397
+ WHERE link_type = ? AND link_id = ?
398
+ `).get(n.link_type,n.link_id);if(i){if(i.journey_id===t&&i.backend_id===(n.backend_id??null))return;throw new Error("JOURNEY_LINK_CONFLICT")}if(s.prepare(`
399
+ INSERT INTO telemetry_journey_links (link_type, link_id, journey_id, backend_id)
400
+ VALUES (?, ?, ?, ?)
401
+ `).run(n.link_type,n.link_id,t,n.backend_id??null),n.link_type==="request"){s.prepare(`
402
+ UPDATE telemetry_journeys SET expires_at = MAX(expires_at, ?) WHERE journey_id = ?
403
+ `).run(this.now()+1440*6e4,t);let a=s.prepare(`
404
+ SELECT link_id FROM telemetry_journey_links
405
+ WHERE journey_id = ? AND link_type = 'ride'
406
+ `).get(t);s.prepare(`
407
+ UPDATE ride_requests SET journey_id = ?, ride_id = COALESCE(?, ride_id)
408
+ WHERE request_id = ?
409
+ `).run(t,a?.link_id??null,n.link_id)}else if(n.link_type==="ride"){let a=s.prepare(`
410
+ SELECT link_id FROM telemetry_journey_links
411
+ WHERE journey_id = ? AND link_type = 'request'
412
+ `).get(t);a&&s.prepare(`
413
+ UPDATE ride_requests SET journey_id = ?, ride_id = ? WHERE request_id = ?
414
+ `).run(t,n.link_id,a.link_id)}})()}catch(i){throw i.code?.startsWith("SQLITE_CONSTRAINT")?new Error("JOURNEY_LINK_CONFLICT"):i}}linkRequestAndRide(t,r,n,s){S().transaction(()=>{this.link(t,r,{link_type:"ride",link_id:s}),this.link(t,r,{link_type:"request",link_id:n})})()}find(t,r){let n=S().prepare("SELECT * FROM telemetry_journeys WHERE journey_id = ?").get(t);return n?.account_id===r?n:void 0}resolveSearchForBooking(t,r,n){let s=S(),i=s.prepare(`
415
+ SELECT j.*, l.backend_id
416
+ FROM telemetry_journeys j
417
+ JOIN telemetry_journey_links l ON l.journey_id = j.journey_id
418
+ WHERE l.link_type = 'search' AND l.link_id = ?
419
+ `).get(t);if(!i)throw new Error("JOURNEY_NOT_FOUND");if(i.account_id!==r)throw new Error("JOURNEY_ACCOUNT_MISMATCH");let{backend_id:a,...o}=i,c=o.status==="open"&&o.expires_at>this.now();!c&&o.status==="open"&&s.prepare(`
420
+ UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
421
+ `).run(this.now(),o.journey_id);let u=o.payment_mode===n.payment_mode&&o.region===n.region&&o.market_code===n.market_code;return{journey:c&&u?o:void 0,backend_id:a}}close(t,r){let n=this.requireOpen({journey_id:t},r),s=this.now();return S().prepare(`
422
+ UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
423
+ `).run(s,t),{...n,status:"closed",closed_at:s}}requireOpen(t,r){let n=S(),s="journey_id"in t?n.prepare("SELECT * FROM telemetry_journeys WHERE journey_id = ?").get(t.journey_id):n.prepare(`
424
+ SELECT j.* FROM telemetry_journeys j
425
+ JOIN telemetry_journey_links l ON l.journey_id = j.journey_id
426
+ WHERE l.link_type = ? AND l.link_id = ?
427
+ `).get(t.link_type,t.link_id);if(!s)throw new Error("JOURNEY_NOT_FOUND");if(s.account_id!==r)throw new Error("JOURNEY_ACCOUNT_MISMATCH");if(s.status!=="open")throw new Error("JOURNEY_CLOSED");if(s.expires_at<=this.now())throw n.prepare(`
428
+ UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
429
+ `).run(this.now(),s.journey_id),new Error("JOURNEY_EXPIRED");return s}};function NN(e){let t=CN(16),r=BigInt(e);for(let s=5;s>=0;s--)t[s]=Number(r&0xffn),r>>=8n;t[6]=t[6]&15|112,t[8]=t[8]&63|128;let n=t.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}p();p();var ET=new Set(["MATCHED","CONFIRMED","ASSIGNED","PICKUP"]),TT=new Set([...ET,"PICKUP_ARRIVED"]),LN=new Set([...TT,"FINISHED","COMPLETED"]);function va(e){return e.toUpperCase().startsWith("INUSE")}function bT(e){return ET.has(e.toUpperCase())}function vT(e){return TT.has(e.toUpperCase())}function kN(e){return va(e)||LN.has(e.toUpperCase())}function xT(e){let t=e.toUpperCase();return xa(t)?!1:kN(t)||t==="NOT_MATCHED"||t.startsWith("EXPIRED")||t.startsWith("ERROR")}function xa(e){let t=e.toUpperCase();return t==="ERROR_PAYMENT"||t==="EXPIRED_BEFORE_PAY"}var Gr=["driver_search_started","driver_matched","pickup_arrived","ride_started","ride_arrived"];function Jl(e,t){let r=e.toUpperCase(),n=t?.toUpperCase(),s=new Set(RT(n)),i=RT(r).filter(a=>!s.has(a)).map(a=>MN(a,r));return r==="NOT_MATCHED"&&i.push({stage:"ride_abandoned",properties:{lifecycleStatus:r,journeyOutcome:"abandoned",dispatchOutcome:"no_driver"}}),r.includes("CANCELED")&&i.push({stage:"ride_cancelled",properties:{lifecycleStatus:r,journeyOutcome:"cancelled",cancellationActor:UN(r),cancellationStage:FN(r,t)}}),(r.startsWith("EXPIRED")||r.startsWith("ERROR"))&&i.push({stage:"ride_abandoned",properties:{lifecycleStatus:r,journeyOutcome:"abandoned",...xa(r)?{dispatchOutcome:"search_not_started"}:{}}}),i}function RT(e){return e?xa(e)?[]:e==="PENDING"?Gr.slice(0,1):e.startsWith("DRIVER_CANCELED")||bT(e)?Gr.slice(0,2):e==="PICKUP_ARRIVED"?Gr.slice(0,3):va(e)?Gr.slice(0,4):e==="FINISHED"||e==="COMPLETED"?Gr:e==="NOT_MATCHED"||e.startsWith("EXPIRED")||e.startsWith("ERROR")?Gr.slice(0,1):[]:[]}function MN(e,t){return e==="driver_search_started"?{stage:e,properties:{lifecycleStatus:t,dispatchOutcome:"search_started"}}:e==="driver_matched"?{stage:e,properties:{lifecycleStatus:t,dispatchOutcome:"matched"}}:e==="ride_arrived"?{stage:e,properties:{lifecycleStatus:t,journeyOutcome:"completed"}}:{stage:e,properties:{lifecycleStatus:t}}}function UN(e){return e.startsWith("USER_")?"rider":e.startsWith("DRIVER_")?"driver":e.startsWith("COMPANY_")?"company":"system"}function FN(e,t){let r=t?.toUpperCase();return r&&va(r)?"in_ride":e.startsWith("DRIVER_CANCELED")||r&&vT(r)?"post_match":"pre_match"}async function Ra(e,t,r,n,s=!1){let i=Xl(e,t);s||i?.started();let a=new Date().toISOString();try{let o=await r(),c=n?.(o);return s&&i?.started(c?.context,0,a),i?.completed(c?.result??o,c?.context),o}catch(o){throw s&&i?.started(void 0,0,a),i?.failed(o),o}finally{await i?.shutdown()}}function Yl(e,t,r,n){return Ra(e,{...t,command:"ride-search",startedStage:"vehicle_search_started",completedStage:s=>BN(s)?"options_presented":"zero_results",completedContext:DT,failedStage:"vehicle_search_failed",errorCode:"RIDE_SEARCH_FAILED"},r,n,n!==void 0)}async function Gt(e,t,r){let n=Xl(e,{command:"activation",completedStage:()=>t,accountId:r?.id});n?.completed(void 0),await n?.shutdown()}function BN(e){if(!e||typeof e!="object")return!1;let t=e.options;return Array.isArray(t)&&t.length>0}function zl(e,t,r,n){return Ra(e,{...t,command:"ride-request",startedStage:"call_confirmed",completedStage:()=>"booking_requested",additionalCompletedEvents:s=>t.paymentMode==="card"?[{stage:"payment_step_completed"},{stage:"ride_created"},...VN(s)]:[],completedContext:s=>DT(s,t.paymentMode==="card"),failedStage:"booking_failed",errorCode:"RIDE_REQUEST_FAILED",failureReason:s=>t.paymentMode==="card"?JN(s):"other"},r,n)}async function AT(e,t){let r=Xl(e,{...t,command:"tip",completedStage:()=>"tip_completed"});r?.completed(void 0),await r?.shutdown()}function wT(e,t,r){return Ra(e,{...t,command:"ride-pay-prepare",startedStage:"payment_started",completedStage:()=>"payment_authorization_prepared",failedStage:"payment_failed",errorCode:"RIDE_PAY_PREPARE_FAILED"},r)}function ST(e,t,r){return Ra(e,{...t,command:"ride-pay-confirm",startedStage:"payment_confirmation_started",completedStage:()=>"payment_completed",failedStage:"payment_failed",errorCode:"RIDE_PAY_CONFIRM_FAILED",failureReason:WN,resultFailureReason:n=>GN(n)?"other":void 0},r)}function Xl(e,t){try{let r=IT(e);if(!r)return;let n=t.journeyId,s=performance.now(),i=As(r,t),a,o=(c,u)=>({event_id:t.command==="ride-request"&&c==="call_confirmed"&&n?Kl(`${n}:call_confirmed`):qN(),stage:c,duration_ms:u??Math.max(0,Math.round(performance.now()-s))});return{started:(c,u,l)=>{let d=c?As(r,{...t,...c}):i;t.startedStage&&d.capture({event:"ambient_cli_command_started",...o(t.startedStage,u),occurredAt:l,outcome:"started"})},completed:(c,u)=>{let l=u?{...t,...u}:t,d=u?As(r,l):i,m=t.resultFailureReason?.(c);if(m&&t.failedStage&&t.errorCode){d.capture({event:"ambient_cli_command_failed",...o(t.failedStage),outcome:"failed",error_code:t.errorCode,failure_reason:m});return}let f=[{stage:t.completedStage(c)}],g=t.additionalCompletedEvents?.(c);g&&f.push(...g);let _=t.completedContext?.(c)??{};for(let E of f)(E.properties?As(r,{...l,...E.properties}):d).capture({event:"ambient_cli_command_completed",...o(E.stage),..._,outcome:"completed"})&&l.accountId&&E.stage==="ride_created"&&(a=l.accountId);if(l.accountId&&l.journeyId&&f.some(E=>HN(E.stage)))try{new pt().close(l.journeyId,l.accountId)}catch{}},failed:c=>{t.failedStage&&t.errorCode&&i.capture({event:"ambient_cli_command_failed",...o(t.failedStage),outcome:"failed",error_code:t.errorCode,failure_reason:t.failureReason?.(c)??"other"})},shutdown:async()=>{await i.shutdown()&&a&&Jo(a)}}}catch{return}}function IT(e){let t=De(),r=KN(t.install.repoBranch);return{transport:new _a,installationId:_T(e),cliVersion:t.artifact.cliVersion,environment:r}}function As(e,t,r){let n=PT(e,t,r);return new xi(e.transport,{installation_id:e.installationId,journey_id:t.journeyId,account_id:t.accountId,search_id:t.searchId,request_id:t.requestId,ride_id:t.rideId,market_code:t.marketCode,sub_market:t.subMarket,ah_user_type:n,lifecycle_status:t.lifecycleStatus,journey_outcome:t.journeyOutcome,cancellation_actor:t.cancellationActor,cancellation_stage:t.cancellationStage,dispatch_outcome:t.dispatchOutcome,command:t.command,region:t.region,payment_mode:t.paymentMode,cli_version:e.cliVersion,build_env:e.environment})}function PT(e,t,r){if(r)return r.ahUserType;if(t.ahUserType)return t.ahUserType;if(t.accountId)return sp(t.accountId,e.installationId,t.journeyId)}function DT(e,t=!1){if(!e||typeof e!="object")return{};let r=e,n=typeof r.search_id=="string"&&r.search_id?r.search_id:typeof r.searchId=="string"&&r.searchId?r.searchId:void 0,s=typeof r.rideId=="string"&&r.rideId?r.rideId:typeof r.ride_id=="string"&&r.ride_id?r.ride_id:void 0,i=typeof r.request_id=="string"&&r.request_id?r.request_id:t?s:void 0;return{search_id:n,request_id:i,ride_id:s}}function VN(e){if(!e||typeof e!="object")return[];let t=e.rideStatus;return typeof t!="string"?[]:Jl(t,"WAITPAY")}function GN(e){return!!e&&typeof e=="object"&&e.success===!1}function HN(e){return e==="ride_arrived"||e==="ride_cancelled"||e==="ride_abandoned"}async function OT(e,t){let r=Jl(t.status,t.previousStatus),n=[],s=t.paymentMode==="wallet_usdc"&&r.some(a=>a.stage==="driver_search_started"),i=t.rideId??t.requestId;(t.rideCreatedObserved||s)&&i&&n.push({stage:"ride_created",properties:{lifecycleStatus:t.status,dispatchOutcome:"search_started"}});for(let a of r)n.some(o=>o.stage===a.stage)||n.push(a);if(n.length!==0)try{let a=IT(e);if(!a)return;let o=PT(a,{...t,command:"ride-monitor"}),c=!1;for(let[u,l]of n.entries())As(a,{...t,command:"ride-monitor",...l.properties,lifecycleStatus:t.status},{ahUserType:o}).capture({event:"ambient_cli_command_completed",event_id:$N(t,l.stage,u),stage:l.stage,outcome:"completed",duration_ms:t.durationMs})&&t.accountId&&l.stage==="ride_created"&&(c=!0);await a.transport.shutdown(),c&&t.accountId&&Jo(t.accountId)}catch{}}function $N(e,t,r){let n=e.requestId??e.rideId;return n?Kl(`${n}:${t}`):r===0?e.eventId:Kl(`${e.eventId}:${t}`)}function Kl(e){return`evt_${jN("sha256").update(e).digest("hex").slice(0,24)}`}function WN(e){let t=e instanceof Error?e.message.toLowerCase():"";return/(?:no|zero|empty)\s+(?:wallet\s+)?balance|wallet\s+balance\s*(?:is|=)\s*0/.test(t)?"wallet_no_balance":t.includes("insufficient")?"wallet_insufficient_balance":"other"}function JN(e){return e instanceof Be&&(e.status===402||e.code==="card_api_error")?"card_error":"other"}function KN(e){if(e==="main")return"production";if(e==="dev"||e==="staging")return e;throw new Error(`Unsupported telemetry build environment: ${e}`)}var NT=300*1e3,zN=async e=>{let t=D();O(t.dataDir);let r=ai();w({wallets:r.map(n=>({address:n.wallet_address,type:n.wallet_type,label:n.label,valid:n.last_valid===1,created_at:n.created_at,...n.wallet_type==="privy"?{wallet_id:bt(n.wallet_address)?.wallet_id}:{}}))})};function XN(e){let t,r;process.platform==="darwin"?(t="open",r=[e]):process.platform==="win32"?(t="cmd",r=["/c","start",'""',e]):(t="xdg-open",r=[e]);try{let n=YN(t,r,{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var QN=async e=>{let t=D();O(t.dataDir),le(t.appServerUrl);let r=e.includes("--force-new"),n=e.includes("--no-wait"),s=Buffer.from(t.passphrase,"utf8"),i;try{i=await Vd(t,s,r)}catch(c){b({error:c.message}),process.exit(1)}if(n){w(i);return}if(i.status==="ready"){w(i);return}let a=i.auth_url;process.stderr.write(`Open this URL to authenticate:
430
+ ${a}
431
+
432
+ `),XN(a),process.stderr.write(`Waiting for authentication to complete (up to 5 minutes)\u2026
433
+ `);let o;try{o=await Vo(t,{waitMs:NT})}catch(c){b({error:c.message}),process.exit(1)}if(w(o),o.status==="ready"){await Gt(t.dataDir,"activation_authenticated",{id:vt(o.wallet_address)}),process.stderr.write(`Wallet registered: ${o.wallet_address}
434
+ `);return}o.status==="failed"&&(process.stderr.write(`Authentication failed: ${o.reason}
435
+ `),process.exit(1)),o.status==="pending"&&(process.stderr.write("Timeout reached \u2014 re-run `amb wallet-setup` to resume.\n"),process.exit(1)),process.stderr.write("No pending session found \u2014 re-run `amb wallet-setup`.\n"),process.exit(1)},ZN=async e=>{let t=D();O(t.dataDir),le(t.appServerUrl);let r=e.includes("--wait")?NT:0;try{let n=await Vo(t,{waitMs:r});n.status==="ready"&&await Gt(t.dataDir,"activation_authenticated",{id:vt(n.wallet_address)}),w(n)}catch(n){b({error:n.message}),process.exit(1)}},eL=async e=>{let[t,r]=e;t||(console.error("error: Usage: amb wallet-add-external <wallet_address> [label]"),process.exit(1));let n=D();O(n.dataDir),vd({wallet_address:t,label:r}),w({status:"registered",wallet_address:t,label:r??null})},tL=async e=>{let[t]=e;t||(console.error("error: Usage: amb wallet-balance <wallet_address>"),process.exit(1));let r=D();O(r.dataDir),J(t);try{let n=await Zd(t,r);w({wallet_address:t,...n})}catch(n){b({error:"RPC_ERROR",message:`Failed to fetch balance: ${n.message}`}),process.exit(1)}},rL=async e=>{let[t,r,n]=e;(!t||!r||!n)&&(console.error("error: Usage: amb wallet-sign <wallet_address> <sign_method> <siwe_file|json>"),console.error("hint: sign_method: personal_sign (SIWE login), eth_signTypedData_v4 (payment/tip)"),console.error(" SIWE: amb wallet-sign 0x... personal_sign /path/to/siwe-file.json"),console.error(` Payment: amb wallet-sign 0x... eth_signTypedData_v4 '{"types":...}'`),process.exit(1));let s=D();O(s.dataDir),J(t),le(s.appServerUrl);let i=Buffer.from(s.passphrase,"utf8"),a;if(r==="personal_sign")if(CT.existsSync(n)){let{message:o,expiresAt:c}=JSON.parse(CT.readFileSync(n,"utf8"));Date.now()/1e3>c&&(b({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1)),a=o}else a=n.replace(/\\n/g,`
436
+ `);else try{a=JSON.parse(n)}catch{b({error:"eth_signTypedData_v4 requires valid JSON typed data"}),process.exit(1)}try{let o=await cr({wallet_address:t,sign_method:r,message:a},s,i);w(o)}catch(o){b({error:o.message}),process.exit(1)}},nL=async e=>{let[t,r,n,s,i]=e;(!t||!r||!n||!s)&&(console.error("error: Usage: amb wallet-send-tx <wallet_address> <to> <value_eth> <chain_id> [data]"),console.error("hint: chain_id: 84532 (BASE_SEPOLIA), 11155111 (ETH_SEPOLIA)"),process.exit(1));let a=D();O(a.dataDir),J(t),le(a.appServerUrl);let o=Buffer.from(a.passphrase,"utf8");try{let c=await lr({wallet_address:t,to:r,value_eth:n,chain_id:parseInt(s,10),data:i},a,o);w(c)}catch(c){b({error:c.message}),process.exit(1)}},LT={"wallet-status":zN,"wallet-setup":QN,"wallet-setup-verify":ZN,"wallet-add-external":eL,"wallet-balance":tL,"wallet-sign":rL,"wallet-send-tx":nL};p();import{encodeFunctionData as LL,formatUnits as kL}from"viem";p();p();import{encodeFunctionData as Ql,parseAbi as sL}from"viem";var iL=sL(["function approve(address spender, uint256 amount) returns (bool)"]);function kT(e,t){return Ql({abi:iL,functionName:"approve",args:[e,t]})}function MT(e,t){return Ql({abi:sn,functionName:"depositMVL",args:[e,t]})}function UT(){return Ql({abi:sn,functionName:"withdraw",args:[]})}p();import FT from"fs";import aL from"crypto";function oL(e){let[t,r=""]=e.split("."),n=r.padEnd(18,"0").slice(0,18);return"0x"+(BigInt(t)*BigInt("1000000000000000000")+BigInt(n)).toString(16)}async function Aa(e,t,r){let{wallet_address:n,chain_id:s,calls:i,sponsor:a}=e,o=jt(n);if(!o)throw new Error(`Wallet not found: ${n}`);let c=bt(n);if(!c)throw new Error("External wallet: signing must be done externally");let u=tt(t.keysDir,c.k_i_key_path);if(!FT.existsSync(u))throw new Error(`Key file not found: ${u}`);let l=FT.readFileSync(u),d=qt(l,r),m=d.toString("utf8");try{let f=Date.now(),g=vi(f,m),_;try{_=await ui({walletId:c.wallet_id,quorumId:c.quorum_id,kIPub:c.k_i_pub,timestamp:f,kISig:g})}catch(N){throw(N instanceof Error?N.message:String(N)).includes("HTTP 401")&&Xt(o.wallet_address,"Unauthorized (401)"),N}if(!_.valid)throw Xt(o.wallet_address,_.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${_.reason??"unknown reason"}`);let E=i.map(N=>({to:N.to,value:oL(N.value_eth),...N.data?{data:N.data}:{}})),T={method:"wallet_sendCalls",caip2:`eip155:${s}`,chain_type:"ethereum",...a?{sponsor:!0}:{},params:{calls:E}},x=`${Date.now()}:${aL.randomUUID()}`,R=on(c.wallet_id,T,m,t.privyAppId,{"privy-idempotency-key":x}),I=await Sd({walletId:c.wallet_id,caip2:`eip155:${s}`,calls:E,idempotencyKey:x,kISig:R,...a?{sponsor:!0}:{}});return{kind:"transaction_id",transaction_id:I.transactionId,caip2:I.caip2}}finally{gt(d)}}p();import RL from"crypto";p();import{createSiweMessage as cL,parseSiweMessage as lL}from"viem/siwe";var uL=60;async function wa(e,t,r){let n=await Id({walletAddress:e,chainId:t},r),s=cL({domain:n.domain,address:e,uri:n.uri,version:n.version,chainId:n.chainId,nonce:n.nonce,issuedAt:new Date(n.issuedAt),expirationTime:new Date(n.expirationTime),...n.scheme?{scheme:n.scheme}:{}}),i=Math.floor(new Date(n.expirationTime).getTime()/1e3);return{message:s,expiresAt:i}}async function Sa(e,t,r){let n=lL(e),s=Math.floor(Date.now()/1e3),i=n.address,{flag:a}=await Cd(i,r),o=a?await Pd({message:e,signature:t},r):await Dd({message:e,signature:t},r),{accessToken:c,expiresIn:u}=o,l=s+u-uL;return $d(n.address,c,l),Tt(`[jwt-debug] SET cache_key=${n.address} expires_at=${l} now=${s} expiresIn=${u} pid=${process.pid}
437
+ `),{accessToken:c,expiresIn:u}}function Ce(e){return ie(e)}p();import{hashTypedData as dL,parseSignature as pL,concat as mL,toHex as fL,keccak256 as gL,toBytes as hL}from"viem";var AH=gL(hL("Kernel(bytes32 hash)"));function Ia(e){return dL(e)}function Pa(e){let{kernelDomain:t,innerDigest:r}=e;return{domain:{name:t.name,version:t.version,chainId:t.chainId,verifyingContract:t.verifyingContract},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Kernel:[{name:"hash",type:"bytes32"}]},primaryType:"Kernel",message:{hash:r}}}function Da(e){let{r:t,s:r,yParity:n}=pL(e),s=BigInt(r)|BigInt(n)<<255n;return mL(["0x00",t,fL(s,{size:32})])}p();async function jT(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/price-quote`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return await n.json();let s="";try{let i=await n.json();(i.code||i.message)&&(s=`${i.code??""} ${i.message??""}`.trim())}catch{}throw s||(s=await n.text().catch(()=>"")||`HTTP ${n.status}`),new Error(`POST /price-quote failed (${n.status}): ${s}`)}p();import{createPublicClient as yL,http as _L,parseAbi as EL,BaseError as TL,ContractFunctionZeroDataError as bL,ContractFunctionRevertedError as vL}from"viem";var xL=EL(["function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)"]);function Zl(e){return yL({transport:_L(e.rpcUrl)})}async function qT(e){return Zl(e).getChainId()}async function Oa(e,t){let r=await Zl(e).getCode({address:t});return!!r&&r!=="0x"}async function Ca(e,t){let r=t;try{let n=await Zl(e).readContract({address:r,abi:xL,functionName:"eip712Domain"});return{name:n[1],version:n[2],chainId:Number(n[3]),verifyingContract:r}}catch(n){if(!(n instanceof TL&&!!n.walk(i=>i instanceof bL||i instanceof vL)))throw n;return{name:"Kernel",version:"0.3.3",chainId:e.chainId,verifyingContract:r}}}function AL(e){let{capability:t,params:r}=e;return{domain:{name:t.domainName,version:t.domainVersion,chainId:t.chainId,verifyingContract:t.tokenAddress},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],ReceiveWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"ReceiveWithAuthorization",message:{from:r.from,to:r.to,value:r.value,validAfter:r.validAfter,validBefore:r.validBefore,nonce:r.nonce}}}function wL(e,t,r){let n=r.toLowerCase();return e.find(s=>s.network===t&&s.tokenAddress.toLowerCase()===n)}function SL(e){return Math.floor(Date.now()/1e3)+e+60}function IL(){return"0x"+RL.randomBytes(32).toString("hex")}async function PL(e,t){try{let r=await fetch(`${t.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay-capabilities`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return r.ok?await r.json():null}catch{return null}}async function DL(e){let{typedData:t,isSmartAccount:r,kernelDomain:n,walletSigner:s,config:i,passphrase:a,agent:o}=e;if(r){if(!n)throw new Error("KERNEL_DOMAIN_REQUIRED: smart-account agent needs a Kernel domain");let u=Ia(t),l=Pa({kernelDomain:n,innerDigest:u}),{wallet_signature:d}=await s({wallet_address:o,sign_method:"eth_signTypedData_v4",message:l},i,a);return Da(d)}let{wallet_signature:c}=await s({wallet_address:o,sign_method:"eth_signTypedData_v4",message:t},i,a);return c}async function OL(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return await n.json();let s="";try{let i=await n.json();(i.code||i.message)&&(s=`${i.code??""} ${i.message??""}`.trim())}catch{}throw s||(s=await n.text().catch(()=>"")||`HTTP ${n.status}`),new Error(`POST /relay failed (${n.status}): ${s}`)}function eu(e){return{request_id:e.requestId,status:e.status,tx_hash:e.txHash,error_code:e.errorCode,error_message:e.errorMessage}}async function Na(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay/${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(n.ok)return await n.json();let s=await n.text().catch(()=>"");throw new Error(`GET /relay/${t} failed (${n.status}): ${s||"no body"}`)}function BT(e){return e!=null&&"unavailable"in e}async function CL(e){let{params:t,network:r,config:n,passphrase:s,jwtProvider:i,capabilitiesFetcher:a,priceQuoteFetcher:o,smartAccountProbe:c,walletSigner:u,relaySubmitter:l}=e,d=i(t.wallet_address);if(!d)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");let m=await a(d,n);if(!m)return{unavailable:"PROBE_FAILED"};let f=wL(m.capabilities,r.name,t.token);if(!f)return{unavailable:"NO_CAPABILITY"};if(f.preferred==="PERMIT")throw new Error("PERMIT_NOT_IMPLEMENTED: relay capability is PERMIT-only; v2 supports AUTHORIZATION only");let g=await o(d,{network:r.name,tokenAddress:t.token,tokenAmount:t.amount},n),_={from:t.wallet_address,to:f.depositContractAddress,value:t.amount,validAfter:"0",validBefore:SL(m.deadlineMinBufferSec).toString(),nonce:IL()},E=AL({capability:f,params:_}),{isSmartAccount:T,kernelDomain:x}=await c(r,t.wallet_address),R=await DL({typedData:E,agent:t.wallet_address,isSmartAccount:T,kernelDomain:x,walletSigner:u,config:n,passphrase:s}),I=await l(d,{network:r.name,tokenAddress:t.token,params:{..._,quote:{mvlAmount:g.quote.mvlAmount,nonce:g.quote.nonce,timestamp:g.quote.timestamp,deadline:g.quote.deadline},quoteSignature:g.signature},signature:R},n);return{path:"relay",request_id:I.requestId,status:I.status,mvl_amount:g.quote.mvlAmount,tx_hash:I.txHash,error_code:I.errorCode,error_message:I.errorMessage,next_step:`Run \`amb deposit-relay-status ${t.wallet_address} ${I.requestId}\` until status is CONFIRMED or FAILED`}}var NL=new Set(["CONFIRMED","FAILED"]);async function VT(e,t,r,n={}){let s=n.intervalMs??3e3,i=n.timeoutMs??12e4,a=Date.now()+i,o=await Na(e,t,r);for(;!NL.has(o.status)&&Date.now()<a;)await new Promise(c=>setTimeout(c,s)),o=await Na(e,t,r);return o}function GT(e){return CL({...e,jwtProvider:Ce,capabilitiesFetcher:PL,priceQuoteFetcher:jT,smartAccountProbe:async(t,r)=>{let n=await Oa(t,r);return{isSmartAccount:n,kernelDomain:n?await Ca(t,r):void 0}},walletSigner:cr,relaySubmitter:OL})}async function HT(e,t,r,n){let s=await Pr(t);if(e.token.toLowerCase()!==s.toLowerCase()){let o=await GT({params:e,network:t,config:r,passphrase:n});if(BT(o))throw new Error(o.unavailable==="NO_CAPABILITY"?`TOKEN_NOT_DEPOSITABLE: the deposit relay has no capability for token ${e.token} on ${t.name}, so it cannot be deposited as collateral. MVL (${s}) is always accepted and needs no relay. Run \`amb deposit-tokens ${t.name}\` for the current list. Retrying will not help.`:`RELAY_UNAVAILABLE: the agent-deposit relay could not be reached for ${t.name}, so token ${e.token} cannot be deposited right now. Check the cached JWT and the gateway, then retry. Depositing MVL (${s}) directly needs no relay.`);return o}let i=BigInt(e.amount),a=await Aa({wallet_address:e.wallet_address,chain_id:t.chainId,sponsor:!0,calls:[{to:e.token,value_eth:"0",data:kT(t.depositContract,i)},{to:t.depositContract,value_eth:"0",data:MT(e.wallet_address,i)}]},r,n);return{path:"mvl-direct",token:e.token,agent:e.wallet_address,amount:e.amount,batch_tx:a}}p();async function $T(e,t,r,n){let s=await bi(t,e.wallet_address),i=BigInt(Math.floor(Date.now()/1e3));if(s>i){let o=Number(s-i),c=Math.ceil(o/60);throw new Error(`WITHDRAW_COOLDOWN: next withdraw allowed at unix ${s.toString()} (~${c} min from now). v2 enforces a per-agent withdraw cooldown.`)}let a=await lr({wallet_address:e.wallet_address,to:t.depositContract,value_eth:"0",chain_id:t.chainId,data:UT(),sponsor:!0},r,n);return{path:"mvl-withdraw",agent:e.wallet_address,withdraw_tx:a}}p();function WT(e,t,r){if(e<0n)throw new Error("requiredTokenWei: gapMvl must be >= 0");if(r<=0n)throw new Error("requiredTokenWei: mvlAmount must be > 0");return(e*t+r-1n)/r}function JT(e,t){let r=10n**BigInt(t),n=(e*100n+r-1n)/r,s=n/100n,i=n%100n;return`${s.toString()}.${i.toString().padStart(2,"0")}`}async function KT(e,t,r){let n=r.gatewayServerUrl.replace(/\/$/,""),s=`network=${encodeURIComponent(t.network)}&tokenAddress=${encodeURIComponent(t.tokenAddress)}`,i=await fetch(`${n}/v1/agent-deposit/exchange-rate?${s}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(i.ok)return await i.json();let a="";try{let o=await i.json();(o.code||o.message)&&(a=`${o.code??""} ${o.message??""}`.trim())}catch{}throw a||(a=await i.text().catch(()=>"")||`HTTP ${i.status}`),new Error(`GET /exchange-rate failed (${i.status}): ${a}`)}var YT="note: collateral is credited in MVL (not the deposited token); withdrawals return MVL.",ML="note: withdrawals return MVL regardless of the token originally deposited.";function XT(e){let t=e.message,r=t.match(/^([A-Z][A-Z0-9_]+):\s*(.+)$/s);r?b({error:r[1],message:r[2]}):b({error:t})}var UL="run SIWE login (siwe-request-message then siwe-submit) to compute the token amount needed to activate";async function FL(e,t,r,n){if(r===0n)return{entries:null,reason:null};let s=Ce(t);if(!s)return{entries:null,reason:"NO_JWT",hint:UL};try{let i=await Go(e);if(i.length===0)return{entries:null,reason:"RATE_UNAVAILABLE"};let o=(await Promise.allSettled(i.map(async c=>{let u=await Dr(e,c),l=await KT(s,{network:e.name,tokenAddress:c},n),d=WT(r,BigInt(l.tokenAmount),BigInt(l.mvlAmount));return{tokenAddress:c,symbol:u.symbol,tokenWei:d.toString(),display:`~${JT(d,u.decimals)} ${u.symbol} to activate`,ratePreview:l.ratePreview}}))).flatMap(c=>c.status==="fulfilled"?[c.value]:[]);return o.length===0?{entries:null,reason:"RATE_UNAVAILABLE"}:{entries:o,reason:null}}catch{return{entries:null,reason:"RATE_UNAVAILABLE"}}}var jL=async e=>{let[t]=e;t||(console.error("error: Usage: amb deposit-status <wallet_address>"),process.exit(1));let r=D();O(r.dataDir),J(t);try{let n=await Promise.allSettled(r.depositNetworks.map(async o=>{let[c,u,l,d,m]=await Promise.all([Ti(o,t),Ei(o,t),bi(o,t),es(o),Yd(o)]),f=d>u?d-u:0n,g=null,_=null;if(f>0n)try{let R=await Pr(o),I=await Dr(o,R);g={tokenAddress:R,symbol:I.symbol,tokenWei:f.toString(),display:`${kL(f,I.decimals)} ${I.symbol} to activate`}}catch(R){_=`MVL activation guidance unavailable: ${R.message}`}let E=await FL(o,t,f,r),T=[...g?[g]:[],...E.entries??[]],x=T.length>0?T:null;return{mvlError:_,network:o.name,isActive:c,deposited:u.toString(),minRequired:d.toString(),nextWithdrawAt:Number(l),mvlReserve:m.toString(),mvlGap:f.toString(),requiredToActivate:x,requiredToActivateReason:E.reason,...E.hint?{requiredToActivateHint:E.hint}:{}}})),s=[],i=[];n.forEach((o,c)=>{if(o.status==="fulfilled"){let{mvlError:u,...l}=o.value;s.push(l),u&&i.push({network:l.network,error:u})}else i.push({network:r.depositNetworks[c].name,error:o.reason?.message})});let a=s.some(o=>o.isActive);w({anyActive:a,networks:s,errors:i})}catch(n){b({error:n.message}),process.exit(1)}},qL=async e=>{let t=e.includes("--no-wait"),r=e.filter(l=>l!=="--no-wait"),[n,s,i,a]=r;if(!n||!s||!i||!a){console.error("error: Usage: amb deposit-add <wallet_address> <network> <token_address> <amount> [--no-wait]"),console.error('hint: amount is raw units (e.g. 1000 MVL = "1000000000000000000000")');let l=De().networks.depositNetworks;console.error(l.length?` network: ${l.join(", ")}`:" network: run `amb deposit-tokens` to see configured deposit networks"),console.error(" token: run `amb deposit-tokens <network>` for depositable token addresses"),process.exit(1)}let o=D();O(o.dataDir),J(n),le(o.appServerUrl);let c=o.depositNetworks.find(l=>l.name===s);c||(b({error:"UNKNOWN_NETWORK",message:`Network "${s}" not configured. Available: ${o.depositNetworks.map(l=>l.name).join(", ")}`}),process.exit(1));let u=Buffer.from(o.passphrase,"utf8");try{let l=await HT({wallet_address:n,token:i,amount:a},c,o,u);if(l.path!=="relay"){w(l);return}if(t){let{next_step:f,...g}=l;if(l.status==="FAILED"){w(g),process.exit(2);return}w(l.status==="CONFIRMED"?g:l),console.error(YT);return}let d=Ce(n);if(!d){b({error:"JWT_NOT_FOUND",request_id:l.request_id,message:"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first."}),process.exit(1);return}let m=await VT(d,l.request_id,o);w({path:"relay",mvl_amount:l.mvl_amount,...eu(m)}),m.status==="FAILED"&&process.exit(2),console.error(YT)}catch(l){XT(l),process.exit(1)}},BL=async e=>{let t=e[0],r=D(),n=t?r.depositNetworks.filter(s=>s.name===t):r.depositNetworks;n.length===0&&(b({error:"UNKNOWN_NETWORK",message:`Network "${t}" not configured. Available: ${r.depositNetworks.map(s=>s.name).join(", ")}`}),process.exit(1));try{let s=await Promise.allSettled(n.map(async o=>{let c=[],u=await Pr(o),l=null;try{l=await Dr(o,u)}catch(_){c.push(`MVL metadata unavailable: ${_.message}`)}let[d,m]=await Promise.allSettled([Go(o),es(o)]);d.status==="rejected"&&c.push(`convertible token list unavailable: ${d.reason?.message}`),m.status==="rejected"&&c.push(`minRequiredBalance unavailable: ${m.reason?.message}`);let f=await Promise.allSettled((d.status==="fulfilled"?d.value:[]).map(async _=>{let E=await Dr(o,_);return{token:_,symbol:E.symbol,name:E.name,decimals:E.decimals}})),g=[];return f.forEach((_,E)=>{if(_.status==="fulfilled")g.push(_.value);else{let T=d.status==="fulfilled"?d.value[E]:"(unknown)";c.push(`token ${T} metadata unavailable: ${_.reason?.message}`)}}),{scopedErrors:c,network:o.name,tokens:[{token:u,symbol:l?.symbol??null,name:l?.name??null,decimals:l?.decimals??null},...g],minRequiredMvl:m.status==="fulfilled"?m.value.toString():null}})),i=[],a=[];s.forEach((o,c)=>{if(o.status==="fulfilled"){let{scopedErrors:u,...l}=o.value;i.push(l);for(let d of u)a.push({network:l.network,error:d})}else a.push({network:n[c].name,error:o.reason?.message})}),w({networks:i,errors:a})}catch(s){b({error:s.message}),process.exit(1)}},VL=async e=>{let[t,r,n]=e;(!t||!r)&&(console.error("error: Usage: amb deposit-withdraw <wallet_address> <network>"),console.error("hint: v2 withdraws the full MVL ledger balance \u2014 no token arg needed."),console.error(" Subject to a per-agent withdraw cooldown enforced by the ledger."),process.exit(1)),n&&console.error(`warning: <token> positional argument ("${n}") is no longer used. v2 withdraws all MVL via router.withdraw(). Drop the token arg: \`amb deposit-withdraw <wallet_address> <network>\``);let s=D();O(s.dataDir),J(t),le(s.appServerUrl);let i=s.depositNetworks.find(o=>o.name===r);i||(b({error:"UNKNOWN_NETWORK",message:`Network "${r}" not configured. Available: ${s.depositNetworks.map(o=>o.name).join(", ")}`}),process.exit(1));let a=Buffer.from(s.passphrase,"utf8");try{let o=await $T({wallet_address:t},i,s,a);w(o),console.error(ML)}catch(o){XT(o),process.exit(1)}},GL="0xfd0Bf71F60660E2f608ed56e1659C450eB113120",HL=11155111,zT=2e5,$L=async e=>{let[t,r,n]=e;(!t||!r)&&(console.error("error: Usage: amb bridge-deposit-eth <wallet_address> <value_eth> [recipient]"),console.error("hint: omit recipient to bridge to the same address on L2"),process.exit(1));let s=n??t,i=LL({abi:[{name:"depositETHTo",type:"function",stateMutability:"payable",inputs:[{name:"_to",type:"address"},{name:"_minGasLimit",type:"uint32"},{name:"_extraData",type:"bytes"}],outputs:[]}],functionName:"depositETHTo",args:[s,zT,"0x"]}),a=D();O(a.dataDir),J(t),le(a.appServerUrl);let o=Buffer.from(a.passphrase,"utf8");try{let c=await lr({wallet_address:t,to:GL,value_eth:r,chain_id:HL,data:i},a,o);w({...c,l2_recipient:s,min_gas_limit:zT})}catch(c){b({error:c.message}),process.exit(1)}},WL=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb deposit-relay-status <wallet_address> <request_id>"),console.error('hint: <request_id> is from the deposit-add response when path="relay"'),process.exit(1));let n=D();O(n.dataDir);let s=Ce(t);s||(b({error:"JWT_NOT_FOUND",message:"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first."}),process.exit(1));try{let i=await Na(s,r,n);w(eu(i)),i.status==="FAILED"&&process.exit(2)}catch(i){b({error:i.message}),process.exit(1)}},QT={"deposit-status":jL,"deposit-add":qL,"deposit-tokens":BL,"deposit-withdraw":VL,"deposit-relay-status":WL,"bridge-deposit-eth":$L};p();import{createPublicClient as vk,http as xk,formatUnits as Rk}from"viem";import{base as Ak,baseSepolia as wk,mainnet as Sk,sepolia as Ik}from"viem/chains";p();import{randomUUID as JL}from"crypto";var KL=["INITIATED","BURN_SUBMITTED","ATTESTED","MINT_SUBMITTED","COMPLETED","FAILED"],fr=["COMPLETED","FAILED"],E$=KL.filter(e=>!fr.includes(e)),ZT=fr.map(()=>"?").join(","),YL={status:"status",fromBlock:"from_block",burnPrivyTxId:"burn_privy_tx_id",burnTxHash:"burn_tx_hash",relayRequestId:"relay_request_id",cctpNonce:"cctp_nonce",message:"message",attestation:"attestation",mintPrivyTxId:"mint_privy_tx_id",mintTxHash:"mint_tx_hash",mintFromBlock:"mint_from_block",mintAttempts:"mint_attempts",lastRevertSig:"last_revert_sig",mintedAmountRaw:"minted_amount_raw",failureReason:"failure_reason"};function tu(){return Math.floor(Date.now()/1e3)}function eb(e){let t=S();return t.transaction(()=>{if(t.prepare(`
438
+ SELECT id FROM bridge_jobs
439
+ WHERE wallet_address = ? AND status NOT IN (${ZT})
440
+ LIMIT 1
441
+ `).get(e.walletAddress,...fr))throw new Error("BRIDGE_JOB_IN_FLIGHT");let n=JL();return t.prepare(`
442
+ INSERT INTO bridge_jobs (
443
+ id, wallet_address, status, source_chain_id, dest_chain_id,
444
+ amount_raw, is_fast, max_fee_raw, from_block, mint_from_block
445
+ ) VALUES (@id, @walletAddress, 'INITIATED', @sourceChainId, @destChainId,
446
+ @amountRaw, @isFast, @maxFeeRaw, @fromBlock, @mintFromBlock)
447
+ `).run({id:n,walletAddress:e.walletAddress,sourceChainId:e.sourceChainId,destChainId:e.destChainId,amountRaw:e.amountRaw,isFast:e.isFast?1:0,maxFeeRaw:e.maxFeeRaw,fromBlock:e.fromBlock??null,mintFromBlock:e.mintFromBlock??null}),gr(n)})()}function gr(e){return S().prepare("SELECT * FROM bridge_jobs WHERE id = ?").get(e)}function tb(e){return S().prepare(`
448
+ SELECT * FROM bridge_jobs
449
+ WHERE wallet_address = ? AND status NOT IN (${ZT})
450
+ ORDER BY created_at DESC, rowid DESC LIMIT 1
451
+ `).get(e,...fr)}function rb(e,t=20){return S().prepare(`
452
+ SELECT * FROM bridge_jobs WHERE wallet_address = ?
453
+ ORDER BY created_at DESC, rowid DESC LIMIT ?
454
+ `).all(e,t)}function ru(e,t){let r=Object.entries(t),n=[],s=[];for(let[i,a]of r){let o=YL[i];if(!o)throw new Error(`updateJob: unknown field "${String(i)}"`);n.push(`${o} = ?`),s.push(a)}n.length!==0&&(n.push("updated_at = ?"),s.push(tu()),S().prepare(`UPDATE bridge_jobs SET ${n.join(", ")} WHERE id = ?`).run(...s,e))}function La(e,t,r=tu()){return S().prepare(`
455
+ UPDATE bridge_jobs SET lease_expires_at = ?, updated_at = ?
456
+ WHERE id = ? AND (lease_expires_at IS NULL OR lease_expires_at < ?)
457
+ `).run(r+t,r,e,r).changes===1}function nb(e){S().prepare("UPDATE bridge_jobs SET lease_expires_at = NULL, updated_at = ? WHERE id = ?").run(tu(),e)}p();function Sn(e){return S().prepare("SELECT * FROM bridge_fast_grants WHERE wallet_address = ?").get(e)}function sb(e,t){return S().prepare(`
458
+ INSERT INTO bridge_fast_grants (wallet_address, max_fee_raw)
459
+ VALUES (?, ?)
460
+ ON CONFLICT(wallet_address) DO UPDATE SET
461
+ max_fee_raw = excluded.max_fee_raw,
462
+ granted_at = CURRENT_TIMESTAMP
463
+ `).run(e,t),Sn(e)}function ib(e){return S().prepare("DELETE FROM bridge_fast_grants WHERE wallet_address = ?").run(e).changes>0}function nu(e,t){if(t===0n)return!0;let r=Sn(e);return r?t<=BigInt(r.max_fee_raw):!1}p();p();import{encodeFunctionData as iu,decodeEventLog as XL,pad as ub}from"viem";p();import{parseAbi as su,parseAbiItem as zL}from"viem";var ab=su(["function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold)"]),ob=su(["function receiveMessage(bytes message, bytes attestation) returns (bool)"]),cb=su(["function approve(address spender, uint256 amount) returns (bool)"]),lb=zL("event MintAndWithdraw(address indexed mintRecipient, uint256 amount, address indexed mintToken, uint256 feeCollected)");function db(e){return iu({abi:ab,functionName:"depositForBurn",args:[e.amount,e.destinationDomain,ub(e.mintRecipient,{size:32}),e.burnToken,ub("0x",{size:32}),e.maxFee,e.minFinalityThreshold]})}function pb(e,t){return iu({abi:ob,functionName:"receiveMessage",args:[e,t]})}function mb(e,t){return iu({abi:cb,functionName:"approve",args:[e,t]})}function ka(e,t,r){let n=t.toLowerCase(),s=r.toLowerCase();for(let i of e.logs??[]){if(i.address?.toLowerCase()!==n)continue;let a;try{a=XL({abi:[lb],data:i.data,topics:i.topics})}catch{continue}let o=a.args;if(o.mintRecipient?.toLowerCase()===s)return{amountRaw:o.amount,feeCollectedRaw:o.feeCollected}}return null}var gb="Run `amb bridge-usdc <wallet>` to resume",QL={status:"status",fromBlock:"from_block",burnPrivyTxId:"burn_privy_tx_id",burnTxHash:"burn_tx_hash",cctpNonce:"cctp_nonce",message:"message",attestation:"attestation",mintPrivyTxId:"mint_privy_tx_id",mintTxHash:"mint_tx_hash",mintFromBlock:"mint_from_block",mintAttempts:"mint_attempts",lastRevertSig:"last_revert_sig",mintedAmountRaw:"minted_amount_raw",failureReason:"failure_reason"};function _t(e,t){ru(e.id,t);let r={...e};for(let[n,s]of Object.entries(t)){let i=QL[n];i&&(r[i]=s)}return r}function Ma(e,t,r=!1){return _t(e,{status:"FAILED",failureReason:t}),{status:"FAILED",...r?{fundsMidFlight:!0}:{}}}function Ct(e,t,r={}){return{status:e,nextStep:gb,...t?.note?{note:t.note}:{},...t?.privyStatus?{privyStatus:t.privyStatus}:{},...r}}function hb(e,t){let r=BigInt(e.amount_raw);return t>=r&&t<=r+BigInt(e.max_fee_raw)}function Hr(e,t,r){return _t(e,{status:"COMPLETED",mintedAmountRaw:t}),{status:"COMPLETED",mintedAmountRaw:t,...r?{note:r}:{}}}function au(e){return`Your USDC arrived \u2014 the CCTP message for this transfer is redeemed on the destination chain \u2014 but the exact credited amount could not be read from the logs. Run \`amb wallet-balance ${e}\` to see the balance.`}async function ws(e,t){let r=BigInt(e.mint_from_block??e.from_block??"0"),n=await t.scanMintLogs(r,e.wallet_address);return n&&hb(e,BigInt(n.amountRaw))?n.amountRaw:null}async function yb(e,t){if(!e.cctp_nonce)return!1;try{return await t.isNonceUsed(e.cctp_nonce)}catch{return!1}}async function _b(e,t){if(BigInt(e.max_fee_raw)===0n)return{amountRaw:e.amount_raw};let r=await ws(e,t);return r?{amountRaw:r}:{amountRaw:null,note:au(e.wallet_address)}}function Eb(e){let t=e instanceof Error?e.message:String(e);return/already used|nonce already/i.test(t)}async function ZL(e,t,r){let n=await ws(e,t);if(n)return Hr(e,n);let s=gr(e.id)??e,i=s.last_revert_sig===r?s.mint_attempts+1:1,a=_t(e,{mintAttempts:i,lastRevertSig:r});if(i>=t.mintMaxAttempts)return Ma(a,`receiveMessage reverted ${i} times with the same signature (${r}). The burn already moved your USDC, so the funds are mid-flight and this job needs the \xA74.3 last-resort recovery: share \`amb bridge-usdc-status\` output with support.`,!0);try{let o=await t.sendMint(a);return a=_t(a,{status:"MINT_SUBMITTED",mintPrivyTxId:o.transactionId,mintTxHash:null}),Ct("MINT_SUBMITTED")}catch(o){if(Eb(o)){let c=await ws(a,t);if(c)return Hr(a,c)}throw o}}var fb=new Set;function ek(e){return fr.includes(e)}async function Tb(e,t){let r=`${e.id}:${e.burn_tx_hash??""}`;if(fb.has(r))return e;fb.add(r);try{let n=await t.registerRelay(e);if(n&&!e.relay_request_id)return ru(e.id,{relayRequestId:n}),gr(e.id)??e}catch{}return e}var ke=e=>({advanced:!1,result:e}),Ua=e=>({advanced:!0,job:e});async function tk(e,t){if(e.burn_privy_tx_id){let a=await t.resolveTxStatus(e.burn_privy_tx_id);return a.kind==="FAILED"?ke(Ma(e,`burn transaction failed (${a.privyStatus??"reverted"}); no USDC was burned`)):a.kind==="REPLACED"?(a.hash&&_t(e,{burnTxHash:a.hash}),ke(Ct("INITIATED",a,{note:`burn transaction was replaced (nonce replacement); now tracking ${a.hash}`}))):a.kind==="SUCCESS"&&a.hash?Ua(_t(e,{status:"BURN_SUBMITTED",burnTxHash:a.hash})):ke(Ct("INITIATED",a))}let r=BigInt(e.from_block??"0"),n=await t.currentBlock(),s=await t.scanBurnLogs(r,n,e.wallet_address);if(s)return Ua(_t(e,{status:"BURN_SUBMITTED",burnTxHash:s.hash}));let i=n-r;return i<BigInt(t.graceBlocks)?ke({status:"INITIATED",verdictWithheld:!0,nextStep:gb,note:`no DepositForBurn found yet, but only ${i} of ${t.graceBlocks} grace blocks have passed; withholding judgement`}):ke(Ma(e,`no DepositForBurn from ${e.wallet_address} in ${i} blocks since block ${r}; the burn never went out`))}async function rk(e,t){let r=e.burn_tx_hash;if(!r)return ke(Ct("BURN_SUBMITTED"));let n=await t.irisAttestation(e.source_chain_id,r);if(n&&n.attestation)return Ua(_t(e,{status:"ATTESTED",message:n.message,attestation:n.attestation,cctpNonce:n.nonce}));let s=n&&"delayReason"in n?n.delayReason:void 0,i=BigInt(e.from_block??"0");return await t.currentBlock()-i>=BigInt(t.graceBlocks)&&await t.getTransactionByHash(r)===null?ke(Ma(e,`burn transaction ${r} is no longer on the canonical chain (suspected reorg) and Circle has issued no attestation; the burn did not stand, so no USDC was lost`)):ke(Ct("BURN_SUBMITTED",void 0,s?{note:`Circle has not attested the burn yet; Iris reports: ${s}`}:{}))}async function nk(e,t){if(await yb(e,t)){let{amountRaw:n,note:s}=await _b(e,t);return ke(Hr(e,n,s))}let r=e.mint_from_block?e:_t(e,{mintFromBlock:(await t.destBlock()).toString()});try{let n=await t.sendMint(r);return Ua(_t(r,{status:"MINT_SUBMITTED",mintPrivyTxId:n.transactionId,mintTxHash:null}))}catch(n){if(Eb(n)){let s=await ws(r,t);if(s)return ke(Hr(r,s))}throw n}}async function sk(e,t){if(!e.mint_privy_tx_id)return ke(Ct("MINT_SUBMITTED"));let r=await t.resolveTxStatus(e.mint_privy_tx_id);if(r.kind==="FAILED")return ke(await ZL(e,t,r.privyStatus??"unknown_revert"));if(r.kind==="REPLACED")return r.hash&&_t(e,{mintTxHash:r.hash}),ke(Ct("MINT_SUBMITTED",r,{note:`mint transaction was replaced (nonce replacement); now tracking ${r.hash}`}));if(r.kind!=="SUCCESS"||!r.hash)return ke(Ct("MINT_SUBMITTED",r));let n=_t(e,{mintTxHash:r.hash}),s=await t.getReceipt(r.hash),i=s?ka(s,t.destTokenMessenger,n.wallet_address):null;if(i)return hb(n,i.amountRaw)?ke(Hr(n,i.amountRaw.toString())):ke(Ct("MINT_SUBMITTED",void 0,{note:`MintAndWithdraw paid ${i.amountRaw} which is outside the expected range ${n.amount_raw}..${BigInt(n.amount_raw)+BigInt(n.max_fee_raw)}; not treating the job as complete`}));if(await yb(n,t)){let{amountRaw:o,note:c}=await _b(n,t);return ke(Hr(n,o,c))}let a=await ws(n,t);return ke(a?Hr(n,a):Ct("MINT_SUBMITTED",void 0,{note:`mint transaction ${r.hash} succeeded but no MintAndWithdraw for ${n.wallet_address} was found yet`}))}async function bb(e,t){let r=await t.sendBurn(e),n=_t(e,{burnPrivyTxId:r.transactionId});return n=await Tb(n,t),Fa(n,t)}async function Fa(e,t){let r=e;for(let n=0;n<ik;n++){r.burn_tx_hash&&!ek(r.status)&&(r=await Tb(r,t));let s;switch(r.status){case"COMPLETED":return{status:"COMPLETED",mintedAmountRaw:r.minted_amount_raw};case"FAILED":return{status:"FAILED"};case"INITIATED":s=await tk(r,t);break;case"BURN_SUBMITTED":s=await rk(r,t);break;case"ATTESTED":s=await nk(r,t);break;case"MINT_SUBMITTED":s=await sk(r,t);break}if(!s.advanced)return s.result;r=s.job}return Ct(r.status)}var ik=8;p();var ak=10000n;function vb(e,t){return(e+t-1n)/t}function xb(e,t,r,n){let s=r?1e3:2e3,i=e.find(o=>o.finalityThreshold===s);if(!i)throw new Error(`IRIS_FEE_MISSING: no fee entry for finalityThreshold ${s} (got: ${e.map(o=>o.finalityThreshold).join(", ")||"none"})`);let a=vb(t*BigInt(i.minimumFee),ak);return vb(a*BigInt(100+n),100n)}async function ou(e,t){let r=`${t.irisBaseUrl}/v2/burn/USDC/fees/${t.srcDomain}/${t.dstDomain}`,n=await e(r);if(!n.ok)throw new Error(`IRIS_FEE_QUERY_FAILED: ${n.status} from ${r}`);let s=await n.json();return Array.isArray(s)?s:[]}function ok(e){return typeof e=="string"&&e.startsWith("0x")}function ck(e,t){let r=e.decodedMessage?.destinationDomain;if(r!==void 0&&Number(r)!==t.destinationDomain)return!1;let n=e.decodedMessage?.decodedMessageBody?.amount;return!(n!==void 0&&BigInt(n)!==t.amountRaw)}async function Rb(e,t){let r=`${t.irisBaseUrl}/v2/messages/${t.srcDomain}?transactionHash=${encodeURIComponent(t.transactionHash)}`,n=await e(r);if(n.status===404)return null;if(!n.ok)throw new Error(`IRIS_MESSAGE_QUERY_FAILED: ${n.status} from ${r}`);let i=(await n.json())?.messages;if(!Array.isArray(i)||i.length===0)return null;let a=i.find(o=>o.status==="complete"&&ck(o,t)&&typeof o.message=="string"&&ok(o.attestation));return a?{message:a.message,attestation:a.attestation,nonce:a.eventNonce??null}:null}p();import{decodeEventLog as lk,parseAbiItem as uk,pad as dk}from"viem";var pk=uk("event DepositForBurn(address indexed burnToken, uint256 amount, address indexed depositor, bytes32 mintRecipient, uint32 destinationDomain, bytes32 destinationTokenMessenger, bytes32 destinationCaller, uint256 maxFee, uint32 indexed minFinalityThreshold, bytes hookData)"),Ab=128,wb=8,mk=[/block range/i,/range is too large/i,/too many blocks/i,/query returned more than/i,/response size exceeded/i,/exceeds? (the )?max(imum)? (results|logs)/i];function fk(e){let t=e instanceof Error?e.message:String(e);return mk.some(r=>r.test(t))}async function Sb(e,t,r){let n=t.chunk??D().bridgeLogChunkBlocks,s=t.fromBlock,i=0;for(;s<=t.toBlock;){let a=s+BigInt(n)-1n;a>t.toBlock&&(a=t.toBlock);let o;try{o=await e({address:t.tokenMessenger,fromBlock:s,toBlock:a})}catch(u){if(!fk(u))throw u;if(++i>wb)throw new Error(`eth_getLogs range rejections are not converging after ${wb} halvings (blocks ${s}-${a})`);let l=Number(a-s+1n),d=Math.floor(l/2);if(d<Ab)throw new Error(`eth_getLogs still rejects the block range at the ${Ab}-block floor (blocks ${s}-${a}): ${u instanceof Error?u.message:String(u)}`);n=d;continue}i=0;let c=r(o);if(c!==null)return c;s=a+1n}return null}async function Ib(e,t,r,n){let s=t.tokenMessenger.toLowerCase(),i=r.toLowerCase(),a=dk(n.mintRecipient,{size:32}).toLowerCase();return Sb(e,t,o=>{for(let c of o){if(c.address?.toLowerCase()!==s)continue;let u;try{u=lk({abi:[pk],data:c.data,topics:c.topics})}catch{continue}let l=u.args;if(l.depositor?.toLowerCase()===i&&l.amount===n.amountRaw&&l.destinationDomain===n.destinationDomain&&l.mintRecipient?.toLowerCase()===a)return{transactionHash:c.transactionHash,blockNumber:BigInt(c.blockNumber),amountRaw:l.amount,mintRecipient:l.mintRecipient,destinationDomain:l.destinationDomain}}return null})}async function Pb(e,t,r){return Sb(e,t,n=>{for(let s of n){let i=ka({logs:[s]},t.tokenMessenger,r);if(i)return{transactionHash:s.transactionHash,blockNumber:BigInt(s.blockNumber),amountRaw:i.amountRaw,feeCollectedRaw:i.feeCollectedRaw}}return null})}p();var gk=["confirmed","finalized"],hk=["execution_reverted","failed","provider_error"],yk=["pending","broadcasted"];function _k(e){let t=e instanceof Error?e.message:String(e),r=/^HTTP (\d{3})\b/.exec(t);return r?Number(r[1]):void 0}async function Db(e,t){let r;try{r=await e(t)}catch(i){let a=_k(i);if(a!==void 0&&a>=400&&a<500&&a!==404)throw i;return{kind:"PENDING",note:`transaction lookup did not resolve (${i instanceof Error?i.message:String(i)}); treating as still in flight`}}let n=r.transactionHash??void 0,s=n?{hash:n}:{};return gk.includes(r.status)?{kind:"SUCCESS",...s}:hk.includes(r.status)?{kind:"FAILED",...s}:yk.includes(r.status)?{kind:"PENDING",...s}:r.status==="replaced"?n?{kind:"REPLACED",hash:n}:{kind:"PENDING",privyStatus:"replaced",note:"Privy reported `replaced` with no transaction hash; re-querying on the next resume"}:{kind:"PENDING",privyStatus:r.status,...s,note:`unrecognised Privy status \`${r.status}\`; treating as still in flight`}}p();var Ob=[{type:"function",name:"usedNonces",stateMutability:"view",inputs:[{name:"nonce",type:"bytes32"}],outputs:[{name:"",type:"uint256"}]}];async function Cb(e,t,r){return await e(t,r)!==0n}p();function Ek(e,t){return{walletAddress:e.wallet_address,...e.burn_privy_tx_id?{burnPrivyTxId:e.burn_privy_tx_id}:{},...e.burn_tx_hash?{burnTxHash:e.burn_tx_hash}:{},sourceNetwork:t.source.name,destNetwork:t.dest.name,srcDomain:t.source.cctpDomain,dstDomain:t.dest.cctpDomain,amountRaw:e.amount_raw,maxFeeRaw:e.max_fee_raw,isFast:e.is_fast===1}}async function Nb(e,t,r,n,s,i=1e4){let a=AbortSignal.timeout(i);async function o(){let l=await t(a);if(!l)return null;let d=await e(`${s.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-cctp-relay/relay-mint`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(Ek(r,n)),signal:a});if(!d.ok||!d.json)return null;let m=await d.json();return typeof m.requestId=="string"&&m.requestId.length>0?m.requestId:null}let c,u=new Promise(l=>{c=setTimeout(()=>l(null),i),c.unref?.()});try{return await Promise.race([o(),u])}catch{return null}finally{clearTimeout(c)}}var Mb=6,Pk=5e3,Dk=3*6e4,Ok=25*6e4,lu=e=>`Run \`amb bridge-usdc ${e}\` to resume`,uu=e=>`note: this bridge is NOT finished (status ${e}). Your USDC has not arrived yet \u2014 do not report it as complete.`,ja=e=>`This bridge could not complete on its own and your USDC is mid-flight.
464
+ Nothing is lost \u2014 it can be finished manually.
465
+ Send the full output of \`amb bridge-usdc-status ${e}\` to support.`,Ck=/^\d+(\.\d{1,6})?$/;function Ss(e){if(!Ck.test(e))throw new Error(`BRIDGE_AMOUNT_INVALID: "${e}" is not a decimal USDC amount. Expected digits with at most 6 decimal places (e.g. "50", "50.5"). No sign, no exponent, and no 7th decimal place \u2014 USDC has exactly 6, so a finer amount cannot be sent and is rejected rather than rounded.`);let[t,r=""]=e.split(".");return BigInt(t)*1000000n+BigInt(r.padEnd(Mb,"0"))}function Ne(e){return Rk(e,Mb)}var Nk={1:Sk,11155111:Ik,8453:Ak,84532:wk},Lk=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]}],kk=(e,t)=>{let r=vk({chain:Nk[e],transport:xk(t)});return{getBlockNumber:()=>r.getBlockNumber(),getReceipt:async n=>{try{return{logs:(await r.getTransactionReceipt({hash:n})).logs}}catch{return null}},getTransaction:async n=>{try{return{blockNumber:(await r.getTransaction({hash:n})).blockNumber??null}}catch{return null}},getLogs:async n=>(await r.getLogs({address:n.address,fromBlock:n.fromBlock,toBlock:n.toBlock})).map(i=>({address:i.address,topics:i.topics,data:i.data,blockNumber:`0x${(i.blockNumber??0n).toString(16)}`,transactionHash:i.transactionHash??""})),usedNonces:(n,s)=>r.readContract({address:n,abi:Ob,functionName:"usedNonces",args:[s]}),erc20Balance:(n,s)=>r.readContract({address:n,abi:Lk,functionName:"balanceOf",args:[s]})}},Is=kk;var In={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};function $r(e){return e instanceof Error?e.message:String(e)}function Ub(e){let t=/^HTTP (\d{3})\b/.exec($r(e));return t?Number(t[1]):void 0}var Mk=1e3,Uk=8e3,Fk=5;async function Lb(e){let t=Mk;for(let r=1;;r++)try{return await e()}catch(n){if(Ub(n)!==429||r>=Fk)throw n;await In.sleep(t),t=Math.min(t*2,Uk)}}function jk(e){let t=$r(e);return Ub(e)===403?{error:"BRIDGE_SPONSOR_NOT_ALLOWED",message:`The gas sponsor rejected this batch (403). This is an operations problem, not yours: the CCTP approve/depositForBurn rules are not deployed to the sponsor allowlist for this environment. No USDC was burned. Report it \u2014 retrying will not help. Server said: ${t}`}:/Request expired/i.test(t)?{error:"BRIDGE_CLOCK_SKEW",message:"The server rejected the request as expired. The idempotency key is generated at call time, so the only cause is this machine's clock drifting more than 5 minutes from the server's. Synchronise the system clock (e.g. enable NTP) and run the command again. Retrying without fixing the clock fails identically, so it was not retried."}:null}function qk(e,t,r){return async n=>{let s=Ce(e);if(s)return s;let{message:i}=await wa(e,t.paymentChainId,n),{wallet_signature:a}=await cr({wallet_address:e,sign_method:"personal_sign",message:i},t,r,n),{accessToken:o}=await Sa(i,a,n);return o}}function cu(e,t,r,n){let{source:s,dest:i}=t,a=Is(s.chainId,s.rpcUrl),o=Is(i.chainId,i.rpcUrl),c=BigInt(r.amount_raw)+BigInt(r.max_fee_raw);return{irisFees:(u,l)=>ou(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:u,dstDomain:l}),irisAttestation:(u,l)=>Rb(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:s.cctpDomain,transactionHash:l,destinationDomain:i.cctpDomain,amountRaw:c}),resolveTxStatus:u=>Db(Od,u),sendBurn:async u=>{let l=BigInt(u.amount_raw)+BigInt(u.max_fee_raw);return{transactionId:(await Lb(()=>Aa({wallet_address:u.wallet_address,chain_id:s.chainId,sponsor:!0,calls:[{to:s.usdcAddress,value_eth:"0",data:mb(s.tokenMessengerV2,l)},{to:s.tokenMessengerV2,value_eth:"0",data:db({amount:l,destinationDomain:i.cctpDomain,mintRecipient:u.wallet_address,burnToken:s.usdcAddress,maxFee:BigInt(u.max_fee_raw),minFinalityThreshold:u.is_fast?1e3:2e3})}]},e,n))).transaction_id}},sendMint:async u=>{let{message:l,attestation:d}=u;if(!l||!d)throw new Error("BRIDGE_NOT_ATTESTED: the job has no message/attestation to submit yet");let m=await Lb(()=>lr({wallet_address:u.wallet_address,to:i.messageTransmitterV2,value_eth:"0",chain_id:i.chainId,sponsor:!0,data:pb(l,d)},e,n));if(!m.transactionId)throw new Error("BRIDGE_NO_TRANSACTION_ID: the mint was submitted but the server returned no transaction id");return{transactionId:m.transactionId}},getReceipt:u=>o.getReceipt(u),currentBlock:()=>a.getBlockNumber(),destBlock:()=>o.getBlockNumber(),scanBurnLogs:async(u,l,d)=>{let m=await Ib(f=>a.getLogs(f),{fromBlock:u,toBlock:l,tokenMessenger:s.tokenMessengerV2},d,{amountRaw:c,mintRecipient:r.wallet_address,destinationDomain:i.cctpDomain});return m?{hash:m.transactionHash}:null},scanMintLogs:async(u,l)=>{let d=await Pb(m=>o.getLogs(m),{fromBlock:u,toBlock:await o.getBlockNumber(),tokenMessenger:i.tokenMessengerV2},l);return d?{amountRaw:d.amountRaw.toString()}:null},getTransactionByHash:u=>a.getTransaction(u),isNonceUsed:u=>Cb((l,d)=>o.usedNonces(l,d),i.messageTransmitterV2,u),registerRelay:u=>Nb(fetch,qk(u.wallet_address,e,n),u,t,e),now:()=>Math.floor(In.now()/1e3),destTokenMessenger:i.tokenMessengerV2,graceBlocks:e.bridgeBurnGraceBlocks,mintMaxAttempts:e.bridgeMintMaxAttempts}}function du(e){return fr.includes(e)}function qa(e){return e.status==="FAILED"&&!!e.burn_tx_hash&&!e.minted_amount_raw}function Bk(e){let t,r;switch(e.status){case"INITIATED":t="BURN_CONFIRMATION_PENDING",r=["ATTESTATION_PENDING","SERVER_MINT_PENDING","MINT_CONFIRMATION_PENDING"];break;case"BURN_SUBMITTED":t="ATTESTATION_PENDING",r=["SERVER_MINT_PENDING","MINT_CONFIRMATION_PENDING"];break;case"ATTESTED":t="SERVER_MINT_PENDING",r=["MINT_CONFIRMATION_PENDING"];break;case"MINT_SUBMITTED":t="MINT_CONFIRMATION_PENDING",r=[];break;case"COMPLETED":case"FAILED":return}return{status_class:"IN_PROGRESS",current_stage:t,remaining_stages:r,completion_mode:"SERVER_RELAY_WITH_CLI_FALLBACK",status_command:`amb bridge-usdc-status ${e.wallet_address} ${e.id}`,do_not_start_new_transfer:!0,user_action_required:"CHECK_STATUS_LATER"}}function Ba(e){let t=Bk(e);return{job_id:e.id,status:e.status,wallet_address:e.wallet_address,amount_usdc:Ne(BigInt(e.amount_raw)),amount_raw:e.amount_raw,max_fee_raw:e.max_fee_raw,is_fast:e.is_fast===1,source_chain_id:e.source_chain_id,dest_chain_id:e.dest_chain_id,...e.burn_tx_hash?{burn_tx_hash:e.burn_tx_hash}:{},...e.mint_tx_hash?{mint_tx_hash:e.mint_tx_hash}:{},...e.mint_attempts?{mint_attempts:e.mint_attempts}:{},...e.failure_reason?{failure_reason:e.failure_reason}:{},...e.status==="COMPLETED"?e.minted_amount_raw?{minted_amount:Ne(BigInt(e.minted_amount_raw)),minted_amount_raw:e.minted_amount_raw}:{minted_amount:null,minted_amount_raw:null,minted_amount_unknown:!0,minted_amount_note:au(e.wallet_address)}:{},...qa(e)?{funds_mid_flight:!0,recovery:ja(e.wallet_address)}:{},...t?{agent_guidance:t}:{}}}function Vk(e,t,r){let n=gr(e.id)??e,s=Ba(n),i=du(n.status);if(w({...s,...t.verdictWithheld?{verdict_withheld:!0}:{},...t.note?{note:t.note}:{},...t.privyStatus?{privy_status:t.privyStatus}:{},...i?{}:{next_step:lu(r)}}),!i){console.error(uu(n.status));return}n.status==="FAILED"&&((qa(n)||t.fundsMidFlight)&&console.error(ja(r)),process.exit(2))}async function Fb(e,t,r,n,s){let i=await ou(fetch,{irisBaseUrl:s.irisBaseUrl,srcDomain:s.source.cctpDomain,dstDomain:s.dest.cctpDomain}),a=xb(i,t,r,n.bridgeMaxFeeBufferPct),o=t+a,u=await Is(s.source.chainId,s.source.rpcUrl).erc20Balance(s.source.usdcAddress,e);return{amountRaw:t,maxFeeRaw:a,requiredRaw:o,sourceBalanceRaw:u,sufficient:u>=o}}var Gk=async e=>{let t=e.includes("--fast"),r=e.includes("--wait"),n=e.filter(l=>l!=="--fast"&&l!=="--wait"),[s,i]=n;if(!s){console.error("error: Usage: amb bridge-usdc <wallet_address> [amount] [--fast] [--wait]"),console.error('hint: amount is decimal USDC (e.g. "50", "50.5") \u2014 NOT raw units like deposit-add.'),console.error(" omit amount to resume an unfinished bridge (idempotent)."),process.exit(1);return}let a=D();if(!a.bridge){b({error:"BRIDGE_NOT_CONFIGURED",message:a.bridgeConfigError??"This build has no USDC bridge configured."}),process.exit(1);return}let o=a.bridge;O(a.dataDir),J(s),le(a.appServerUrl);let c=Buffer.from(a.passphrase,"utf8"),u;try{let l,d;if(i===void 0){let f=tb(s);if(!f){b({error:"BRIDGE_NO_ACTIVE_JOB",message:`No unfinished bridge for ${s}. Pass an amount to start one, or run \`amb bridge-usdc-status\` to see past jobs.`}),process.exit(1);return}if(!La(f.id,a.bridgeLeaseSec)){w({...Ba(f),lease_held:!0,next_step:lu(s)}),console.error(uu(f.status)),console.error("note: another process is already advancing this bridge; nothing was submitted.");return}u=f.id,l=f,d=await Fa(l,cu(a,o,l,c))}else{let f=Ss(i),g=Ss(a.bridgeMinUsdc);if(f<g){b({error:"BRIDGE_AMOUNT_BELOW_MIN",message:`${Ne(f)} USDC is below the fixed ${a.bridgeMinUsdc} USDC bridge minimum. Nothing was submitted.`,amount_usdc:Ne(f),min_usdc:a.bridgeMinUsdc}),process.exit(1);return}let _=await Fb(s,f,t,a,o),E=_.maxFeeRaw;if(!_.sufficient){b({error:"BRIDGE_INSUFFICIENT_USDC",message:`${Ne(_.sourceBalanceRaw)} USDC on ${o.source.name} is short of the ${Ne(_.requiredRaw)} USDC this transfer needs`+(E>0n?` (${Ne(f)} to receive + ${Ne(E)} max fee)`:"")+". Nothing was submitted.",source:o.source.name,balance_usdc:Ne(_.sourceBalanceRaw),required_usdc:Ne(_.requiredRaw),required_raw:_.requiredRaw.toString()}),process.exit(1);return}if(!nu(s,E)){let N=Sn(s);b({error:"BRIDGE_FEE_NOT_AUTHORIZED",message:`This transfer's fee is ${Ne(E)} USDC`+(N?`, above the ${Ne(BigInt(N.max_fee_raw))} USDC ceiling approved for this wallet`:", and this wallet has no standing fee approval")+`. Nothing was submitted. Either approve it with \`amb bridge-fast-grant ${s} <max_fee_usdc>\`, or drop \`--fast\` to send it as a Standard transfer, which costs nothing.`,max_fee_usdc:Ne(E),max_fee_raw:E.toString(),grant_max_fee_usdc:N?Ne(BigInt(N.max_fee_raw)):null}),process.exit(1);return}let x=await Is(o.source.chainId,o.source.rpcUrl).getBlockNumber(),I=await Is(o.dest.chainId,o.dest.rpcUrl).getBlockNumber();l=eb({walletAddress:s,sourceChainId:o.source.chainId,destChainId:o.dest.chainId,amountRaw:f.toString(),isFast:t,maxFeeRaw:E.toString(),fromBlock:x.toString(),mintFromBlock:I.toString()}),La(l.id,a.bridgeLeaseSec),u=l.id,d=await bb(l,cu(a,o,l,c))}if(t||r){let f=t?Dk:Ok,g=In.now()+f;for(;!du(d.status)&&In.now()<g;){await In.sleep(Math.min(Pk,g-In.now()));let _=gr(l.id);if(!_)break;La(_.id,a.bridgeLeaseSec),d=await Fa(_,cu(a,o,_,c))}}Vk(l,d,s)}catch(l){let d=jk(l);if(d)b(d);else if($r(l)==="BRIDGE_JOB_IN_FLIGHT")b({error:"BRIDGE_JOB_IN_FLIGHT",message:`A bridge is already running for ${s}. Run \`amb bridge-usdc ${s}\` (no amount) to resume it, or \`amb bridge-usdc-status ${s}\` to inspect it.`});else{let m=$r(l),f=m.match(/^([A-Z][A-Z0-9_]+):\s*(.+)$/s);f?b({error:f[1],message:f[2]}):b({error:m})}process.exit(1)}finally{u&&nb(u)}},Hk=async e=>{let[t,r]=e;if(!t){console.error("error: Usage: amb bridge-usdc-status <wallet_address> [job_id]"),process.exit(1);return}let n=D();O(n.dataDir);try{if(r){let a=gr(r);if(!a||a.wallet_address.toLowerCase()!==t.toLowerCase()){b({error:"BRIDGE_JOB_NOT_FOUND",message:`No bridge job ${r} for ${t}.`}),process.exit(1);return}w(Ba(a)),qa(a)&&console.error(ja(t));return}let s=rb(t),i=s.find(a=>!du(a.status));w({wallet_address:t,active_job_id:i?.id??null,jobs:s.map(Ba),...i?{next_step:lu(t)}:{}}),i&&console.error(uu(i.status));for(let a of s)if(qa(a)){console.error(ja(t));break}}catch(s){b({error:$r(s)}),process.exit(1)}};function kb(e){let t=Sn(e);return{wallet_address:e,granted:!!t,max_fee_usdc:t?Ne(BigInt(t.max_fee_raw)):null,max_fee_raw:t?t.max_fee_raw:null,granted_at:t?t.granted_at:null}}var $k=async e=>{let t=e.includes("--fast"),r=e.filter(c=>c!=="--fast"),[n,s]=r;if(!n||!s){console.error("error: Usage: amb bridge-usdc-quote <wallet_address> <amount> [--fast]"),console.error('hint: amount is decimal USDC (e.g. "90") \u2014 NOT raw units like deposit-add.'),console.error(" Starts nothing: this is a pure read."),process.exit(1);return}let i=D();if(!i.bridge){b({error:"BRIDGE_NOT_CONFIGURED",message:i.bridgeConfigError??"This build has no USDC bridge configured."}),process.exit(1);return}let a=i.bridge;O(i.dataDir),J(n);let o;try{o=Ss(s)}catch(c){b({error:"BRIDGE_AMOUNT_INVALID",message:$r(c).replace(/^BRIDGE_AMOUNT_INVALID:\s*/,"")}),process.exit(1);return}try{let c=await Fb(n,o,t,i,a),u=Sn(n);w({wallet_address:n,amount_usdc:Ne(c.amountRaw),amount_raw:c.amountRaw.toString(),mode:t?"fast":"standard",max_fee_usdc:Ne(c.maxFeeRaw),max_fee_raw:c.maxFeeRaw.toString(),required_usdc:Ne(c.requiredRaw),source:a.source.name,source_balance_usdc:Ne(c.sourceBalanceRaw),sufficient:c.sufficient,below_min:o<Ss(i.bridgeMinUsdc),min_usdc:i.bridgeMinUsdc,preauthorized:nu(n,c.maxFeeRaw),grant_max_fee_usdc:u?Ne(BigInt(u.max_fee_raw)):null})}catch(c){b({error:$r(c)}),process.exit(1)}},Wk=async e=>{let t=e.includes("--revoke"),r=e.filter(a=>a!=="--revoke"),[n,s]=r;if(!n){console.error("error: Usage: amb bridge-fast-grant <wallet_address> [<max_fee_usdc> | --revoke]"),console.error("hint: no argument reads the current grant; an amount sets it; --revoke clears it."),console.error(' max_fee_usdc is decimal USDC (e.g. "0.1") \u2014 the per-transfer fee ceiling'),console.error(" below which a Fast bridge proceeds without asking about the fee."),process.exit(1);return}if(t&&s!==void 0){b({error:"BRIDGE_GRANT_INVALID",message:"--revoke takes no amount. Pass an amount to set the ceiling, or --revoke alone to clear it. Nothing was changed."}),process.exit(1);return}let i=D();if(O(i.dataDir),J(n),t){ib(n),w(kb(n));return}if(s!==void 0){let a;try{a=Ss(s)}catch{b({error:"BRIDGE_GRANT_INVALID",message:`"${s}" is not a decimal USDC amount. Expected digits with at most 6 decimal places (e.g. "0.1"). Nothing was stored.`}),process.exit(1);return}sb(n,a.toString())}w(kb(n))},jb={"bridge-usdc":Gk,"bridge-usdc-status":Hk,"bridge-usdc-quote":$k,"bridge-fast-grant":Wk};p();import{randomUUID as Ex}from"crypto";p();var Jk={POLYGON:"https://polygonscan.com",POLYGON_AMOY:"https://amoy.polygonscan.com",BASE:"https://basescan.org",BASE_SEPOLIA:"https://sepolia.basescan.org",ETHEREUM:"https://etherscan.io",ETHEREUM_SEPOLIA:"https://sepolia.etherscan.io"};function Pn(e,t){if(!e||!t)return null;let r=Jk[e];return r?`${r}/tx/${t}`:null}p();function Va(e,t){S().prepare(`
466
+ INSERT OR REPLACE INTO phone_verifications (wallet_address, phone, verified_at)
467
+ VALUES (?, ?, CURRENT_TIMESTAMP)
468
+ `).run(e,t)}function qb(e){return S().prepare("SELECT phone FROM phone_verifications WHERE wallet_address = ? ORDER BY verified_at ASC").all(e).map(r=>r.phone)}function Bb(e,t){return S().prepare("SELECT 1 FROM phone_verifications WHERE wallet_address = ? AND phone = ?").get(e,t)!==void 0}p();function Ga(e){S().prepare(`
320
469
  INSERT OR REPLACE INTO ride_requests (
321
- request_id, wallet_address, member_id, region, product_code, status, price, pay_currency,
470
+ request_id, journey_id, ride_id, wallet_address, member_id, region, product_code, status, price, pay_currency,
322
471
  origin_name, origin_addr, origin_lat, origin_lng,
323
472
  dest_name, dest_addr, dest_lat, dest_lng,
324
473
  rider_name, rider_phone
325
474
  ) VALUES (
326
- @request_id, @wallet_address, @member_id, @region, @product_code, @status, @price, @pay_currency,
475
+ @request_id, @journey_id, @ride_id, @wallet_address, @member_id, @region, @product_code, @status, @price, @pay_currency,
327
476
  @origin_name, @origin_addr, @origin_lat, @origin_lng,
328
477
  @dest_name, @dest_addr, @dest_lat, @dest_lng,
329
478
  @rider_name, @rider_phone
330
479
  )
331
- `).run({...e,wallet_address:e.wallet_address??null,member_id:e.member_id??null,status:e.status??"WAITPAY",product_code:e.product_code??null,price:e.price??null,pay_currency:e.pay_currency??null,origin_name:e.origin_name??null,origin_addr:e.origin_addr??null,origin_lat:e.origin_lat??null,origin_lng:e.origin_lng??null,dest_name:e.dest_name??null,dest_addr:e.dest_addr??null,dest_lat:e.dest_lat??null,dest_lng:e.dest_lng??null,rider_name:e.rider_name??null,rider_phone:e.rider_phone??null})}function V(e){return T().prepare("SELECT * FROM ride_requests WHERE request_id = ?").get(e)}function Ve(e,t){T().prepare(`
480
+ `).run({...e,journey_id:e.journey_id??null,ride_id:e.ride_id??null,wallet_address:e.wallet_address??null,member_id:e.member_id??null,status:e.status??"WAITPAY",product_code:e.product_code??null,price:e.price??null,pay_currency:e.pay_currency??null,origin_name:e.origin_name??null,origin_addr:e.origin_addr??null,origin_lat:e.origin_lat??null,origin_lng:e.origin_lng??null,dest_name:e.dest_name??null,dest_addr:e.dest_addr??null,dest_lat:e.dest_lat??null,dest_lng:e.dest_lng??null,rider_name:e.rider_name??null,rider_phone:e.rider_phone??null})}function Ae(e){return S().prepare("SELECT * FROM ride_requests WHERE request_id = ?").get(e)}function Dn(e,t){S().prepare(`
332
481
  UPDATE ride_requests SET status = ?, status_updated_at = strftime('%s', 'now') WHERE request_id = ?
333
- `).run(t,e)}function Rr(e,t){T().prepare(`
334
- INSERT OR REPLACE INTO phone_verifications (wallet_address, phone, verified_at)
335
- VALUES (?, ?, CURRENT_TIMESTAMP)
336
- `).run(e,t)}function Zi(e){return T().prepare("SELECT phone FROM phone_verifications WHERE wallet_address = ? ORDER BY verified_at ASC").all(e).map(r=>r.phone)}function eo(e,t){return T().prepare("SELECT 1 FROM phone_verifications WHERE wallet_address = ? AND phone = ?").get(e,t)!==void 0}function to(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return T().prepare(`
337
- SELECT token, expires_at FROM jwt_cache WHERE cache_key = ? AND kind = ? AND expires_at > ?
338
- `).get(e,t,r)??null}function ro(e){let t=Math.floor(Date.now()/1e3),r=T();r.prepare("DELETE FROM tada_members WHERE id <> ?").run(e.id),r.prepare(`
339
- INSERT INTO tada_members (id, phone, display_name, region, created_at, last_active_at)
340
- VALUES (?, ?, ?, ?, ?, ?)
341
- ON CONFLICT(id) DO UPDATE SET
342
- phone = excluded.phone,
343
- display_name = excluded.display_name,
344
- region = excluded.region,
345
- last_active_at = excluded.last_active_at
346
- `).run(e.id,e.phone??null,e.display_name??null,e.region??null,t,t)}function St(){return T().prepare("SELECT * FROM tada_members ORDER BY last_active_at DESC LIMIT 1").get()}function no(e){let t=T();t.prepare("DELETE FROM jwt_cache WHERE cache_key = ? AND kind = 'member'").run(e),t.prepare("DELETE FROM tada_members WHERE id = ?").run(e)}function so(e,t){return!!T().prepare("SELECT 1 FROM processed_events WHERE ride_id=? AND event_id=?").get(e,t)}function io(e,t,r){T().prepare("INSERT OR IGNORE INTO processed_events(ride_id,event_id,seq) VALUES(?,?,?)").run(e,t,r)}function oo(e){return T().prepare("SELECT MAX(seq) AS m FROM processed_events WHERE ride_id=?").get(e).m??0}function it(e){if(e==null)return null;let t=e.trim();return t.length===0?null:t.toLowerCase()}function qn(e){let t=it(e.label),r=st({placeId:e.google_place_id??void 0,latitude:e.latitude,longitude:e.longitude});if(!r)throw new Error("upsertSavedPlace: cannot compute dedup_key (missing placeId and coords)");let n=T().prepare(`
482
+ `).run(t,e)}function Vb(e,t){S().prepare("UPDATE ride_requests SET ride_id = COALESCE(ride_id, ?) WHERE request_id = ?").run(t,e)}p();var Ps;function _e(e){Ps=e.replace(/\/$/,"")}async function Ht(e,t,r,n,s,i){let a={"Content-Type":"application/json",Authorization:`Bearer ${r}`,...i},o=s?`${Ps}${t}?${new URLSearchParams(s).toString()}`:`${Ps}${t}`,c=await fetch(o,{method:e,headers:a,body:n!==void 0?JSON.stringify(n):void 0});if(!c.ok){let u=await c.text().catch(()=>"");throw new Error(`HTTP ${c.status} ${c.statusText} on ${e} ${t}: ${u}`)}return c.json()}async function Gb(e,t,r){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`};r&&(n["payment-signature"]=r,n["x-signature-interpret-mode"]="general");let s=await fetch(`${Ps}/payment/ride`,{method:"POST",headers:n,body:JSON.stringify(t)});if(s.status===402){let a=s.headers.get("payment-required");if(!a)throw new Error("402 response missing payment-required header");let o=JSON.parse(Buffer.from(a,"base64").toString("utf-8"));return{status:402,accepts:o.accepts,nonce:o.nonce}}if(s.status===200||s.status===201){let a=s.headers.get("payment-response"),o=a?JSON.parse(Buffer.from(a,"base64").toString("utf-8")):{network:"",payer:"",success:!0,transaction:""};return{status:s.status,paymentResponse:o}}let i=await s.text().catch(()=>"");throw new Error(`HTTP ${s.status} ${s.statusText} on POST /payment/ride: ${i}`)}function Hb(e,t){return Ht("GET","/v1/phone-verification/check",e,void 0,{phone:t})}function $b(e,t){return Ht("POST","/v1/phone-verification/send-code",e,{phone:t})}function Wb(e,t,r){return Ht("POST","/v1/phone-verification/confirm",e,{phone:t,code:r})}function Jb(e,t,r){return Ht("POST","/v2/rides/base-search",e,{region:t,locations:r})}function Kb(e,t){return Ht("POST","/v2/rides/pre-request",e,t)}function Yb(e,t){return Gb(e,{rideRequestId:t,type:"RIDE"}).then(r=>{if(r.status!==402)throw new Error(`Expected 402 from payment probe, got ${r.status}`);return{accepts:r.accepts,nonce:r.nonce}})}function zb(e,t,r){return Gb(e,{rideRequestId:t,type:"RIDE"},r).then(n=>{if(n.status!==200&&n.status!==201)throw new Error(`Expected 200/201 from payment submit, got ${n.status}`);return n.paymentResponse})}var Ds={SIN:"SG",BKK:"TH",DEN:"CO",HCM:"VN",HAN:"VN",PNH:"KH",REP:"KH",SHV:"KH",KPK:"KH",SEL:"KR",ADD:"ET",JKT:"ID",HKG:"HK",NYC:"NY"},Kk={singapore:"SIN",bangkok:"BKK",denver:"DEN","ho chi minh":"HCM",saigon:"HCM",hcmc:"HCM",hanoi:"HAN","phnom penh":"PNH",sihanoukville:"SHV","siem reap":"REP",kampot:"KPK",seoul:"SEL","addis ababa":"ADD",jakarta:"JKT","hong kong":"HKG","new york":"NYC","new york city":"NYC",nyc:"NYC"};function Os(e){let t=e.toUpperCase();return Ds[t]?t:Kk[e.toLowerCase()]}var Yk={SIN:{lat:1.3521,lng:103.8198},BKK:{lat:13.7563,lng:100.5018},DEN:{lat:39.7392,lng:-104.9903},HCM:{lat:10.8231,lng:106.6297},HAN:{lat:21.0285,lng:105.8542},PNH:{lat:11.5564,lng:104.9282},REP:{lat:13.3633,lng:103.8564},SHV:{lat:10.6097,lng:103.523},KPK:{lat:10.6099,lng:104.18},SEL:{lat:37.5665,lng:126.978},ADD:{lat:9.032,lng:38.7469},JKT:{lat:-6.2088,lng:106.8456},HKG:{lat:22.3193,lng:114.1694},NYC:{lat:40.7128,lng:-74.006}};function Xb(e,t,r,n,s){let i=Ds[r];if(!i)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);let a=Yk[r],o=n??a.lat,c=s??a.lng;return Ht("GET","/v2/places/autocomplete",e,void 0,{input:t,latitude:String(o),longitude:String(c)},{region:i})}function Qb(e,t,r){let n=Ds[r];if(!n)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);return Ht("GET",`/v1/places/${encodeURIComponent(t)}`,e,void 0,{region:n,city:r},{region:n})}function Cs(e,t){return Ht("GET",`/v1/rides/request/${t}`,e)}function Ha(e,t,r,n){let s={};return r&&(s.reason=r),n!=null&&(s.cancelReasonType=n),Ht("POST",`/v2/rides/request/${t}/cancel`,e,s)}async function $a(e,t,r,n=20){let s={limit:String(n)};r&&(s.messageTs=r);let a=(await Ht("GET",`/v1/chat/${e}/messages`,t,void 0,s)).messages??[],o=a.length>0?a[a.length-1].createdAt:null;return{count:a.length,messages:a,next_cursor:o}}async function Wa(e,t,r,n){let s=new FormData,i=new Blob([new Uint8Array(r)],{type:n});s.append("image",i,"image");let a=await fetch(`${Ps}/v1/chat/${t}/image`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:s});if(!a.ok){let o=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status} ${a.statusText} on POST /v1/chat/${t}/image: ${o}`)}return a.json()}p();p();p();function Zb(e,t,r=18e4){let n=Date.now()+r;S().prepare(`
483
+ INSERT OR REPLACE INTO search_cache (check_sum, raw, expires_at)
484
+ VALUES (?, ?, ?)
485
+ `).run(e,t,n)}function ev(e){let t=Date.now();return S().prepare(`
486
+ SELECT raw FROM search_cache WHERE check_sum = ? AND expires_at > ?
487
+ `).get(e,t)?.raw??null}function tv(e,t,r=6e5){let n=Date.now()+r;S().prepare(`
488
+ INSERT OR REPLACE INTO payment_cache (request_id, data, expires_at)
489
+ VALUES (?, ?, ?)
490
+ `).run(e,JSON.stringify(t),n)}function rv(e){let t=Date.now(),r=S().prepare(`
491
+ SELECT data FROM payment_cache WHERE request_id = ? AND expires_at > ?
492
+ `).get(e,t);return r?JSON.parse(r.data):null}function Ja(e,t){Zb(e,t,18e4)}function Ka(e){return ev(e)}function Ya(e,t){let r=t.expiresAt-Date.now();tv(e,t,r>0?r:6e5)}function On(e){let t=rv(e);return t||null}p();var nv={12:"Ride Throo",14:"EV Throo"},sv={0:"Save Throo",1:"XL Throo",31:"EV Throo",13:"Premium Throo",4:"Premium XL Throo",4e4:"WAV Throo"};function za(e,t,r,n){return(e??"").toUpperCase()!=="NY"?n:t!==void 0&&t in nv?nv[t]:r!==void 0&&r in sv?sv[r]:n}p();function zk(e,t){return`${(t==="mi"?e/1609.344:e/1e3).toFixed(1)} ${t}`}function Xk(e){return`${Math.round(e/60)} min`}var Qk=e=>typeof e=="number"&&Number.isFinite(e),iv=(e,...t)=>{for(let r of t)if(Qk(e[r]))return e[r]};function av(e,t){if(e==null||typeof e!="object")return e;let r=e,n={...r},s=iv(r,"distance","distance_meter"),i=iv(r,"duration","duration_seconds");return s!==void 0&&(n.distance_display=zk(s,t)),i!==void 0&&(n.duration_display=Xk(i)),n}function Xa(e,t){if(Array.isArray(e))return e.map(n=>av(n,t));if(e==null||typeof e!="object")return e;let r={};for(let[n,s]of Object.entries(e))r[n]=av(s,t);return r}p();var Zk={minLat:15,maxLat:72,minLng:-168,maxLng:-52};function mt(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Invalid coordinate for region routing: lat=${e}, lng=${t}`);let r=Zk;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLng&&t<=r.maxLng?"US":"SG"}var eM=new Set(["NY"]);function St(e){return e&&eM.has(e.toUpperCase())?"US":"SG"}function Qa(e){return e==="US"?"mi":"km"}function Ze(e,t,r){return(t??{})[e]??r}function Ye(e,t){return Ze("US",e,t)}function tM(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function Za(e){let t=tM(e.wallet_address),r=await Jb(t,e.region,e.locations),n=JSON.stringify(r),s=r.checkSum;if(!s)throw new Error("product-search response missing checkSum field");Ja(s,n);let i=r.products??[],a=[];for(let o of i){let u=(o.priceInfos??[]).find(l=>l.currencyId===e.payCurrency);if(u){let l=u.supportedCurrencyPriceInfo;a.push({product_id:o.id,product_code:o.code,product_name:za(e.region,o.productType,o.carType,o.title),pay_currency:e.payCurrency,price:l?.priceAfterDiscount??l?.price,price_currency:l?.currency})}}return{search_id:s,options:a,routes:Xa(r.routes,Qa(St(e.region)))}}p();p();p();p();function Cn(e){return e.placeId?`gid:${e.placeId}`:Number.isFinite(e.latitude)&&Number.isFinite(e.longitude)?`coord:${e.latitude.toFixed(4)},${e.longitude.toFixed(4)}`:null}function Nn(e){if(e==null)return null;let t=e.trim();return t.length===0?null:t.toLowerCase()}function pu(e){let t=Nn(e.label),r=Cn({placeId:e.google_place_id??void 0,latitude:e.latitude,longitude:e.longitude});if(!r)throw new Error("upsertSavedPlace: cannot compute dedup_key (missing placeId and coords)");let n=S().prepare(`
347
493
  INSERT INTO places (
348
494
  wallet_address, label, name, formatted_address, latitude, longitude,
349
495
  google_place_id, city, region, ftid, kg_id, source_url,
@@ -354,16 +500,16 @@ ${Ln.randomUUID()}
354
500
  1, 0, NULL, @dedup_key,
355
501
  strftime('%s', 'now')
356
502
  )
357
- `).run({...e,label:t,google_place_id:e.google_place_id??null,ftid:e.ftid??null,kg_id:e.kg_id??null,dedup_key:r});return T().prepare("SELECT * FROM places WHERE id = ?").get(n.lastInsertRowid)}var pr="is_favorite DESC, hit_count DESC, last_used_at DESC NULLS LAST, created_at DESC";function jn(e,t={}){let r=["wallet_address = ?"],n=[e];t.favoritesOnly&&r.push("is_favorite = 1"),t.historyOnly&&r.push("is_favorite = 0");let s=`SELECT * FROM places WHERE ${r.join(" AND ")}
358
- ORDER BY ${pr}`;return t.limit&&t.limit>0&&(s+=" LIMIT ?",n.push(t.limit)),T().prepare(s).all(...n)}function ao(e,t,r={}){let n=Array.from(new Set(t.map(A=>A.trim().toLowerCase()).filter(A=>A.length>0)));if(n.length===0)return{matches:jn(e,r),matched_tier:null,normalized_queries:[]};let s=T(),i=[];r.favoritesOnly&&i.push("is_favorite = 1"),r.historyOnly&&i.push("is_favorite = 0");let o=i.length>0?` AND ${i.join(" AND ")}`:"",a=!!(r.limit&&r.limit>0),c=a?" LIMIT ?":"",l=n.map(()=>"?").join(","),d=[e,...n];a&&d.push(r.limit);let u=s.prepare(`SELECT * FROM places
359
- WHERE wallet_address = ? AND label IN (${l})${o}
360
- ORDER BY ${pr}${c}`).all(...d);if(u.length>0)return{matches:u,matched_tier:"label",normalized_queries:n};let m=n.map(A=>`%${A}%`),p=n.map(()=>"name LIKE ? COLLATE NOCASE").join(" OR "),f=[e,...m];a&&f.push(r.limit);let _=s.prepare(`SELECT * FROM places
361
- WHERE wallet_address = ? AND (${p})${o}
362
- ORDER BY ${pr}${c}`).all(...f);if(_.length>0)return{matches:_,matched_tier:"name",normalized_queries:n};let h=n.map(()=>"formatted_address LIKE ? COLLATE NOCASE").join(" OR "),I=[e,...m];a&&I.push(r.limit);let E=s.prepare(`SELECT * FROM places
363
- WHERE wallet_address = ? AND (${h})${o}
364
- ORDER BY ${pr}${c}`).all(...I);return E.length>0?{matches:E,matched_tier:"address",normalized_queries:n}:{matches:[],matched_tier:null,normalized_queries:n}}function co(e,t){let r=T().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t);return r?(T().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,t),r):null}function lo(e,t){let r=it(t);if(!r)return null;let n=T().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?(T().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,n.id),n):null}function uo(e){let t=T(),r=t.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?"),n=r.get(e.wallet_address,e.dedup_key);if(!n&&e.dedup_key.startsWith("gid:")){let i=`coord:${e.latitude.toFixed(4)},${e.longitude.toFixed(4)}`,o=r.get(e.wallet_address,i);if(o)if(t.prepare("SELECT id FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e.wallet_address,e.dedup_key))n=r.get(e.wallet_address,e.dedup_key);else try{t.prepare(`UPDATE places SET dedup_key = ?,
503
+ `).run({...e,label:t,google_place_id:e.google_place_id??null,ftid:e.ftid??null,kg_id:e.kg_id??null,dedup_key:r});return S().prepare("SELECT * FROM places WHERE id = ?").get(n.lastInsertRowid)}var eo="is_favorite DESC, hit_count DESC, last_used_at DESC NULLS LAST, created_at DESC";function mu(e,t={}){let r=["wallet_address = ?"],n=[e];t.favoritesOnly&&r.push("is_favorite = 1"),t.historyOnly&&r.push("is_favorite = 0");let s=`SELECT * FROM places WHERE ${r.join(" AND ")}
504
+ ORDER BY ${eo}`;return t.limit&&t.limit>0&&(s+=" LIMIT ?",n.push(t.limit)),S().prepare(s).all(...n)}function ov(e,t,r={}){let n=Array.from(new Set(t.map(R=>R.trim().toLowerCase()).filter(R=>R.length>0)));if(n.length===0)return{matches:mu(e,r),matched_tier:null,normalized_queries:[]};let s=S(),i=[];r.favoritesOnly&&i.push("is_favorite = 1"),r.historyOnly&&i.push("is_favorite = 0");let a=i.length>0?` AND ${i.join(" AND ")}`:"",o=!!(r.limit&&r.limit>0),c=o?" LIMIT ?":"",u=n.map(()=>"?").join(","),l=[e,...n];o&&l.push(r.limit);let d=s.prepare(`SELECT * FROM places
505
+ WHERE wallet_address = ? AND label IN (${u})${a}
506
+ ORDER BY ${eo}${c}`).all(...l);if(d.length>0)return{matches:d,matched_tier:"label",normalized_queries:n};let m=n.map(R=>`%${R}%`),f=n.map(()=>"name LIKE ? COLLATE NOCASE").join(" OR "),g=[e,...m];o&&g.push(r.limit);let _=s.prepare(`SELECT * FROM places
507
+ WHERE wallet_address = ? AND (${f})${a}
508
+ ORDER BY ${eo}${c}`).all(...g);if(_.length>0)return{matches:_,matched_tier:"name",normalized_queries:n};let E=n.map(()=>"formatted_address LIKE ? COLLATE NOCASE").join(" OR "),T=[e,...m];o&&T.push(r.limit);let x=s.prepare(`SELECT * FROM places
509
+ WHERE wallet_address = ? AND (${E})${a}
510
+ ORDER BY ${eo}${c}`).all(...T);return x.length>0?{matches:x,matched_tier:"address",normalized_queries:n}:{matches:[],matched_tier:null,normalized_queries:n}}function cv(e,t){let r=S().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t);return r?(S().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,t),r):null}function lv(e,t){let r=Nn(t);if(!r)return null;let n=S().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?(S().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,n.id),n):null}function uv(e){let t=S(),r=t.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?"),n=r.get(e.wallet_address,e.dedup_key);if(!n&&e.dedup_key.startsWith("gid:")){let i=`coord:${e.latitude.toFixed(4)},${e.longitude.toFixed(4)}`,a=r.get(e.wallet_address,i);if(a)if(t.prepare("SELECT id FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e.wallet_address,e.dedup_key))n=r.get(e.wallet_address,e.dedup_key);else try{t.prepare(`UPDATE places SET dedup_key = ?,
365
511
  google_place_id = COALESCE(google_place_id, ?)
366
- WHERE wallet_address = ? AND id = ?`).run(e.dedup_key,e.google_place_id,e.wallet_address,o.id),n=r.get(e.wallet_address,e.dedup_key)}catch(c){if(c.code!=="SQLITE_CONSTRAINT_UNIQUE")throw c;process.stderr.write(`[place-history] coord\u2192gid upgrade race for wallet=${e.wallet_address} key=${e.dedup_key}; falling through to gid row
512
+ WHERE wallet_address = ? AND id = ?`).run(e.dedup_key,e.google_place_id,e.wallet_address,a.id),n=r.get(e.wallet_address,e.dedup_key)}catch(c){if(c.code!=="SQLITE_CONSTRAINT_UNIQUE")throw c;process.stderr.write(`[place-history] coord\u2192gid upgrade race for wallet=${e.wallet_address} key=${e.dedup_key}; falling through to gid row
367
513
  `),n=r.get(e.wallet_address,e.dedup_key)}}if(n)return t.prepare(`UPDATE places SET hit_count = hit_count + 1, last_used_at = ?
368
514
  WHERE wallet_address = ? AND id = ?`).run(e.ts,e.wallet_address,n.id),t.prepare("SELECT * FROM places WHERE id = ?").get(n.id);let s=t.prepare(`
369
515
  INSERT INTO places (
@@ -375,7 +521,7 @@ ${Ln.randomUUID()}
375
521
  @google_place_id, NULL, @region, NULL, NULL, NULL,
376
522
  0, 1, @ts, @dedup_key, strftime('%s', 'now')
377
523
  )
378
- `).run(e);return t.prepare("SELECT * FROM places WHERE id = ?").get(s.lastInsertRowid)}function Gn(e,t){return T().prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t)}function Wn(e,t,r){let n=T();if(!n.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t))return null;let i="label"in r&&r.label!==void 0?1:0,o=i?it(r.label):null;return n.prepare(`
524
+ `).run(e);return t.prepare("SELECT * FROM places WHERE id = ?").get(s.lastInsertRowid)}function fu(e,t){return S().prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t)}function gu(e,t,r){let n=S();if(!n.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t))return null;let i="label"in r&&r.label!==void 0?1:0,a=i?Nn(r.label):null;return n.prepare(`
379
525
  UPDATE places SET
380
526
  is_favorite = 1,
381
527
  label = CASE WHEN @label_provided THEN @label ELSE label END,
@@ -389,91 +535,92 @@ ${Ln.randomUUID()}
389
535
  region = COALESCE(@region, region),
390
536
  updated_at = strftime('%s', 'now')
391
537
  WHERE wallet_address = @wallet_address AND dedup_key = @dedup_key
392
- `).run({wallet_address:e,dedup_key:t,label:o,label_provided:i,source_url:r.source_url??null,source_url_provided:"source_url"in r&&r.source_url!==void 0?1:0,google_place_id:r.google_place_id??null,ftid:r.ftid??null,kg_id:r.kg_id??null,formatted_address:r.formatted_address??null,name:r.name??null,city:r.city??null,region:r.region??null}),n.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t)}function At(e,t){return T().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function po(e,t,r){if(!At(e,t))return null;let s=r!==void 0?it(r):void 0;return T().prepare(`
538
+ `).run({wallet_address:e,dedup_key:t,label:a,label_provided:i,source_url:r.source_url??null,source_url_provided:"source_url"in r&&r.source_url!==void 0?1:0,google_place_id:r.google_place_id??null,ftid:r.ftid??null,kg_id:r.kg_id??null,formatted_address:r.formatted_address??null,name:r.name??null,city:r.city??null,region:r.region??null}),n.prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t)}function Ns(e,t){return S().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function dv(e,t,r){if(!Ns(e,t))return null;let s=r!==void 0?Nn(r):void 0;return S().prepare(`
393
539
  UPDATE places SET
394
540
  is_favorite = 1,
395
541
  label = CASE WHEN ? THEN ? ELSE label END,
396
542
  updated_at = strftime('%s','now')
397
543
  WHERE wallet_address = ? AND id = ?
398
- `).run(s!==void 0?1:0,s??null,e,t),T().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function mo(e,t){let r=it(t);if(r)return T().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r)}function go(e,t){let r=At(e,t);return r?r.is_favorite===0?r:(T().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
399
- WHERE wallet_address = ? AND id = ?`).run(e,t),T().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)):null}function fo(e,t){let r=it(t);if(!r)return null;let n=T().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?n.is_favorite===0?n:(T().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
400
- WHERE wallet_address = ? AND id = ?`).run(e,n.id),T().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,n.id)):null}var _o;function O(e){_o=e.replace(/\/$/,"")}async function de(e,t,r,n,s){let i={"Content-Type":"application/json","x-auth-client-id":"TadaRideAiAgent"};n&&(i.Authorization=`Bearer ${n}`);let o=await fetch(`${_o}${t}`,{method:e,headers:i,body:r!==void 0?JSON.stringify(r):void 0,...s?{signal:s}:{}});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`HTTP ${o.status} ${o.statusText} on ${e} ${t}: ${a}`)}return o.json()}function yo(e){return de("POST","/quorum-wallet/session",{kIPub:e})}async function br(e){let t=await de("GET",`/quorum-wallet/session/${e}`);return{...t,status:String(t.status).toUpperCase()}}function Tr(e){return de("POST","/quorum-wallet/validate",e)}function ho(e,t){return de("POST","/quorum-wallet/cosign",e,void 0,t)}function wo(e){return de("POST","/quorum-wallet/sendtx",e)}function Eo(e){return de("POST","/quorum-wallet/sendcalls",e)}function Ro(e,t){return de("POST","/auth/siwe/nonce",e,void 0,t)}function bo(e,t){return de("POST","/auth/siwe/token",e,void 0,t)}function To(e,t){return de("POST","/auth/siwe/users",e,void 0,t)}function So(e){return de("GET",`/quorum-wallet/transaction/${e}`)}function Ao(e,t){return de("GET",`/auth/siwe/users/${e}`,void 0,void 0,t)}import ue from"fs";import xt from"path";function It(e,t,r){return`${e}?handle=${t}&pub=${encodeURIComponent(r)}`}async function Io(e,t,r=!1){let n=r?[]:fr();if(n.length>0){let m=[],p=[];for(let f of n){let _=ae(f.wallet_address);if(!_){p.push(f.wallet_address);continue}try{let h=Q(e.keysDir,_.k_i_key_path);if(!ue.existsSync(h)){p.push(f.wallet_address);continue}let I=ue.readFileSync(h),E=fe(I,t),A=E.toString("utf8"),N=Qt(A);if(ne(E),N!==_.k_i_pub){p.push(f.wallet_address);continue}m.push({wallet_address:f.wallet_address,wallet_id:_.wallet_id})}catch{p.push(f.wallet_address)}}if(m.length>0){if(p.length>0)for(let f of p)Ae(f,"Local validation failed");return{status:"ready",wallets:m}}for(let f of p)Ae(f,"Local validation failed")}let s=yr();if(s){try{let m=await br(s.session_token);if(m.status==="PENDING")return{status:"auth_pending",auth_url:It(e.webappUrl,s.session_token,s.k_i_pub),next_action:"AFTER_USER_COMPLETES_AUTH_CALL_wallet_check_auth"};if(m.status==="DONE"){let{quorumId:p,walletId:f,walletAddress:_}=m,h=e.keysDir,I=Q(h,s.k_i_key_path),E=xt.join(h,`${_}_private.enc`);return ue.renameSync(I,E),ue.rmSync(xt.join(h,`${s.session_token}_public.pem`),{force:!0}),mr({wallet_address:_,wallet_id:f,quorum_id:p,k_i_pub:s.k_i_pub,k_i_key_path:er(E)}),_r(_),We(s.session_token),{status:"ready",wallets:[{wallet_address:_,wallet_id:f}]}}}catch{}ue.rmSync(Q(e.keysDir,s.k_i_key_path),{force:!0}),ue.rmSync(xt.join(e.keysDir,`${s.session_token}_public.pem`),{force:!0}),We(s.session_token)}let{publicKeyPem:i,privateKeyPem:o}=si(),a=ii(i),{sessionToken:c}=await yo(a),l=It(e.webappUrl,c,a),d=xt.join(e.keysDir,`${c}_private.enc`),u=xt.join(e.keysDir,`${c}_public.pem`);try{ue.mkdirSync(e.keysDir,{recursive:!0,mode:448});let m=Buffer.from(o,"utf8"),p=ai(m,t);ne(m),ue.writeFileSync(d,p,{mode:384}),ue.writeFileSync(u,i,{mode:420}),ji({session_token:c,k_i_pub:a,k_i_key_path:d})}catch(m){throw ue.rmSync(d,{force:!0}),ue.rmSync(u,{force:!0}),m}return{status:"auth_required",auth_url:l,next_action:"SHOW_AUTH_URL_TO_USER_THEN_IMMEDIATELY_CALL_wallet_check_auth_WITHOUT_WAITING_FOR_USER_CONFIRMATION"}}import xo from"fs";import vo from"path";var uu=1e3;async function Vn(e,t={}){let r=yr();if(!r)return{status:"no_pending"};let{session_token:n,k_i_pub:s,k_i_key_path:i}=r,o=It(e.webappUrl,n,s),a=Date.now()+(t.waitMs??0),c;for(;c=await br(n),c.status==="PENDING";){if(Date.now()>=a)return{status:"pending",auth_url:o};await new Promise(h=>setTimeout(h,uu))}if(c.status!=="DONE")return We(n),{status:"failed",reason:c.status==="FAILED"?c.reason:`Unexpected session status: ${c.status}`};let{quorumId:l,walletId:d,walletAddress:u}=c,m=e.keysDir,p=Q(m,i),f=vo.join(m,`${u}_private.enc`),_=vo.join(m,`${n}_public.pem`);try{xo.renameSync(p,f)}catch(h){throw We(n),new Error(`Failed to rename key file: ${h}`)}return xo.rmSync(_,{force:!0}),mr({wallet_address:u,wallet_id:d,quorum_id:l,k_i_pub:s,k_i_key_path:er(f)}),_r(u),We(n),{status:"ready",wallet_address:u}}function k(e){ye(e)||(g({error:"WALLET_NOT_FOUND",message:`Wallet ${e} is not registered.`,action:"Run `amb wallet-setup --no-wait` first to create the built-in wallet."}),process.exit(1))}function $(e){let t=P(e),r=Math.floor(Date.now()/1e3);oe(`[jwt-debug] GET cache_key=${e} now=${r} found=${!!t} pid=${process.pid}
401
- `),t||(g({error:"JWT_NOT_FOUND",message:`No valid JWT for wallet ${e}.`,action:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1))}import{createPublicClient as Ou,http as Mu,formatUnits as es,parseAbi as Uu}from"viem";import{baseSepolia as Do,base as Bu,mainnet as Fu,sepolia as $u}from"viem/chains";function No(e){let t=new Map,r=(i,o,a)=>{let c=t.get(i);if(c)return c;let l={network:i,chainId:o,rpcUrl:a,tokens:[{kind:"native"}]};return t.set(i,l),l},n=(i,o)=>{i.tokens.some(c=>c.kind==="erc20"&&c.address.toLowerCase()===o.toLowerCase())||i.tokens.push({kind:"erc20",symbol:"USDC",decimals:6,address:o})};n(r(e.paymentNetwork,e.paymentChainId,e.paymentRpcUrl),e.paymentUsdcAddress);let s=e.bridge?.source;s&&n(r(s.name,s.chainId,s.rpcUrl),s.usdcAddress);for(let i of e.depositNetworks)r(i.name,i.chainId,i.rpcUrl).tokens.push({kind:"mvl",deposit:i});return[...t.values()]}import{createPublicClient as _u,http as yu,parseAbi as hu}from"viem";import{baseSepolia as wu,base as Eu,mainnet as Ru,sepolia as bu}from"viem/chains";import{parseAbi as pu}from"viem";var ot=pu(["function mvlReserve() view returns (uint256)","function supportedTokens() view returns (address[])","function isAllowedToken(address token) view returns (bool)","function maxDeposit(address token) view returns (uint256)","function tokenDeposits(address agent, address token) view returns (uint256)","function maxPriceAge() view returns (uint256)","function isQuoteNonceUsed(address agent, uint256 nonce) view returns (bool)","function isDepositNonceUsed(address agent, uint256 nonce) view returns (bool)","function DOMAIN_SEPARATOR() view returns (bytes32)","function depositMVL(address agent, uint256 amount)","function withdraw()"]);import{parseAbi as mu}from"viem";var at=mu(["function deposits(address agent) view returns (uint256)","function isAgentActive(address agent) view returns (bool)","function nextWithdrawAt(address agent) view returns (uint256)","function minRequiredBalance() view returns (uint256)","function withdrawCooldown() view returns (uint256)","function router() view returns (address)","function mvlToken() view returns (address)","function treasury() view returns (uint256)"]);import{encodeFunctionData as Jn,parseAbi as gu}from"viem";var fu=gu(["function approve(address spender, uint256 amount) returns (bool)"]);function Kn(e,t){return Jn({abi:fu,functionName:"approve",args:[e,t]})}function Yn(e,t){return Jn({abi:ot,functionName:"depositMVL",args:[e,t]})}function Xn(){return Jn({abi:ot,functionName:"withdraw",args:[]})}var Tu={84532:wu,8453:Eu,1:Ru,11155111:bu},Qh=hu(["function allowance(address owner, address spender) view returns (uint256)"]);function Su(e){let t=Tu[e];if(!t)throw new Error(`Unsupported chainId: ${e}`);return t}function Je(e){return _u({chain:Su(e.chainId),transport:yu(e.rpcUrl)})}async function Sr(e,t){return await Je(e).readContract({address:e.agentDepositLedger,abi:at,functionName:"deposits",args:[t]})}async function Ar(e,t){return await Je(e).readContract({address:e.agentDepositLedger,abi:at,functionName:"isAgentActive",args:[t]})}async function zn(e){return(await Je(e).readContract({address:e.depositContract,abi:ot,functionName:"supportedTokens"})).filter(r=>!/^0x0{40}$/i.test(r))}async function Ir(e,t){return await Je(e).readContract({address:e.agentDepositLedger,abi:at,functionName:"nextWithdrawAt",args:[t]})}async function vt(e){return await Je(e).readContract({address:e.agentDepositLedger,abi:at,functionName:"minRequiredBalance"})}async function Ke(e){return await Je(e).readContract({address:e.agentDepositLedger,abi:at,functionName:"mvlToken"})}async function ko(e){return await Je(e).readContract({address:e.depositContract,abi:ot,functionName:"mvlReserve"})}import{createPublicClient as Au,http as Iu,parseAbi as xu,formatUnits as nw}from"viem";import{baseSepolia as vu,base as Nu,mainnet as ku,sepolia as Cu}from"viem/chains";var Du={84532:vu,8453:Nu,1:ku,11155111:Cu},Qn=xu(["function symbol() view returns (string)","function name() view returns (string)","function decimals() view returns (uint8)"]),Pu={BASE_SEPOLIA:{"0x036cbd53842c5426634e7929541ec2318f3dcf7e":{symbol:"USDC",name:"USDC",decimals:6}},BASE:{"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":{symbol:"USDC",name:"USD Coin",decimals:6}},ETHEREUM_SEPOLIA:{"0x3cf4ccf7ec4bb094d1504d1315057a46005d5065":{symbol:"MVL",name:"Mass Vehicle Ledger Token",decimals:18}},ETHEREUM:{"0xa849eaae994fb86afa73382e9bd88c2b6b18dc71":{symbol:"MVL",name:"Mass Vehicle Ledger Token",decimals:18}}},Zn=new Map;function Lu(e,t){return`${e}:${t.toLowerCase()}`}async function Ye(e,t){let r=Lu(e.name,t),n=Zn.get(r);if(n)return n;let s=Pu[e.name]?.[t.toLowerCase()];if(s)return Zn.set(r,s),s;let i=Du[e.chainId],o=Au({chain:i,transport:Iu(e.rpcUrl)}),a=t,[c,l,d]=await Promise.all([o.readContract({address:a,abi:Qn,functionName:"symbol"}),o.readContract({address:a,abi:Qn,functionName:"name"}),o.readContract({address:a,abi:Qn,functionName:"decimals"})]),u={symbol:c,name:l,decimals:d};return Zn.set(r,u),u}var Po={84532:Do,8453:Bu,1:Fu,11155111:$u},Hu=Uu(["function balanceOf(address account) view returns (uint256)"]),qu=(e,t)=>Ou({chain:Po[e]??Do,transport:Mu(t)});function Co(e,t,r){return e.readContract({address:t,abi:Hu,functionName:"balanceOf",args:[r]})}async function Lo(e,t,r={}){let n=r.makeClient??qu,s=r.mvlTokenReader??Ke,i=r.tokenMetadata??Ye,o=No(t),a=await Promise.all(o.map(async m=>{let p;try{p=n(m.chainId,m.rpcUrl)}catch(f){return m.tokens.map(_=>({status:"rejected",network:m.network,symbol:d(_),error:f.message}))}return await Promise.all(m.tokens.map(async f=>{try{return{status:"fulfilled",row:await u(f,m,p)}}catch(_){return{status:"rejected",network:m.network,symbol:d(f),error:_.message}}}))})),c=[],l=[];for(let m of a.flat())m.status==="fulfilled"?c.push(m.row):l.push({network:m.network,symbol:m.symbol,error:m.error});return{balances:c,errors:l};function d(m){return m.kind==="erc20"?m.symbol:m.kind==="mvl"?"MVL":"native"}async function u(m,p,f){let _=p.network;if(m.kind==="native"){let A=await f.getBalance({address:e}),N=Po[p.chainId]?.nativeCurrency.symbol??"ETH";return{network:_,symbol:N,amount:es(A,18)}}if(m.kind==="erc20"){let A=await Co(f,m.address,e);return{network:_,symbol:m.symbol,amount:es(A,m.decimals),address:m.address}}let h=await s(m.deposit),I=await i(m.deposit,h),E=await Co(f,h,e);return{network:_,symbol:I.symbol,amount:es(E,I.decimals),address:h}}}import Mo from"fs";import{p256 as ju}from"@noble/curves/p256";import{sha256 as Gu}from"@noble/hashes/sha2";import{formatRequestForAuthorizationSignature as Wu}from"@privy-io/node";import Vu from"crypto";function Oo(e,t){let n=Vu.createPrivateKey(t).export({format:"jwk"}),s=Buffer.from(n.d,"base64url"),i=ju.sign(Gu(typeof e=="string"?Buffer.from(e):e),s);return Buffer.from(i.toDERRawBytes()).toString("base64")}function ct(e,t,r,n,s){let i={version:1,method:"POST",url:`https://api.privy.io/v1/wallets/${e}/rpc`,body:t,headers:{"privy-app-id":n,...s}},o=Wu(i);return Oo(o,r)}function xr(e,t){return Oo(`${e}`,t)}async function Ce(e,t,r,n){let{wallet_address:s,sign_method:i,message:o}=e;if(!ye(s))throw new Error(`Wallet not found: ${s}`);let c=ae(s);if(!c)throw new Error("External wallet: signing must be done externally");let l=Q(t.keysDir,c.k_i_key_path);if(!Mo.existsSync(l))throw new Error(`Key file not found: ${l}`);let d=Mo.readFileSync(l),u=fe(d,r),m=u.toString("utf8");if(i==="personal_sign"&&typeof o!="string")throw ne(u),new Error("personal_sign requires a string message");if(i==="eth_signTypedData_v4"&&typeof o=="string")throw ne(u),new Error("eth_signTypedData_v4 requires a typed data object");let p=i==="personal_sign"?{method:"personal_sign",params:{encoding:"utf-8",message:o}}:{method:"eth_signTypedData_v4",params:{typed_data:{domain:o.domain,message:o.message,primary_type:o.primaryType,types:o.types}}},f=ct(c.wallet_id,p,m,t.privyAppId),{walletSignature:_}=await ho({signMethod:i,message:o,walletId:c.wallet_id,kISig:f},n);return ne(u),{wallet_signature:_}}import Uo from"fs";var Ju={1:"https://etherscan.io/tx",11155111:"https://sepolia.etherscan.io/tx",8453:"https://basescan.org/tx",84532:"https://sepolia.basescan.org/tx"};function Ku(e){let[t,r=""]=e.split("."),n=r.padEnd(18,"0").slice(0,18);return"0x"+(BigInt(t)*BigInt("1000000000000000000")+BigInt(n)).toString(16)}async function De(e,t,r){let{wallet_address:n,to:s,value_eth:i,chain_id:o,data:a,sponsor:c}=e,l=Ku(i),d=ye(n);if(!d)throw new Error(`Wallet not found: ${n}`);let u=ae(n);if(!u)throw new Error("External wallet: signing must be done externally");let m=Q(t.keysDir,u.k_i_key_path);if(!Uo.existsSync(m))throw new Error(`Key file not found: ${m}`);let p=Uo.readFileSync(m),f=fe(p,r),_=f.toString("utf8");try{let h=Date.now(),I=xr(h,_),E;try{E=await Tr({walletId:u.wallet_id,quorumId:u.quorum_id,kIPub:u.k_i_pub,timestamp:h,kISig:I})}catch(Vt){throw(Vt instanceof Error?Vt.message:String(Vt)).includes("HTTP 401")&&Ae(d.wallet_address,"Unauthorized (401)"),Vt}if(!E.valid)throw Ae(d.wallet_address,E.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${E.reason??"unknown reason"}`);let A={method:"eth_sendTransaction",caip2:`eip155:${o}`,params:{transaction:{to:s,value:l,...a?{data:a}:{}}},...c?{sponsor:!0}:{}},N=`${Date.now()}:${crypto.randomUUID()}`,C=ct(u.wallet_id,A,_,t.privyAppId,{"privy-idempotency-key":N}),U=await wo({walletId:u.wallet_id,caip2:`eip155:${o}`,transaction:{to:s,value:l,...a?{data:a}:{}},idempotencyKey:N,kISig:C,...c?{sponsor:!0}:{}}),re=U.transactionId?{transactionId:U.transactionId}:{};if(U.kind==="user_operation_hash")return{kind:"user_operation_hash",user_operation_hash:U.userOperationHash,...re};let js=U.txHash,Gs=Ju[o];return{kind:"tx_hash",tx_hash:js,...Gs?{explorer_url:`${Gs}/${js}`}:{},...re}}finally{ne(f)}}var Fo=300*1e3,Xu=async e=>{let t=R();b(t.dataDir);let r=gr();w({wallets:r.map(n=>({address:n.wallet_address,type:n.wallet_type,label:n.label,valid:n.last_valid===1,created_at:n.created_at,...n.wallet_type==="privy"?{wallet_id:ae(n.wallet_address)?.wallet_id}:{}}))})};function zu(e){let t,r;process.platform==="darwin"?(t="open",r=[e]):process.platform==="win32"?(t="cmd",r=["/c","start",'""',e]):(t="xdg-open",r=[e]);try{let n=Yu(t,r,{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var Qu=async e=>{let t=R();b(t.dataDir),O(t.appServerUrl);let r=e.includes("--force-new"),n=e.includes("--no-wait"),s=Buffer.from(t.passphrase,"utf8"),i;try{i=await Io(t,s,r)}catch(c){g({error:c.message}),process.exit(1)}if(n){w(i);return}if(i.status==="ready"){w(i);return}let o=i.auth_url;process.stderr.write(`Open this URL to authenticate:
402
- ${o}
403
-
404
- `),zu(o),process.stderr.write(`Waiting for authentication to complete (up to 5 minutes)\u2026
405
- `);let a;try{a=await Vn(t,{waitMs:Fo})}catch(c){g({error:c.message}),process.exit(1)}if(w(a),a.status==="ready"){process.stderr.write(`Wallet registered: ${a.wallet_address}
406
- `);return}a.status==="failed"&&(process.stderr.write(`Authentication failed: ${a.reason}
407
- `),process.exit(1)),a.status==="pending"&&(process.stderr.write("Timeout reached \u2014 re-run `amb wallet-setup` to resume.\n"),process.exit(1)),process.stderr.write("No pending session found \u2014 re-run `amb wallet-setup`.\n"),process.exit(1)},Zu=async e=>{let t=R();b(t.dataDir),O(t.appServerUrl);let r=e.includes("--wait")?Fo:0;try{let n=await Vn(t,{waitMs:r});w(n)}catch(n){g({error:n.message}),process.exit(1)}},ep=async e=>{let[t,r]=e;t||(console.error("error: Usage: amb wallet-add-external <wallet_address> [label]"),process.exit(1));let n=R();b(n.dataDir),qi({wallet_address:t,label:r}),w({status:"registered",wallet_address:t,label:r??null})},tp=async e=>{let[t]=e;t||(console.error("error: Usage: amb wallet-balance <wallet_address>"),process.exit(1));let r=R();b(r.dataDir),k(t);try{let n=await Lo(t,r);w({wallet_address:t,...n})}catch(n){g({error:"RPC_ERROR",message:`Failed to fetch balance: ${n.message}`}),process.exit(1)}},rp=async e=>{let[t,r,n]=e;(!t||!r||!n)&&(console.error("error: Usage: amb wallet-sign <wallet_address> <sign_method> <siwe_file|json>"),console.error("hint: sign_method: personal_sign (SIWE login), eth_signTypedData_v4 (payment/tip)"),console.error(" SIWE: amb wallet-sign 0x... personal_sign /path/to/siwe-file.json"),console.error(` Payment: amb wallet-sign 0x... eth_signTypedData_v4 '{"types":...}'`),process.exit(1));let s=R();b(s.dataDir),k(t),O(s.appServerUrl);let i=Buffer.from(s.passphrase,"utf8"),o;if(r==="personal_sign")if(Bo.existsSync(n)){let{message:a,expiresAt:c}=JSON.parse(Bo.readFileSync(n,"utf8"));Date.now()/1e3>c&&(g({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1)),o=a}else o=n.replace(/\\n/g,`
408
- `);else try{o=JSON.parse(n)}catch{g({error:"eth_signTypedData_v4 requires valid JSON typed data"}),process.exit(1)}try{let a=await Ce({wallet_address:t,sign_method:r,message:o},s,i);w(a)}catch(a){g({error:a.message}),process.exit(1)}},np=async e=>{let[t,r,n,s,i]=e;(!t||!r||!n||!s)&&(console.error("error: Usage: amb wallet-send-tx <wallet_address> <to> <value_eth> <chain_id> [data]"),console.error("hint: chain_id: 84532 (BASE_SEPOLIA), 11155111 (ETH_SEPOLIA)"),process.exit(1));let o=R();b(o.dataDir),k(t),O(o.appServerUrl);let a=Buffer.from(o.passphrase,"utf8");try{let c=await De({wallet_address:t,to:r,value_eth:n,chain_id:parseInt(s,10),data:i},o,a);w(c)}catch(c){g({error:c.message}),process.exit(1)}},$o={"wallet-status":Xu,"wallet-setup":Qu,"wallet-setup-verify":Zu,"wallet-add-external":ep,"wallet-balance":tp,"wallet-sign":rp,"wallet-send-tx":np};import{encodeFunctionData as Dp,formatUnits as Pp}from"viem";import Ho from"fs";import sp from"crypto";function ip(e){let[t,r=""]=e.split("."),n=r.padEnd(18,"0").slice(0,18);return"0x"+(BigInt(t)*BigInt("1000000000000000000")+BigInt(n)).toString(16)}async function vr(e,t,r){let{wallet_address:n,chain_id:s,calls:i,sponsor:o}=e,a=ye(n);if(!a)throw new Error(`Wallet not found: ${n}`);let c=ae(n);if(!c)throw new Error("External wallet: signing must be done externally");let l=Q(t.keysDir,c.k_i_key_path);if(!Ho.existsSync(l))throw new Error(`Key file not found: ${l}`);let d=Ho.readFileSync(l),u=fe(d,r),m=u.toString("utf8");try{let p=Date.now(),f=xr(p,m),_;try{_=await Tr({walletId:c.wallet_id,quorumId:c.quorum_id,kIPub:c.k_i_pub,timestamp:p,kISig:f})}catch(C){throw(C instanceof Error?C.message:String(C)).includes("HTTP 401")&&Ae(a.wallet_address,"Unauthorized (401)"),C}if(!_.valid)throw Ae(a.wallet_address,_.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${_.reason??"unknown reason"}`);let h=i.map(C=>({to:C.to,value:ip(C.value_eth),...C.data?{data:C.data}:{}})),I={method:"wallet_sendCalls",caip2:`eip155:${s}`,chain_type:"ethereum",...o?{sponsor:!0}:{},params:{calls:h}},E=`${Date.now()}:${sp.randomUUID()}`,A=ct(c.wallet_id,I,m,t.privyAppId,{"privy-idempotency-key":E}),N=await Eo({walletId:c.wallet_id,caip2:`eip155:${s}`,calls:h,idempotencyKey:E,kISig:A,...o?{sponsor:!0}:{}});return{kind:"transaction_id",transaction_id:N.transactionId,caip2:N.caip2}}finally{ne(u)}}import bp from"crypto";import{createSiweMessage as op,parseSiweMessage as ap}from"viem/siwe";var cp=60;async function Nr(e,t,r){let n=await Ro({walletAddress:e,chainId:t},r),s=op({domain:n.domain,address:e,uri:n.uri,version:n.version,chainId:n.chainId,nonce:n.nonce,issuedAt:new Date(n.issuedAt),expirationTime:new Date(n.expirationTime),...n.scheme?{scheme:n.scheme}:{}}),i=Math.floor(new Date(n.expirationTime).getTime()/1e3);return{message:s,expiresAt:i}}async function kr(e,t,r){let n=ap(e),s=Math.floor(Date.now()/1e3),i=n.address,{flag:o}=await Ao(i,r),a=o?await bo({message:e,signature:t},r):await To({message:e,signature:t},r),{accessToken:c,expiresIn:l}=a,d=s+l-cp;return Ji(n.address,c,d),oe(`[jwt-debug] SET cache_key=${n.address} expires_at=${d} now=${s} expiresIn=${l} pid=${process.pid}
409
- `),{accessToken:c,expiresIn:l}}function j(e){return P(e)}import{hashTypedData as lp,parseSignature as dp,concat as up,toHex as pp,keccak256 as mp,toBytes as gp}from"viem";var pE=mp(gp("Kernel(bytes32 hash)"));function Cr(e){return lp(e)}function Dr(e){let{kernelDomain:t,innerDigest:r}=e;return{domain:{name:t.name,version:t.version,chainId:t.chainId,verifyingContract:t.verifyingContract},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Kernel:[{name:"hash",type:"bytes32"}]},primaryType:"Kernel",message:{hash:r}}}function Pr(e){let{r:t,s:r,yParity:n}=dp(e),s=BigInt(r)|BigInt(n)<<255n;return up(["0x00",t,pp(s,{size:32})])}async function qo(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/price-quote`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return await n.json();let s="";try{let i=await n.json();(i.code||i.message)&&(s=`${i.code??""} ${i.message??""}`.trim())}catch{}throw s||(s=await n.text().catch(()=>"")||`HTTP ${n.status}`),new Error(`POST /price-quote failed (${n.status}): ${s}`)}import{createPublicClient as fp,http as _p,parseAbi as yp,BaseError as hp,ContractFunctionZeroDataError as wp,ContractFunctionRevertedError as Ep}from"viem";var Rp=yp(["function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)"]);function ts(e){return fp({transport:_p(e.rpcUrl)})}async function jo(e){return ts(e).getChainId()}async function Lr(e,t){let r=await ts(e).getCode({address:t});return!!r&&r!=="0x"}async function Or(e,t){let r=t;try{let n=await ts(e).readContract({address:r,abi:Rp,functionName:"eip712Domain"});return{name:n[1],version:n[2],chainId:Number(n[3]),verifyingContract:r}}catch(n){if(!(n instanceof hp&&!!n.walk(i=>i instanceof wp||i instanceof Ep)))throw n;return{name:"Kernel",version:"0.3.3",chainId:e.chainId,verifyingContract:r}}}function Tp(e){let{capability:t,params:r}=e;return{domain:{name:t.domainName,version:t.domainVersion,chainId:t.chainId,verifyingContract:t.tokenAddress},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],ReceiveWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"ReceiveWithAuthorization",message:{from:r.from,to:r.to,value:r.value,validAfter:r.validAfter,validBefore:r.validBefore,nonce:r.nonce}}}function Sp(e,t,r){let n=r.toLowerCase();return e.find(s=>s.network===t&&s.tokenAddress.toLowerCase()===n)}function Ap(e){return Math.floor(Date.now()/1e3)+e+60}function Ip(){return"0x"+bp.randomBytes(32).toString("hex")}async function xp(e,t){try{let r=await fetch(`${t.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay-capabilities`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return r.ok?await r.json():null}catch{return null}}async function vp(e){let{typedData:t,isSmartAccount:r,kernelDomain:n,walletSigner:s,config:i,passphrase:o,agent:a}=e;if(r){if(!n)throw new Error("KERNEL_DOMAIN_REQUIRED: smart-account agent needs a Kernel domain");let l=Cr(t),d=Dr({kernelDomain:n,innerDigest:l}),{wallet_signature:u}=await s({wallet_address:a,sign_method:"eth_signTypedData_v4",message:d},i,o);return Pr(u)}let{wallet_signature:c}=await s({wallet_address:a,sign_method:"eth_signTypedData_v4",message:t},i,o);return c}async function Np(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return await n.json();let s="";try{let i=await n.json();(i.code||i.message)&&(s=`${i.code??""} ${i.message??""}`.trim())}catch{}throw s||(s=await n.text().catch(()=>"")||`HTTP ${n.status}`),new Error(`POST /relay failed (${n.status}): ${s}`)}function rs(e){return{request_id:e.requestId,status:e.status,tx_hash:e.txHash,error_code:e.errorCode,error_message:e.errorMessage}}async function Mr(e,t,r){let n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay/${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(n.ok)return await n.json();let s=await n.text().catch(()=>"");throw new Error(`GET /relay/${t} failed (${n.status}): ${s||"no body"}`)}function Go(e){return e!=null&&"unavailable"in e}async function kp(e){let{params:t,network:r,config:n,passphrase:s,jwtProvider:i,capabilitiesFetcher:o,priceQuoteFetcher:a,smartAccountProbe:c,walletSigner:l,relaySubmitter:d}=e,u=i(t.wallet_address);if(!u)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");let m=await o(u,n);if(!m)return{unavailable:"PROBE_FAILED"};let p=Sp(m.capabilities,r.name,t.token);if(!p)return{unavailable:"NO_CAPABILITY"};if(p.preferred==="PERMIT")throw new Error("PERMIT_NOT_IMPLEMENTED: relay capability is PERMIT-only; v2 supports AUTHORIZATION only");let f=await a(u,{network:r.name,tokenAddress:t.token,tokenAmount:t.amount},n),_={from:t.wallet_address,to:p.depositContractAddress,value:t.amount,validAfter:"0",validBefore:Ap(m.deadlineMinBufferSec).toString(),nonce:Ip()},h=Tp({capability:p,params:_}),{isSmartAccount:I,kernelDomain:E}=await c(r,t.wallet_address),A=await vp({typedData:h,agent:t.wallet_address,isSmartAccount:I,kernelDomain:E,walletSigner:l,config:n,passphrase:s}),N=await d(u,{network:r.name,tokenAddress:t.token,params:{..._,quote:{mvlAmount:f.quote.mvlAmount,nonce:f.quote.nonce,timestamp:f.quote.timestamp,deadline:f.quote.deadline},quoteSignature:f.signature},signature:A},n);return{path:"relay",request_id:N.requestId,status:N.status,mvl_amount:f.quote.mvlAmount,tx_hash:N.txHash,error_code:N.errorCode,error_message:N.errorMessage,next_step:`Run \`amb deposit-relay-status ${t.wallet_address} ${N.requestId}\` until status is CONFIRMED or FAILED`}}var Cp=new Set(["CONFIRMED","FAILED"]);async function Wo(e,t,r,n={}){let s=n.intervalMs??3e3,i=n.timeoutMs??12e4,o=Date.now()+i,a=await Mr(e,t,r);for(;!Cp.has(a.status)&&Date.now()<o;)await new Promise(c=>setTimeout(c,s)),a=await Mr(e,t,r);return a}function Vo(e){return kp({...e,jwtProvider:j,capabilitiesFetcher:xp,priceQuoteFetcher:qo,smartAccountProbe:async(t,r)=>{let n=await Lr(t,r);return{isSmartAccount:n,kernelDomain:n?await Or(t,r):void 0}},walletSigner:Ce,relaySubmitter:Np})}async function Jo(e,t,r,n){let s=await Ke(t);if(e.token.toLowerCase()!==s.toLowerCase()){let a=await Vo({params:e,network:t,config:r,passphrase:n});if(Go(a))throw new Error(a.unavailable==="NO_CAPABILITY"?`TOKEN_NOT_DEPOSITABLE: the deposit relay has no capability for token ${e.token} on ${t.name}, so it cannot be deposited as collateral. MVL (${s}) is always accepted and needs no relay. Run \`amb deposit-tokens ${t.name}\` for the current list. Retrying will not help.`:`RELAY_UNAVAILABLE: the agent-deposit relay could not be reached for ${t.name}, so token ${e.token} cannot be deposited right now. Check the cached JWT and the gateway, then retry. Depositing MVL (${s}) directly needs no relay.`);return a}let i=BigInt(e.amount),o=await vr({wallet_address:e.wallet_address,chain_id:t.chainId,sponsor:!0,calls:[{to:e.token,value_eth:"0",data:Kn(t.depositContract,i)},{to:t.depositContract,value_eth:"0",data:Yn(e.wallet_address,i)}]},r,n);return{path:"mvl-direct",token:e.token,agent:e.wallet_address,amount:e.amount,batch_tx:o}}async function Ko(e,t,r,n){let s=await Ir(t,e.wallet_address),i=BigInt(Math.floor(Date.now()/1e3));if(s>i){let a=Number(s-i),c=Math.ceil(a/60);throw new Error(`WITHDRAW_COOLDOWN: next withdraw allowed at unix ${s.toString()} (~${c} min from now). v2 enforces a per-agent withdraw cooldown.`)}let o=await De({wallet_address:e.wallet_address,to:t.depositContract,value_eth:"0",chain_id:t.chainId,data:Xn(),sponsor:!0},r,n);return{path:"mvl-withdraw",agent:e.wallet_address,withdraw_tx:o}}function Yo(e,t,r){if(e<0n)throw new Error("requiredTokenWei: gapMvl must be >= 0");if(r<=0n)throw new Error("requiredTokenWei: mvlAmount must be > 0");return(e*t+r-1n)/r}function Xo(e,t){let r=10n**BigInt(t),n=(e*100n+r-1n)/r,s=n/100n,i=n%100n;return`${s.toString()}.${i.toString().padStart(2,"0")}`}async function zo(e,t,r){let n=r.gatewayServerUrl.replace(/\/$/,""),s=`network=${encodeURIComponent(t.network)}&tokenAddress=${encodeURIComponent(t.tokenAddress)}`,i=await fetch(`${n}/v1/agent-deposit/exchange-rate?${s}`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(i.ok)return await i.json();let o="";try{let a=await i.json();(a.code||a.message)&&(o=`${a.code??""} ${a.message??""}`.trim())}catch{}throw o||(o=await i.text().catch(()=>"")||`HTTP ${i.status}`),new Error(`GET /exchange-rate failed (${i.status}): ${o}`)}var Qo="note: collateral is credited in MVL (not the deposited token); withdrawals return MVL.",Lp="note: withdrawals return MVL regardless of the token originally deposited.";function ea(e){let t=e.message,r=t.match(/^([A-Z][A-Z0-9_]+):\s*(.+)$/s);r?g({error:r[1],message:r[2]}):g({error:t})}var Op="run SIWE login (siwe-request-message then siwe-submit) to compute the token amount needed to activate";async function Mp(e,t,r,n){if(r===0n)return{entries:null,reason:null};let s=j(t);if(!s)return{entries:null,reason:"NO_JWT",hint:Op};try{let i=await zn(e);if(i.length===0)return{entries:null,reason:"RATE_UNAVAILABLE"};let a=(await Promise.allSettled(i.map(async c=>{let l=await Ye(e,c),d=await zo(s,{network:e.name,tokenAddress:c},n),u=Yo(r,BigInt(d.tokenAmount),BigInt(d.mvlAmount));return{tokenAddress:c,symbol:l.symbol,tokenWei:u.toString(),display:`~${Xo(u,l.decimals)} ${l.symbol} to activate`,ratePreview:d.ratePreview}}))).flatMap(c=>c.status==="fulfilled"?[c.value]:[]);return a.length===0?{entries:null,reason:"RATE_UNAVAILABLE"}:{entries:a,reason:null}}catch{return{entries:null,reason:"RATE_UNAVAILABLE"}}}var Up=async e=>{let[t]=e;t||(console.error("error: Usage: amb deposit-status <wallet_address>"),process.exit(1));let r=R();b(r.dataDir),k(t);try{let n=await Promise.allSettled(r.depositNetworks.map(async a=>{let[c,l,d,u,m]=await Promise.all([Ar(a,t),Sr(a,t),Ir(a,t),vt(a),ko(a)]),p=u>l?u-l:0n,f=null,_=null;if(p>0n)try{let A=await Ke(a),N=await Ye(a,A);f={tokenAddress:A,symbol:N.symbol,tokenWei:p.toString(),display:`${Pp(p,N.decimals)} ${N.symbol} to activate`}}catch(A){_=`MVL activation guidance unavailable: ${A.message}`}let h=await Mp(a,t,p,r),I=[...f?[f]:[],...h.entries??[]],E=I.length>0?I:null;return{mvlError:_,network:a.name,isActive:c,deposited:l.toString(),minRequired:u.toString(),nextWithdrawAt:Number(d),mvlReserve:m.toString(),mvlGap:p.toString(),requiredToActivate:E,requiredToActivateReason:h.reason,...h.hint?{requiredToActivateHint:h.hint}:{}}})),s=[],i=[];n.forEach((a,c)=>{if(a.status==="fulfilled"){let{mvlError:l,...d}=a.value;s.push(d),l&&i.push({network:d.network,error:l})}else i.push({network:r.depositNetworks[c].name,error:a.reason?.message})});let o=s.some(a=>a.isActive);w({anyActive:o,networks:s,errors:i})}catch(n){g({error:n.message}),process.exit(1)}},Bp=async e=>{let t=e.includes("--no-wait"),r=e.filter(d=>d!=="--no-wait"),[n,s,i,o]=r;if(!n||!s||!i||!o){console.error("error: Usage: amb deposit-add <wallet_address> <network> <token_address> <amount> [--no-wait]"),console.error('hint: amount is raw units (e.g. 1000 MVL = "1000000000000000000000")');let d=z().networks.depositNetworks;console.error(d.length?` network: ${d.join(", ")}`:" network: run `amb deposit-tokens` to see configured deposit networks"),console.error(" token: run `amb deposit-tokens <network>` for depositable token addresses"),process.exit(1)}let a=R();b(a.dataDir),k(n),O(a.appServerUrl);let c=a.depositNetworks.find(d=>d.name===s);c||(g({error:"UNKNOWN_NETWORK",message:`Network "${s}" not configured. Available: ${a.depositNetworks.map(d=>d.name).join(", ")}`}),process.exit(1));let l=Buffer.from(a.passphrase,"utf8");try{let d=await Jo({wallet_address:n,token:i,amount:o},c,a,l);if(d.path!=="relay"){w(d);return}if(t){let{next_step:p,...f}=d;if(d.status==="FAILED"){w(f),process.exit(2);return}w(d.status==="CONFIRMED"?f:d),console.error(Qo);return}let u=j(n);if(!u){g({error:"JWT_NOT_FOUND",request_id:d.request_id,message:"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first."}),process.exit(1);return}let m=await Wo(u,d.request_id,a);w({path:"relay",mvl_amount:d.mvl_amount,...rs(m)}),m.status==="FAILED"&&process.exit(2),console.error(Qo)}catch(d){ea(d),process.exit(1)}},Fp=async e=>{let t=e[0],r=R(),n=t?r.depositNetworks.filter(s=>s.name===t):r.depositNetworks;n.length===0&&(g({error:"UNKNOWN_NETWORK",message:`Network "${t}" not configured. Available: ${r.depositNetworks.map(s=>s.name).join(", ")}`}),process.exit(1));try{let s=await Promise.allSettled(n.map(async a=>{let c=[],l=await Ke(a),d=null;try{d=await Ye(a,l)}catch(_){c.push(`MVL metadata unavailable: ${_.message}`)}let[u,m]=await Promise.allSettled([zn(a),vt(a)]);u.status==="rejected"&&c.push(`convertible token list unavailable: ${u.reason?.message}`),m.status==="rejected"&&c.push(`minRequiredBalance unavailable: ${m.reason?.message}`);let p=await Promise.allSettled((u.status==="fulfilled"?u.value:[]).map(async _=>{let h=await Ye(a,_);return{token:_,symbol:h.symbol,name:h.name,decimals:h.decimals}})),f=[];return p.forEach((_,h)=>{if(_.status==="fulfilled")f.push(_.value);else{let I=u.status==="fulfilled"?u.value[h]:"(unknown)";c.push(`token ${I} metadata unavailable: ${_.reason?.message}`)}}),{scopedErrors:c,network:a.name,tokens:[{token:l,symbol:d?.symbol??null,name:d?.name??null,decimals:d?.decimals??null},...f],minRequiredMvl:m.status==="fulfilled"?m.value.toString():null}})),i=[],o=[];s.forEach((a,c)=>{if(a.status==="fulfilled"){let{scopedErrors:l,...d}=a.value;i.push(d);for(let u of l)o.push({network:d.network,error:u})}else o.push({network:n[c].name,error:a.reason?.message})}),w({networks:i,errors:o})}catch(s){g({error:s.message}),process.exit(1)}},$p=async e=>{let[t,r,n]=e;(!t||!r)&&(console.error("error: Usage: amb deposit-withdraw <wallet_address> <network>"),console.error("hint: v2 withdraws the full MVL ledger balance \u2014 no token arg needed."),console.error(" Subject to a per-agent withdraw cooldown enforced by the ledger."),process.exit(1)),n&&console.error(`warning: <token> positional argument ("${n}") is no longer used. v2 withdraws all MVL via router.withdraw(). Drop the token arg: \`amb deposit-withdraw <wallet_address> <network>\``);let s=R();b(s.dataDir),k(t),O(s.appServerUrl);let i=s.depositNetworks.find(a=>a.name===r);i||(g({error:"UNKNOWN_NETWORK",message:`Network "${r}" not configured. Available: ${s.depositNetworks.map(a=>a.name).join(", ")}`}),process.exit(1));let o=Buffer.from(s.passphrase,"utf8");try{let a=await Ko({wallet_address:t},i,s,o);w(a),console.error(Lp)}catch(a){ea(a),process.exit(1)}},Hp="0xfd0Bf71F60660E2f608ed56e1659C450eB113120",qp=11155111,Zo=2e5,jp=async e=>{let[t,r,n]=e;(!t||!r)&&(console.error("error: Usage: amb bridge-deposit-eth <wallet_address> <value_eth> [recipient]"),console.error("hint: omit recipient to bridge to the same address on L2"),process.exit(1));let s=n??t,i=Dp({abi:[{name:"depositETHTo",type:"function",stateMutability:"payable",inputs:[{name:"_to",type:"address"},{name:"_minGasLimit",type:"uint32"},{name:"_extraData",type:"bytes"}],outputs:[]}],functionName:"depositETHTo",args:[s,Zo,"0x"]}),o=R();b(o.dataDir),k(t),O(o.appServerUrl);let a=Buffer.from(o.passphrase,"utf8");try{let c=await De({wallet_address:t,to:Hp,value_eth:r,chain_id:qp,data:i},o,a);w({...c,l2_recipient:s,min_gas_limit:Zo})}catch(c){g({error:c.message}),process.exit(1)}},Gp=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb deposit-relay-status <wallet_address> <request_id>"),console.error('hint: <request_id> is from the deposit-add response when path="relay"'),process.exit(1));let n=R();b(n.dataDir);let s=j(t);s||(g({error:"JWT_NOT_FOUND",message:"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first."}),process.exit(1));try{let i=await Mr(s,r,n);w(rs(i)),i.status==="FAILED"&&process.exit(2)}catch(i){g({error:i.message}),process.exit(1)}},ta={"deposit-status":Up,"deposit-add":Bp,"deposit-tokens":Fp,"deposit-withdraw":$p,"deposit-relay-status":Gp,"bridge-deposit-eth":jp};import{createPublicClient as Em,http as Rm,formatUnits as bm}from"viem";import{base as Tm,baseSepolia as Sm,mainnet as Am,sepolia as Im}from"viem/chains";import{randomUUID as Wp}from"crypto";var Vp=["INITIATED","BURN_SUBMITTED","ATTESTED","MINT_SUBMITTED","COMPLETED","FAILED"],Pe=["COMPLETED","FAILED"],pR=Vp.filter(e=>!Pe.includes(e)),ra=Pe.map(()=>"?").join(","),Jp={status:"status",fromBlock:"from_block",burnPrivyTxId:"burn_privy_tx_id",burnTxHash:"burn_tx_hash",relayRequestId:"relay_request_id",cctpNonce:"cctp_nonce",message:"message",attestation:"attestation",mintPrivyTxId:"mint_privy_tx_id",mintTxHash:"mint_tx_hash",mintFromBlock:"mint_from_block",mintAttempts:"mint_attempts",lastRevertSig:"last_revert_sig",mintedAmountRaw:"minted_amount_raw",failureReason:"failure_reason"};function ns(){return Math.floor(Date.now()/1e3)}function na(e){let t=T();return t.transaction(()=>{if(t.prepare(`
410
- SELECT id FROM bridge_jobs
411
- WHERE wallet_address = ? AND status NOT IN (${ra})
412
- LIMIT 1
413
- `).get(e.walletAddress,...Pe))throw new Error("BRIDGE_JOB_IN_FLIGHT");let n=Wp();return t.prepare(`
414
- INSERT INTO bridge_jobs (
415
- id, wallet_address, status, source_chain_id, dest_chain_id,
416
- amount_raw, is_fast, max_fee_raw, from_block, mint_from_block
417
- ) VALUES (@id, @walletAddress, 'INITIATED', @sourceChainId, @destChainId,
418
- @amountRaw, @isFast, @maxFeeRaw, @fromBlock, @mintFromBlock)
419
- `).run({id:n,walletAddress:e.walletAddress,sourceChainId:e.sourceChainId,destChainId:e.destChainId,amountRaw:e.amountRaw,isFast:e.isFast?1:0,maxFeeRaw:e.maxFeeRaw,fromBlock:e.fromBlock??null,mintFromBlock:e.mintFromBlock??null}),Le(n)})()}function Le(e){return T().prepare("SELECT * FROM bridge_jobs WHERE id = ?").get(e)}function sa(e){return T().prepare(`
420
- SELECT * FROM bridge_jobs
421
- WHERE wallet_address = ? AND status NOT IN (${ra})
422
- ORDER BY created_at DESC, rowid DESC LIMIT 1
423
- `).get(e,...Pe)}function ia(e,t=20){return T().prepare(`
424
- SELECT * FROM bridge_jobs WHERE wallet_address = ?
425
- ORDER BY created_at DESC, rowid DESC LIMIT ?
426
- `).all(e,t)}function ss(e,t){let r=Object.entries(t),n=[],s=[];for(let[i,o]of r){let a=Jp[i];if(!a)throw new Error(`updateJob: unknown field "${String(i)}"`);n.push(`${a} = ?`),s.push(o)}n.length!==0&&(n.push("updated_at = ?"),s.push(ns()),T().prepare(`UPDATE bridge_jobs SET ${n.join(", ")} WHERE id = ?`).run(...s,e))}function Ur(e,t,r=ns()){return T().prepare(`
427
- UPDATE bridge_jobs SET lease_expires_at = ?, updated_at = ?
428
- WHERE id = ? AND (lease_expires_at IS NULL OR lease_expires_at < ?)
429
- `).run(r+t,r,e,r).changes===1}function oa(e){T().prepare("UPDATE bridge_jobs SET lease_expires_at = NULL, updated_at = ? WHERE id = ?").run(ns(),e)}function lt(e){return T().prepare("SELECT * FROM bridge_fast_grants WHERE wallet_address = ?").get(e)}function aa(e,t){return T().prepare(`
430
- INSERT INTO bridge_fast_grants (wallet_address, max_fee_raw)
431
- VALUES (?, ?)
432
- ON CONFLICT(wallet_address) DO UPDATE SET
433
- max_fee_raw = excluded.max_fee_raw,
434
- granted_at = CURRENT_TIMESTAMP
435
- `).run(e,t),lt(e)}function ca(e){return T().prepare("DELETE FROM bridge_fast_grants WHERE wallet_address = ?").run(e).changes>0}function is(e,t){if(t===0n)return!0;let r=lt(e);return r?t<=BigInt(r.max_fee_raw):!1}import{encodeFunctionData as as,decodeEventLog as Yp,pad as ma}from"viem";import{parseAbi as os,parseAbiItem as Kp}from"viem";var la=os(["function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold)"]),da=os(["function receiveMessage(bytes message, bytes attestation) returns (bool)"]),ua=os(["function approve(address spender, uint256 amount) returns (bool)"]),pa=Kp("event MintAndWithdraw(address indexed mintRecipient, uint256 amount, address indexed mintToken, uint256 feeCollected)");function ga(e){return as({abi:la,functionName:"depositForBurn",args:[e.amount,e.destinationDomain,ma(e.mintRecipient,{size:32}),e.burnToken,ma("0x",{size:32}),e.maxFee,e.minFinalityThreshold]})}function fa(e,t){return as({abi:da,functionName:"receiveMessage",args:[e,t]})}function _a(e,t){return as({abi:ua,functionName:"approve",args:[e,t]})}function Br(e,t,r){let n=t.toLowerCase(),s=r.toLowerCase();for(let i of e.logs??[]){if(i.address?.toLowerCase()!==n)continue;let o;try{o=Yp({abi:[pa],data:i.data,topics:i.topics})}catch{continue}let a=o.args;if(a.mintRecipient?.toLowerCase()===s)return{amountRaw:a.amount,feeCollectedRaw:a.feeCollected}}return null}var ha="Run `amb bridge-usdc <wallet>` to resume",Xp={status:"status",fromBlock:"from_block",burnPrivyTxId:"burn_privy_tx_id",burnTxHash:"burn_tx_hash",cctpNonce:"cctp_nonce",message:"message",attestation:"attestation",mintPrivyTxId:"mint_privy_tx_id",mintTxHash:"mint_tx_hash",mintFromBlock:"mint_from_block",mintAttempts:"mint_attempts",lastRevertSig:"last_revert_sig",mintedAmountRaw:"minted_amount_raw",failureReason:"failure_reason"};function se(e,t){ss(e.id,t);let r={...e};for(let[n,s]of Object.entries(t)){let i=Xp[n];i&&(r[i]=s)}return r}function Fr(e,t,r=!1){return se(e,{status:"FAILED",failureReason:t}),{status:"FAILED",...r?{fundsMidFlight:!0}:{}}}function pe(e,t,r={}){return{status:e,nextStep:ha,...t?.note?{note:t.note}:{},...t?.privyStatus?{privyStatus:t.privyStatus}:{},...r}}function wa(e,t){let r=BigInt(e.amount_raw);return t>=r&&t<=r+BigInt(e.max_fee_raw)}function Xe(e,t,r){return se(e,{status:"COMPLETED",mintedAmountRaw:t}),{status:"COMPLETED",mintedAmountRaw:t,...r?{note:r}:{}}}function cs(e){return`Your USDC arrived \u2014 the CCTP message for this transfer is redeemed on the destination chain \u2014 but the exact credited amount could not be read from the logs. Run \`amb wallet-balance ${e}\` to see the balance.`}async function Nt(e,t){let r=BigInt(e.mint_from_block??e.from_block??"0"),n=await t.scanMintLogs(r,e.wallet_address);return n&&wa(e,BigInt(n.amountRaw))?n.amountRaw:null}async function Ea(e,t){if(!e.cctp_nonce)return!1;try{return await t.isNonceUsed(e.cctp_nonce)}catch{return!1}}async function Ra(e,t){if(BigInt(e.max_fee_raw)===0n)return{amountRaw:e.amount_raw};let r=await Nt(e,t);return r?{amountRaw:r}:{amountRaw:null,note:cs(e.wallet_address)}}function ba(e){let t=e instanceof Error?e.message:String(e);return/already used|nonce already/i.test(t)}async function zp(e,t,r){let n=await Nt(e,t);if(n)return Xe(e,n);let s=Le(e.id)??e,i=s.last_revert_sig===r?s.mint_attempts+1:1,o=se(e,{mintAttempts:i,lastRevertSig:r});if(i>=t.mintMaxAttempts)return Fr(o,`receiveMessage reverted ${i} times with the same signature (${r}). The burn already moved your USDC, so the funds are mid-flight and this job needs the \xA74.3 last-resort recovery: share \`amb bridge-usdc-status\` output with support.`,!0);try{let a=await t.sendMint(o);return o=se(o,{status:"MINT_SUBMITTED",mintPrivyTxId:a.transactionId,mintTxHash:null}),pe("MINT_SUBMITTED")}catch(a){if(ba(a)){let c=await Nt(o,t);if(c)return Xe(o,c)}throw a}}var ya=new Set;function Qp(e){return Pe.includes(e)}async function Ta(e,t){let r=`${e.id}:${e.burn_tx_hash??""}`;if(ya.has(r))return e;ya.add(r);try{let n=await t.registerRelay(e);if(n&&!e.relay_request_id)return ss(e.id,{relayRequestId:n}),Le(e.id)??e}catch{}return e}var J=e=>({advanced:!1,result:e}),$r=e=>({advanced:!0,job:e});async function Zp(e,t){if(e.burn_privy_tx_id){let o=await t.resolveTxStatus(e.burn_privy_tx_id);return o.kind==="FAILED"?J(Fr(e,`burn transaction failed (${o.privyStatus??"reverted"}); no USDC was burned`)):o.kind==="REPLACED"?(o.hash&&se(e,{burnTxHash:o.hash}),J(pe("INITIATED",o,{note:`burn transaction was replaced (nonce replacement); now tracking ${o.hash}`}))):o.kind==="SUCCESS"&&o.hash?$r(se(e,{status:"BURN_SUBMITTED",burnTxHash:o.hash})):J(pe("INITIATED",o))}let r=BigInt(e.from_block??"0"),n=await t.currentBlock(),s=await t.scanBurnLogs(r,n,e.wallet_address);if(s)return $r(se(e,{status:"BURN_SUBMITTED",burnTxHash:s.hash}));let i=n-r;return i<BigInt(t.graceBlocks)?J({status:"INITIATED",verdictWithheld:!0,nextStep:ha,note:`no DepositForBurn found yet, but only ${i} of ${t.graceBlocks} grace blocks have passed; withholding judgement`}):J(Fr(e,`no DepositForBurn from ${e.wallet_address} in ${i} blocks since block ${r}; the burn never went out`))}async function em(e,t){let r=e.burn_tx_hash;if(!r)return J(pe("BURN_SUBMITTED"));let n=await t.irisAttestation(e.source_chain_id,r);if(n&&n.attestation)return $r(se(e,{status:"ATTESTED",message:n.message,attestation:n.attestation,cctpNonce:n.nonce}));let s=n&&"delayReason"in n?n.delayReason:void 0,i=BigInt(e.from_block??"0");return await t.currentBlock()-i>=BigInt(t.graceBlocks)&&await t.getTransactionByHash(r)===null?J(Fr(e,`burn transaction ${r} is no longer on the canonical chain (suspected reorg) and Circle has issued no attestation; the burn did not stand, so no USDC was lost`)):J(pe("BURN_SUBMITTED",void 0,s?{note:`Circle has not attested the burn yet; Iris reports: ${s}`}:{}))}async function tm(e,t){if(await Ea(e,t)){let{amountRaw:n,note:s}=await Ra(e,t);return J(Xe(e,n,s))}let r=e.mint_from_block?e:se(e,{mintFromBlock:(await t.destBlock()).toString()});try{let n=await t.sendMint(r);return $r(se(r,{status:"MINT_SUBMITTED",mintPrivyTxId:n.transactionId,mintTxHash:null}))}catch(n){if(ba(n)){let s=await Nt(r,t);if(s)return J(Xe(r,s))}throw n}}async function rm(e,t){if(!e.mint_privy_tx_id)return J(pe("MINT_SUBMITTED"));let r=await t.resolveTxStatus(e.mint_privy_tx_id);if(r.kind==="FAILED")return J(await zp(e,t,r.privyStatus??"unknown_revert"));if(r.kind==="REPLACED")return r.hash&&se(e,{mintTxHash:r.hash}),J(pe("MINT_SUBMITTED",r,{note:`mint transaction was replaced (nonce replacement); now tracking ${r.hash}`}));if(r.kind!=="SUCCESS"||!r.hash)return J(pe("MINT_SUBMITTED",r));let n=se(e,{mintTxHash:r.hash}),s=await t.getReceipt(r.hash),i=s?Br(s,t.destTokenMessenger,n.wallet_address):null;if(i)return wa(n,i.amountRaw)?J(Xe(n,i.amountRaw.toString())):J(pe("MINT_SUBMITTED",void 0,{note:`MintAndWithdraw paid ${i.amountRaw} which is outside the expected range ${n.amount_raw}..${BigInt(n.amount_raw)+BigInt(n.max_fee_raw)}; not treating the job as complete`}));if(await Ea(n,t)){let{amountRaw:a,note:c}=await Ra(n,t);return J(Xe(n,a,c))}let o=await Nt(n,t);return J(o?Xe(n,o):pe("MINT_SUBMITTED",void 0,{note:`mint transaction ${r.hash} succeeded but no MintAndWithdraw for ${n.wallet_address} was found yet`}))}async function Sa(e,t){let r=await t.sendBurn(e),n=se(e,{burnPrivyTxId:r.transactionId});return n=await Ta(n,t),Hr(n,t)}async function Hr(e,t){let r=e;for(let n=0;n<nm;n++){r.burn_tx_hash&&!Qp(r.status)&&(r=await Ta(r,t));let s;switch(r.status){case"COMPLETED":return{status:"COMPLETED",mintedAmountRaw:r.minted_amount_raw};case"FAILED":return{status:"FAILED"};case"INITIATED":s=await Zp(r,t);break;case"BURN_SUBMITTED":s=await em(r,t);break;case"ATTESTED":s=await tm(r,t);break;case"MINT_SUBMITTED":s=await rm(r,t);break}if(!s.advanced)return s.result;r=s.job}return pe(r.status)}var nm=8;var sm=10000n;function Aa(e,t){return(e+t-1n)/t}function Ia(e,t,r,n){let s=r?1e3:2e3,i=e.find(a=>a.finalityThreshold===s);if(!i)throw new Error(`IRIS_FEE_MISSING: no fee entry for finalityThreshold ${s} (got: ${e.map(a=>a.finalityThreshold).join(", ")||"none"})`);let o=Aa(t*BigInt(i.minimumFee),sm);return Aa(o*BigInt(100+n),100n)}async function ls(e,t){let r=`${t.irisBaseUrl}/v2/burn/USDC/fees/${t.srcDomain}/${t.dstDomain}`,n=await e(r);if(!n.ok)throw new Error(`IRIS_FEE_QUERY_FAILED: ${n.status} from ${r}`);let s=await n.json();return Array.isArray(s)?s:[]}function im(e){return typeof e=="string"&&e.startsWith("0x")}function om(e,t){let r=e.decodedMessage?.destinationDomain;if(r!==void 0&&Number(r)!==t.destinationDomain)return!1;let n=e.decodedMessage?.decodedMessageBody?.amount;return!(n!==void 0&&BigInt(n)!==t.amountRaw)}async function xa(e,t){let r=`${t.irisBaseUrl}/v2/messages/${t.srcDomain}?transactionHash=${encodeURIComponent(t.transactionHash)}`,n=await e(r);if(n.status===404)return null;if(!n.ok)throw new Error(`IRIS_MESSAGE_QUERY_FAILED: ${n.status} from ${r}`);let i=(await n.json())?.messages;if(!Array.isArray(i)||i.length===0)return null;let o=i.find(a=>a.status==="complete"&&om(a,t)&&typeof a.message=="string"&&im(a.attestation));return o?{message:o.message,attestation:o.attestation,nonce:o.eventNonce??null}:null}import{decodeEventLog as am,parseAbiItem as cm,pad as lm}from"viem";var dm=cm("event DepositForBurn(address indexed burnToken, uint256 amount, address indexed depositor, bytes32 mintRecipient, uint32 destinationDomain, bytes32 destinationTokenMessenger, bytes32 destinationCaller, uint256 maxFee, uint32 indexed minFinalityThreshold, bytes hookData)"),va=128,Na=8,um=[/block range/i,/range is too large/i,/too many blocks/i,/query returned more than/i,/response size exceeded/i,/exceeds? (the )?max(imum)? (results|logs)/i];function pm(e){let t=e instanceof Error?e.message:String(e);return um.some(r=>r.test(t))}async function ka(e,t,r){let n=t.chunk??R().bridgeLogChunkBlocks,s=t.fromBlock,i=0;for(;s<=t.toBlock;){let o=s+BigInt(n)-1n;o>t.toBlock&&(o=t.toBlock);let a;try{a=await e({address:t.tokenMessenger,fromBlock:s,toBlock:o})}catch(l){if(!pm(l))throw l;if(++i>Na)throw new Error(`eth_getLogs range rejections are not converging after ${Na} halvings (blocks ${s}-${o})`);let d=Number(o-s+1n),u=Math.floor(d/2);if(u<va)throw new Error(`eth_getLogs still rejects the block range at the ${va}-block floor (blocks ${s}-${o}): ${l instanceof Error?l.message:String(l)}`);n=u;continue}i=0;let c=r(a);if(c!==null)return c;s=o+1n}return null}async function Ca(e,t,r,n){let s=t.tokenMessenger.toLowerCase(),i=r.toLowerCase(),o=lm(n.mintRecipient,{size:32}).toLowerCase();return ka(e,t,a=>{for(let c of a){if(c.address?.toLowerCase()!==s)continue;let l;try{l=am({abi:[dm],data:c.data,topics:c.topics})}catch{continue}let d=l.args;if(d.depositor?.toLowerCase()===i&&d.amount===n.amountRaw&&d.destinationDomain===n.destinationDomain&&d.mintRecipient?.toLowerCase()===o)return{transactionHash:c.transactionHash,blockNumber:BigInt(c.blockNumber),amountRaw:d.amount,mintRecipient:d.mintRecipient,destinationDomain:d.destinationDomain}}return null})}async function Da(e,t,r){return ka(e,t,n=>{for(let s of n){let i=Br({logs:[s]},t.tokenMessenger,r);if(i)return{transactionHash:s.transactionHash,blockNumber:BigInt(s.blockNumber),amountRaw:i.amountRaw,feeCollectedRaw:i.feeCollectedRaw}}return null})}var mm=["confirmed","finalized"],gm=["execution_reverted","failed","provider_error"],fm=["pending","broadcasted"];function _m(e){let t=e instanceof Error?e.message:String(e),r=/^HTTP (\d{3})\b/.exec(t);return r?Number(r[1]):void 0}async function Pa(e,t){let r;try{r=await e(t)}catch(i){let o=_m(i);if(o!==void 0&&o>=400&&o<500&&o!==404)throw i;return{kind:"PENDING",note:`transaction lookup did not resolve (${i instanceof Error?i.message:String(i)}); treating as still in flight`}}let n=r.transactionHash??void 0,s=n?{hash:n}:{};return mm.includes(r.status)?{kind:"SUCCESS",...s}:gm.includes(r.status)?{kind:"FAILED",...s}:fm.includes(r.status)?{kind:"PENDING",...s}:r.status==="replaced"?n?{kind:"REPLACED",hash:n}:{kind:"PENDING",privyStatus:"replaced",note:"Privy reported `replaced` with no transaction hash; re-querying on the next resume"}:{kind:"PENDING",privyStatus:r.status,...s,note:`unrecognised Privy status \`${r.status}\`; treating as still in flight`}}var La=[{type:"function",name:"usedNonces",stateMutability:"view",inputs:[{name:"nonce",type:"bytes32"}],outputs:[{name:"",type:"uint256"}]}];async function Oa(e,t,r){return await e(t,r)!==0n}function ym(e,t){return{walletAddress:e.wallet_address,...e.burn_privy_tx_id?{burnPrivyTxId:e.burn_privy_tx_id}:{},...e.burn_tx_hash?{burnTxHash:e.burn_tx_hash}:{},sourceNetwork:t.source.name,destNetwork:t.dest.name,srcDomain:t.source.cctpDomain,dstDomain:t.dest.cctpDomain,amountRaw:e.amount_raw,maxFeeRaw:e.max_fee_raw,isFast:e.is_fast===1}}async function Ma(e,t,r,n,s,i=1e4){let o=AbortSignal.timeout(i);async function a(){let d=await t(o);if(!d)return null;let u=await e(`${s.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-cctp-relay/relay-mint`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`},body:JSON.stringify(ym(r,n)),signal:o});if(!u.ok||!u.json)return null;let m=await u.json();return typeof m.requestId=="string"&&m.requestId.length>0?m.requestId:null}let c,l=new Promise(d=>{c=setTimeout(()=>d(null),i),c.unref?.()});try{return await Promise.race([a(),l])}catch{return null}finally{clearTimeout(c)}}var Fa=6,xm=5e3,vm=3*6e4,Nm=25*6e4,us=e=>`Run \`amb bridge-usdc ${e}\` to resume`,ps=e=>`note: this bridge is NOT finished (status ${e}). Your USDC has not arrived yet \u2014 do not report it as complete.`,qr=e=>`This bridge could not complete on its own and your USDC is mid-flight.
436
- Nothing is lost \u2014 it can be finished manually.
437
- Send the full output of \`amb bridge-usdc-status ${e}\` to support.`,km=/^\d+(\.\d{1,6})?$/;function kt(e){if(!km.test(e))throw new Error(`BRIDGE_AMOUNT_INVALID: "${e}" is not a decimal USDC amount. Expected digits with at most 6 decimal places (e.g. "50", "50.5"). No sign, no exponent, and no 7th decimal place \u2014 USDC has exactly 6, so a finer amount cannot be sent and is rejected rather than rounded.`);let[t,r=""]=e.split(".");return BigInt(t)*1000000n+BigInt(r.padEnd(Fa,"0"))}function G(e){return bm(e,Fa)}var Cm={1:Am,11155111:Im,8453:Tm,84532:Sm},Dm=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]}],Pm=(e,t)=>{let r=Em({chain:Cm[e],transport:Rm(t)});return{getBlockNumber:()=>r.getBlockNumber(),getReceipt:async n=>{try{return{logs:(await r.getTransactionReceipt({hash:n})).logs}}catch{return null}},getTransaction:async n=>{try{return{blockNumber:(await r.getTransaction({hash:n})).blockNumber??null}}catch{return null}},getLogs:async n=>(await r.getLogs({address:n.address,fromBlock:n.fromBlock,toBlock:n.toBlock})).map(i=>({address:i.address,topics:i.topics,data:i.data,blockNumber:`0x${(i.blockNumber??0n).toString(16)}`,transactionHash:i.transactionHash??""})),usedNonces:(n,s)=>r.readContract({address:n,abi:La,functionName:"usedNonces",args:[s]}),erc20Balance:(n,s)=>r.readContract({address:n,abi:Dm,functionName:"balanceOf",args:[s]})}},Ct=Pm;var dt={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};function ze(e){return e instanceof Error?e.message:String(e)}function $a(e){let t=/^HTTP (\d{3})\b/.exec(ze(e));return t?Number(t[1]):void 0}var Lm=1e3,Om=8e3,Mm=5;async function Ua(e){let t=Lm;for(let r=1;;r++)try{return await e()}catch(n){if($a(n)!==429||r>=Mm)throw n;await dt.sleep(t),t=Math.min(t*2,Om)}}function Um(e){let t=ze(e);return $a(e)===403?{error:"BRIDGE_SPONSOR_NOT_ALLOWED",message:`The gas sponsor rejected this batch (403). This is an operations problem, not yours: the CCTP approve/depositForBurn rules are not deployed to the sponsor allowlist for this environment. No USDC was burned. Report it \u2014 retrying will not help. Server said: ${t}`}:/Request expired/i.test(t)?{error:"BRIDGE_CLOCK_SKEW",message:"The server rejected the request as expired. The idempotency key is generated at call time, so the only cause is this machine's clock drifting more than 5 minutes from the server's. Synchronise the system clock (e.g. enable NTP) and run the command again. Retrying without fixing the clock fails identically, so it was not retried."}:null}function Bm(e,t,r){return async n=>{let s=j(e);if(s)return s;let{message:i}=await Nr(e,t.paymentChainId,n),{wallet_signature:o}=await Ce({wallet_address:e,sign_method:"personal_sign",message:i},t,r,n),{accessToken:a}=await kr(i,o,n);return a}}function ds(e,t,r,n){let{source:s,dest:i}=t,o=Ct(s.chainId,s.rpcUrl),a=Ct(i.chainId,i.rpcUrl),c=BigInt(r.amount_raw)+BigInt(r.max_fee_raw);return{irisFees:(l,d)=>ls(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:l,dstDomain:d}),irisAttestation:(l,d)=>xa(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:s.cctpDomain,transactionHash:d,destinationDomain:i.cctpDomain,amountRaw:c}),resolveTxStatus:l=>Pa(So,l),sendBurn:async l=>{let d=BigInt(l.amount_raw)+BigInt(l.max_fee_raw);return{transactionId:(await Ua(()=>vr({wallet_address:l.wallet_address,chain_id:s.chainId,sponsor:!0,calls:[{to:s.usdcAddress,value_eth:"0",data:_a(s.tokenMessengerV2,d)},{to:s.tokenMessengerV2,value_eth:"0",data:ga({amount:d,destinationDomain:i.cctpDomain,mintRecipient:l.wallet_address,burnToken:s.usdcAddress,maxFee:BigInt(l.max_fee_raw),minFinalityThreshold:l.is_fast?1e3:2e3})}]},e,n))).transaction_id}},sendMint:async l=>{let{message:d,attestation:u}=l;if(!d||!u)throw new Error("BRIDGE_NOT_ATTESTED: the job has no message/attestation to submit yet");let m=await Ua(()=>De({wallet_address:l.wallet_address,to:i.messageTransmitterV2,value_eth:"0",chain_id:i.chainId,sponsor:!0,data:fa(d,u)},e,n));if(!m.transactionId)throw new Error("BRIDGE_NO_TRANSACTION_ID: the mint was submitted but the server returned no transaction id");return{transactionId:m.transactionId}},getReceipt:l=>a.getReceipt(l),currentBlock:()=>o.getBlockNumber(),destBlock:()=>a.getBlockNumber(),scanBurnLogs:async(l,d,u)=>{let m=await Ca(p=>o.getLogs(p),{fromBlock:l,toBlock:d,tokenMessenger:s.tokenMessengerV2},u,{amountRaw:c,mintRecipient:r.wallet_address,destinationDomain:i.cctpDomain});return m?{hash:m.transactionHash}:null},scanMintLogs:async(l,d)=>{let u=await Da(m=>a.getLogs(m),{fromBlock:l,toBlock:await a.getBlockNumber(),tokenMessenger:i.tokenMessengerV2},d);return u?{amountRaw:u.amountRaw.toString()}:null},getTransactionByHash:l=>o.getTransaction(l),isNonceUsed:l=>Oa((d,u)=>a.usedNonces(d,u),i.messageTransmitterV2,l),registerRelay:l=>Ma(fetch,Bm(l.wallet_address,e,n),l,t,e),now:()=>Math.floor(dt.now()/1e3),destTokenMessenger:i.tokenMessengerV2,graceBlocks:e.bridgeBurnGraceBlocks,mintMaxAttempts:e.bridgeMintMaxAttempts}}function ms(e){return Pe.includes(e)}function jr(e){return e.status==="FAILED"&&!!e.burn_tx_hash&&!e.minted_amount_raw}function Fm(e){let t,r;switch(e.status){case"INITIATED":t="BURN_CONFIRMATION_PENDING",r=["ATTESTATION_PENDING","SERVER_MINT_PENDING","MINT_CONFIRMATION_PENDING"];break;case"BURN_SUBMITTED":t="ATTESTATION_PENDING",r=["SERVER_MINT_PENDING","MINT_CONFIRMATION_PENDING"];break;case"ATTESTED":t="SERVER_MINT_PENDING",r=["MINT_CONFIRMATION_PENDING"];break;case"MINT_SUBMITTED":t="MINT_CONFIRMATION_PENDING",r=[];break;case"COMPLETED":case"FAILED":return}return{status_class:"IN_PROGRESS",current_stage:t,remaining_stages:r,completion_mode:"SERVER_RELAY_WITH_CLI_FALLBACK",status_command:`amb bridge-usdc-status ${e.wallet_address} ${e.id}`,do_not_start_new_transfer:!0,user_action_required:"CHECK_STATUS_LATER"}}function Gr(e){let t=Fm(e);return{job_id:e.id,status:e.status,wallet_address:e.wallet_address,amount_usdc:G(BigInt(e.amount_raw)),amount_raw:e.amount_raw,max_fee_raw:e.max_fee_raw,is_fast:e.is_fast===1,source_chain_id:e.source_chain_id,dest_chain_id:e.dest_chain_id,...e.burn_tx_hash?{burn_tx_hash:e.burn_tx_hash}:{},...e.mint_tx_hash?{mint_tx_hash:e.mint_tx_hash}:{},...e.mint_attempts?{mint_attempts:e.mint_attempts}:{},...e.failure_reason?{failure_reason:e.failure_reason}:{},...e.status==="COMPLETED"?e.minted_amount_raw?{minted_amount:G(BigInt(e.minted_amount_raw)),minted_amount_raw:e.minted_amount_raw}:{minted_amount:null,minted_amount_raw:null,minted_amount_unknown:!0,minted_amount_note:cs(e.wallet_address)}:{},...jr(e)?{funds_mid_flight:!0,recovery:qr(e.wallet_address)}:{},...t?{agent_guidance:t}:{}}}function $m(e,t,r){let n=Le(e.id)??e,s=Gr(n),i=ms(n.status);if(w({...s,...t.verdictWithheld?{verdict_withheld:!0}:{},...t.note?{note:t.note}:{},...t.privyStatus?{privy_status:t.privyStatus}:{},...i?{}:{next_step:us(r)}}),!i){console.error(ps(n.status));return}n.status==="FAILED"&&((jr(n)||t.fundsMidFlight)&&console.error(qr(r)),process.exit(2))}async function Ha(e,t,r,n,s){let i=await ls(fetch,{irisBaseUrl:s.irisBaseUrl,srcDomain:s.source.cctpDomain,dstDomain:s.dest.cctpDomain}),o=Ia(i,t,r,n.bridgeMaxFeeBufferPct),a=t+o,l=await Ct(s.source.chainId,s.source.rpcUrl).erc20Balance(s.source.usdcAddress,e);return{amountRaw:t,maxFeeRaw:o,requiredRaw:a,sourceBalanceRaw:l,sufficient:l>=a}}var Hm=async e=>{let t=e.includes("--fast"),r=e.includes("--wait"),n=e.filter(d=>d!=="--fast"&&d!=="--wait"),[s,i]=n;if(!s){console.error("error: Usage: amb bridge-usdc <wallet_address> [amount] [--fast] [--wait]"),console.error('hint: amount is decimal USDC (e.g. "50", "50.5") \u2014 NOT raw units like deposit-add.'),console.error(" omit amount to resume an unfinished bridge (idempotent)."),process.exit(1);return}let o=R();if(!o.bridge){g({error:"BRIDGE_NOT_CONFIGURED",message:o.bridgeConfigError??"This build has no USDC bridge configured."}),process.exit(1);return}let a=o.bridge;b(o.dataDir),k(s),O(o.appServerUrl);let c=Buffer.from(o.passphrase,"utf8"),l;try{let d,u;if(i===void 0){let p=sa(s);if(!p){g({error:"BRIDGE_NO_ACTIVE_JOB",message:`No unfinished bridge for ${s}. Pass an amount to start one, or run \`amb bridge-usdc-status\` to see past jobs.`}),process.exit(1);return}if(!Ur(p.id,o.bridgeLeaseSec)){w({...Gr(p),lease_held:!0,next_step:us(s)}),console.error(ps(p.status)),console.error("note: another process is already advancing this bridge; nothing was submitted.");return}l=p.id,d=p,u=await Hr(d,ds(o,a,d,c))}else{let p=kt(i),f=kt(o.bridgeMinUsdc);if(p<f){g({error:"BRIDGE_AMOUNT_BELOW_MIN",message:`${G(p)} USDC is below the fixed ${o.bridgeMinUsdc} USDC bridge minimum. Nothing was submitted.`,amount_usdc:G(p),min_usdc:o.bridgeMinUsdc}),process.exit(1);return}let _=await Ha(s,p,t,o,a),h=_.maxFeeRaw;if(!_.sufficient){g({error:"BRIDGE_INSUFFICIENT_USDC",message:`${G(_.sourceBalanceRaw)} USDC on ${a.source.name} is short of the ${G(_.requiredRaw)} USDC this transfer needs`+(h>0n?` (${G(p)} to receive + ${G(h)} max fee)`:"")+". Nothing was submitted.",source:a.source.name,balance_usdc:G(_.sourceBalanceRaw),required_usdc:G(_.requiredRaw),required_raw:_.requiredRaw.toString()}),process.exit(1);return}if(!is(s,h)){let C=lt(s);g({error:"BRIDGE_FEE_NOT_AUTHORIZED",message:`This transfer's fee is ${G(h)} USDC`+(C?`, above the ${G(BigInt(C.max_fee_raw))} USDC ceiling approved for this wallet`:", and this wallet has no standing fee approval")+`. Nothing was submitted. Either approve it with \`amb bridge-fast-grant ${s} <max_fee_usdc>\`, or drop \`--fast\` to send it as a Standard transfer, which costs nothing.`,max_fee_usdc:G(h),max_fee_raw:h.toString(),grant_max_fee_usdc:C?G(BigInt(C.max_fee_raw)):null}),process.exit(1);return}let E=await Ct(a.source.chainId,a.source.rpcUrl).getBlockNumber(),N=await Ct(a.dest.chainId,a.dest.rpcUrl).getBlockNumber();d=na({walletAddress:s,sourceChainId:a.source.chainId,destChainId:a.dest.chainId,amountRaw:p.toString(),isFast:t,maxFeeRaw:h.toString(),fromBlock:E.toString(),mintFromBlock:N.toString()}),Ur(d.id,o.bridgeLeaseSec),l=d.id,u=await Sa(d,ds(o,a,d,c))}if(t||r){let p=t?vm:Nm,f=dt.now()+p;for(;!ms(u.status)&&dt.now()<f;){await dt.sleep(Math.min(xm,f-dt.now()));let _=Le(d.id);if(!_)break;Ur(_.id,o.bridgeLeaseSec),u=await Hr(_,ds(o,a,_,c))}}$m(d,u,s)}catch(d){let u=Um(d);if(u)g(u);else if(ze(d)==="BRIDGE_JOB_IN_FLIGHT")g({error:"BRIDGE_JOB_IN_FLIGHT",message:`A bridge is already running for ${s}. Run \`amb bridge-usdc ${s}\` (no amount) to resume it, or \`amb bridge-usdc-status ${s}\` to inspect it.`});else{let m=ze(d),p=m.match(/^([A-Z][A-Z0-9_]+):\s*(.+)$/s);p?g({error:p[1],message:p[2]}):g({error:m})}process.exit(1)}finally{l&&oa(l)}},qm=async e=>{let[t,r]=e;if(!t){console.error("error: Usage: amb bridge-usdc-status <wallet_address> [job_id]"),process.exit(1);return}let n=R();b(n.dataDir);try{if(r){let o=Le(r);if(!o||o.wallet_address.toLowerCase()!==t.toLowerCase()){g({error:"BRIDGE_JOB_NOT_FOUND",message:`No bridge job ${r} for ${t}.`}),process.exit(1);return}w(Gr(o)),jr(o)&&console.error(qr(t));return}let s=ia(t),i=s.find(o=>!ms(o.status));w({wallet_address:t,active_job_id:i?.id??null,jobs:s.map(Gr),...i?{next_step:us(t)}:{}}),i&&console.error(ps(i.status));for(let o of s)if(jr(o)){console.error(qr(t));break}}catch(s){g({error:ze(s)}),process.exit(1)}};function Ba(e){let t=lt(e);return{wallet_address:e,granted:!!t,max_fee_usdc:t?G(BigInt(t.max_fee_raw)):null,max_fee_raw:t?t.max_fee_raw:null,granted_at:t?t.granted_at:null}}var jm=async e=>{let t=e.includes("--fast"),r=e.filter(c=>c!=="--fast"),[n,s]=r;if(!n||!s){console.error("error: Usage: amb bridge-usdc-quote <wallet_address> <amount> [--fast]"),console.error('hint: amount is decimal USDC (e.g. "90") \u2014 NOT raw units like deposit-add.'),console.error(" Starts nothing: this is a pure read."),process.exit(1);return}let i=R();if(!i.bridge){g({error:"BRIDGE_NOT_CONFIGURED",message:i.bridgeConfigError??"This build has no USDC bridge configured."}),process.exit(1);return}let o=i.bridge;b(i.dataDir),k(n);let a;try{a=kt(s)}catch(c){g({error:"BRIDGE_AMOUNT_INVALID",message:ze(c).replace(/^BRIDGE_AMOUNT_INVALID:\s*/,"")}),process.exit(1);return}try{let c=await Ha(n,a,t,i,o),l=lt(n);w({wallet_address:n,amount_usdc:G(c.amountRaw),amount_raw:c.amountRaw.toString(),mode:t?"fast":"standard",max_fee_usdc:G(c.maxFeeRaw),max_fee_raw:c.maxFeeRaw.toString(),required_usdc:G(c.requiredRaw),source:o.source.name,source_balance_usdc:G(c.sourceBalanceRaw),sufficient:c.sufficient,below_min:a<kt(i.bridgeMinUsdc),min_usdc:i.bridgeMinUsdc,preauthorized:is(n,c.maxFeeRaw),grant_max_fee_usdc:l?G(BigInt(l.max_fee_raw)):null})}catch(c){g({error:ze(c)}),process.exit(1)}},Gm=async e=>{let t=e.includes("--revoke"),r=e.filter(o=>o!=="--revoke"),[n,s]=r;if(!n){console.error("error: Usage: amb bridge-fast-grant <wallet_address> [<max_fee_usdc> | --revoke]"),console.error("hint: no argument reads the current grant; an amount sets it; --revoke clears it."),console.error(' max_fee_usdc is decimal USDC (e.g. "0.1") \u2014 the per-transfer fee ceiling'),console.error(" below which a Fast bridge proceeds without asking about the fee."),process.exit(1);return}if(t&&s!==void 0){g({error:"BRIDGE_GRANT_INVALID",message:"--revoke takes no amount. Pass an amount to set the ceiling, or --revoke alone to clear it. Nothing was changed."}),process.exit(1);return}let i=R();if(b(i.dataDir),k(n),t){ca(n),w(Ba(n));return}if(s!==void 0){let o;try{o=kt(s)}catch{g({error:"BRIDGE_GRANT_INVALID",message:`"${s}" is not a decimal USDC amount. Expected digits with at most 6 decimal places (e.g. "0.1"). Nothing was stored.`}),process.exit(1);return}aa(n,o.toString())}w(Ba(n))},qa={"bridge-usdc":Hm,"bridge-usdc-status":qm,"bridge-usdc-quote":jm,"bridge-fast-grant":Gm};var Wm={POLYGON:"https://polygonscan.com",POLYGON_AMOY:"https://amoy.polygonscan.com",BASE:"https://basescan.org",BASE_SEPOLIA:"https://sepolia.basescan.org",ETHEREUM:"https://etherscan.io",ETHEREUM_SEPOLIA:"https://sepolia.etherscan.io"};function ut(e,t){if(!e||!t)return null;let r=Wm[e];return r?`${r}/tx/${t}`:null}var Dt;function H(e){Dt=e.replace(/\/$/,"")}async function he(e,t,r,n,s,i){let o={"Content-Type":"application/json",Authorization:`Bearer ${r}`,...i},a=s?`${Dt}${t}?${new URLSearchParams(s).toString()}`:`${Dt}${t}`,c=await fetch(a,{method:e,headers:o,body:n!==void 0?JSON.stringify(n):void 0});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`HTTP ${c.status} ${c.statusText} on ${e} ${t}: ${l}`)}return c.json()}async function ja(e,t,r){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`};r&&(n["payment-signature"]=r,n["x-signature-interpret-mode"]="general");let s=await fetch(`${Dt}/payment/ride`,{method:"POST",headers:n,body:JSON.stringify(t)});if(s.status===402){let o=s.headers.get("payment-required");if(!o)throw new Error("402 response missing payment-required header");let a=JSON.parse(Buffer.from(o,"base64").toString("utf-8"));return{status:402,accepts:a.accepts,nonce:a.nonce}}if(s.status===200||s.status===201){let o=s.headers.get("payment-response"),a=o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{network:"",payer:"",success:!0,transaction:""};return{status:s.status,paymentResponse:a}}let i=await s.text().catch(()=>"");throw new Error(`HTTP ${s.status} ${s.statusText} on POST /payment/ride: ${i}`)}function Ga(e,t){return he("GET","/v1/phone-verification/check",e,void 0,{phone:t})}function Wa(e,t){return he("POST","/v1/phone-verification/send-code",e,{phone:t})}function Va(e,t,r){return he("POST","/v1/phone-verification/confirm",e,{phone:t,code:r})}function Ja(e,t,r){return he("POST","/v2/rides/base-search",e,{region:t,locations:r})}function Ka(e,t){return he("POST","/v2/rides/pre-request",e,t)}function Ya(e,t){return ja(e,{rideRequestId:t,type:"RIDE"}).then(r=>{if(r.status!==402)throw new Error(`Expected 402 from payment probe, got ${r.status}`);return{accepts:r.accepts,nonce:r.nonce}})}function Xa(e,t,r){return ja(e,{rideRequestId:t,type:"RIDE"},r).then(n=>{if(n.status!==200&&n.status!==201)throw new Error(`Expected 200/201 from payment submit, got ${n.status}`);return n.paymentResponse})}var Pt={SIN:"SG",BKK:"TH",DEN:"CO",HCM:"VN",HAN:"VN",PNH:"KH",REP:"KH",SHV:"KH",KPK:"KH",SEL:"KR",ADD:"ET",JKT:"ID",HKG:"HK",NYC:"NY"},Vm={singapore:"SIN",bangkok:"BKK",denver:"DEN","ho chi minh":"HCM",saigon:"HCM",hcmc:"HCM",hanoi:"HAN","phnom penh":"PNH",sihanoukville:"SHV","siem reap":"REP",kampot:"KPK",seoul:"SEL","addis ababa":"ADD",jakarta:"JKT","hong kong":"HKG","new york":"NYC","new york city":"NYC",nyc:"NYC"};function Lt(e){let t=e.toUpperCase();return Pt[t]?t:Vm[e.toLowerCase()]}var Jm={SIN:{lat:1.3521,lng:103.8198},BKK:{lat:13.7563,lng:100.5018},DEN:{lat:39.7392,lng:-104.9903},HCM:{lat:10.8231,lng:106.6297},HAN:{lat:21.0285,lng:105.8542},PNH:{lat:11.5564,lng:104.9282},REP:{lat:13.3633,lng:103.8564},SHV:{lat:10.6097,lng:103.523},KPK:{lat:10.6099,lng:104.18},SEL:{lat:37.5665,lng:126.978},ADD:{lat:9.032,lng:38.7469},JKT:{lat:-6.2088,lng:106.8456},HKG:{lat:22.3193,lng:114.1694},NYC:{lat:40.7128,lng:-74.006}};function za(e,t,r,n,s){let i=Pt[r];if(!i)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);let o=Jm[r],a=n??o.lat,c=s??o.lng;return he("GET","/v2/places/autocomplete",e,void 0,{input:t,latitude:String(a),longitude:String(c)},{region:i})}function Qa(e,t,r){let n=Pt[r];if(!n)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);return he("GET",`/v1/places/${encodeURIComponent(t)}`,e,void 0,{region:n,city:r},{region:n})}function Ot(e,t){return he("GET",`/v1/rides/request/${t}`,e)}function Wr(e,t,r,n){let s={};return r&&(s.reason=r),n!=null&&(s.cancelReasonType=n),he("POST",`/v2/rides/request/${t}/cancel`,e,s)}async function Vr(e,t,r,n=20){let s={limit:String(n)};r&&(s.messageTs=r);let o=(await he("GET",`/v1/chat/${e}/messages`,t,void 0,s)).messages??[],a=o.length>0?o[o.length-1].createdAt:null;return{count:o.length,messages:o,next_cursor:a}}async function Jr(e,t,r,n){let s=new FormData,i=new Blob([new Uint8Array(r)],{type:n});s.append("image",i,"image");let o=await fetch(`${Dt}/v1/chat/${t}/image`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:s});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`HTTP ${o.status} ${o.statusText} on POST /v1/chat/${t}/image: ${a}`)}return o.json()}function Za(e,t){Yi(e,t,18e4)}function ec(e){return Xi(e)}function Kr(e,t){let r=t.expiresAt-Date.now();zi(e,t,r>0?r:6e5)}function Yr(e){let t=Qi(e);return t||null}var tc={12:"Ride Throo",14:"EV Throo"},rc={0:"Save Throo",1:"XL Throo",31:"EV Throo",13:"Premium Throo",4:"Premium XL Throo",4e4:"WAV Throo"};function Xr(e,t,r,n){return(e??"").toUpperCase()!=="NY"?n:t!==void 0&&t in tc?tc[t]:r!==void 0&&r in rc?rc[r]:n}function Km(e,t){return`${(t==="mi"?e/1609.344:e/1e3).toFixed(1)} ${t}`}function Ym(e){return`${Math.round(e/60)} min`}var nc=e=>typeof e=="number"&&Number.isFinite(e);function zr(e,t){return Array.isArray(e)?e.map(r=>{if(r==null||typeof r!="object")return r;let n=r,s={...n};return nc(n.distance)&&(s.distance_display=Km(n.distance,t)),nc(n.duration)&&(s.duration_display=Ym(n.duration)),s}):e}var Xm={minLat:15,maxLat:72,minLng:-168,maxLng:-52};function pt(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Invalid coordinate for region routing: lat=${e}, lng=${t}`);let r=Xm;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLng&&t<=r.maxLng?"US":"SG"}var zm=new Set(["NY"]);function we(e){return e&&zm.has(e.toUpperCase())?"US":"SG"}function Qr(e){return e==="US"?"mi":"km"}function ie(e,t,r){return(t??{})[e]??r}function ee(e,t){return ie("US",e,t)}function Qm(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function Zr(e){let t=Qm(e.wallet_address),r=await Ja(t,e.region,e.locations),n=JSON.stringify(r),s=r.checkSum;if(!s)throw new Error("product-search response missing checkSum field");Za(s,n);let i=r.products??[],o=[];for(let a of i){let l=(a.priceInfos??[]).find(d=>d.currencyId===e.payCurrency);if(l){let d=l.supportedCurrencyPriceInfo;o.push({product_id:a.id,product_code:a.code,product_name:Xr(e.region,a.productType,a.carType,a.title),pay_currency:e.payCurrency,price:d?.priceAfterDiscount??d?.price,price_currency:d?.currency})}}return{search_id:s,options:o,routes:zr(r.routes,Qr(we(e.region)))}}function sc(e){for(let t of e.locations){let r=t.googlePlaceId??t.placeId,n=st({placeId:r,latitude:t.latitude,longitude:t.longitude});if(!n){process.stderr.write(`[place-history] skip location (no placeId + invalid coords): name=${t.name}
438
- `);continue}uo({wallet_address:e.wallet_address,name:t.name,formatted_address:t.address,latitude:t.latitude,longitude:t.longitude,google_place_id:r??null,region:e.region,dedup_key:n,ts:e.ts})}}function Zm(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function en(e,t){let r=Zm(e.wallet_address),n=ec(e.search_id);if(!n)throw new Error("SEARCH_CACHE_MISS: search_id not found or expired. Call ride_search again.");let o=(JSON.parse(n).products??[]).find(p=>p.code===e.product_code);if(!o)throw new Error(`PRODUCT_NOT_FOUND: product_code ${e.product_code} not found in search result.`);let c=(o.priceInfos??[]).find(p=>p.currencyId===e.pay_currency);if(!c)throw new Error(`CURRENCY_NOT_FOUND: pay_currency ${e.pay_currency} not available for product ${e.product_code}.`);let l=c.walletProviderId,d=await Ka(r,{region:e.region,productCode:e.product_code,walletProviderId:l,payCurrency:e.pay_currency,locations:e.locations,rider:e.rider,baseSearchResponse:n,userWallet:{network:t.paymentNetwork,address:e.wallet_address,name:e.wallet_address}}),u=e.locations[0],m=e.locations[e.locations.length-1];Er({request_id:d.requestId,wallet_address:e.wallet_address,region:e.region,product_code:e.product_code,price:d.price,pay_currency:e.pay_currency,origin_name:u?.name,origin_addr:u?.address,origin_lat:u?.latitude,origin_lng:u?.longitude,dest_name:m?.name,dest_addr:m?.address,dest_lat:m?.latitude,dest_lng:m?.longitude,rider_name:e.rider.name,rider_phone:e.rider.phone});try{sc({wallet_address:e.wallet_address,region:e.region,locations:e.locations,ts:Math.floor(Date.now()/1e3)})}catch(p){process.stderr.write(`[place-history] record failed: ${p.message}
439
- `)}return{request_id:d.requestId,price:d.price,currency:d.currency}}var tn;function Oe(e){tn=e.replace(/\/$/,"")}async function rn(e,t,r,n,s){let i={"Content-Type":"application/json",Authorization:`Bearer ${r}`},o=s?`${tn}${t}?${new URLSearchParams(s).toString()}`:`${tn}${t}`,a=await fetch(o,{method:e,headers:i,body:n!==void 0?JSON.stringify(n):void 0});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status} ${a.statusText} on ${e} ${t}: ${c}`)}return a.json()}async function ic(e,t,r){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`};r&&(n["payment-signature"]=r,n["x-signature-interpret-mode"]="general");let s=await fetch(`${tn}/payment/tip`,{method:"POST",headers:n,body:JSON.stringify(t)});if(s.status===402){let o=s.headers.get("payment-required");if(!o)throw new Error("402 response missing payment-required header");let a=JSON.parse(Buffer.from(o,"base64").toString("utf-8"));return{status:402,accepts:a.accepts,nonce:a.nonce}}if(s.status===200||s.status===201){let o=s.headers.get("payment-response"),a=o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{network:"",payer:"",success:!0,transaction:""};return{status:s.status,paymentResponse:a}}let i=await s.text().catch(()=>"");throw new Error(`HTTP ${s.status} ${s.statusText} on POST /payment/tip: ${i}`)}function oc(e,t){return rn("GET","/tip/config",e,void 0,{region:t})}function ac(e,t,r){return rn("POST",`/v2/rides/request/${t}/tip/pre-request`,e,{price:r})}function cc(e,t){return ic(e,{rideRequestId:t}).then(r=>{if(r.status!==402)throw new Error(`Expected 402 from tip payment probe, got ${r.status}`);return{accepts:r.accepts,nonce:r.nonce}})}function lc(e,t,r){return ic(e,{rideRequestId:t},r).then(n=>{if(n.status!==200&&n.status!==201)throw new Error(`Expected 200/201 from tip payment submit, got ${n.status}`);return n.paymentResponse})}async function dc(e,t=20){let r=await rn("GET","/v2/rides/request/history",e,void 0,{status:"completed",limit:String(t)});return{items:r.items??[],nextCursor:r.nextCursor??null}}function nn(e,t){return rn("GET",`/v2/ride-histories/detail/${t}`,e)}import _s from"fs";import{spawn as tg}from"child_process";import ys from"path";import me from"fs";import uc from"path";function sn(e,t){return uc.join(e,"run",`${t}.pid`)}function gs(e){try{let t=parseInt(me.readFileSync(e,"utf8").trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function pc(e){try{return process.kill(e,0),!0}catch{return!1}}function mt(e,t){let r=gs(sn(e,t));return r!==null&&pc(r)}function fs(e,t){if(me.existsSync(`${e}.amb-migration-quiesced`))return!1;let r=sn(e,t);me.mkdirSync(uc.dirname(r),{recursive:!0});try{let n=me.openSync(r,"wx");return me.writeSync(n,String(process.pid)),me.closeSync(n),!0}catch{let n=gs(r);if(n===process.pid||n!==null&&pc(n))return!1;try{me.unlinkSync(r)}catch{}try{let s=me.openSync(r,"wx");return me.writeSync(s,String(process.pid)),me.closeSync(s),!0}catch{return!1}}}function on(e,t){try{gs(sn(e,t))===process.pid&&me.unlinkSync(sn(e,t))}catch{}}import{createHash as mc}from"crypto";var gc=1,eg=new Set(["FINISHED","CANCELED","USER_CANCELED","USER_CANCELED_BEFORE_CALL","USER_CANCELED_NO_FREE","DRIVER_CANCELED","DRIVER_CANCELED_RECALLABLE","COMPANY_CANCELED","COMPANY_CANCELED_RECALLABLE","EXPIRED","EXPIRED_RECALLABLE","EXPIRED_BEFORE_PAY","NOT_MATCHED","ERROR_PAYMENT","ERROR","ACCIDENT_CANCELED"]);function Ie(e){return eg.has(e)}function fc(e){let t=e.kind==="ride_status"?`${e.rideId}|ride_status|${e.status??""}`:`${e.rideId}|${e.kind}|${mc("sha256").update(e.content??"").digest("hex")}`;return"evt_"+mc("sha256").update(t).digest("hex").slice(0,24)}function rg(){let e=process.argv[1]??"",t=e?ys.resolve(e):"";if(!t||!_s.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}async function xe(e,t={}){try{let r=V(e);if(!r||Ie(r.status)||mt(F(),`sup-${e}`))return!1;let n=t.spawn??tg,s=rg();return n(process.execPath,[s,"monitor-supervisor",e],{detached:!0,stdio:"ignore"}).unref?.(),!0}catch(r){try{let n=ys.join(F(),"run",`monitor-trace-${e}.log`);_s.mkdirSync(ys.dirname(n),{recursive:!0}),_s.appendFileSync(n,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:"ensure_monitor_failed",rideId:e,error:String(r)})+`
440
- `)}catch{}return!1}}import ng from"fs";import sg from"path";var hs;function yc(e){hs=e}function hc(){return hs}function wc(e){let t=[],r;for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--account=")){let i=s.slice(10);if(i!=="wallet"&&i!=="tada")throw new Error(`--account: expected 'wallet' or 'tada', got '${i}'`);r=i;continue}if(s==="--account"){let i=e[n+1];if(i!=="wallet"&&i!=="tada")throw new Error(`--account: expected 'wallet' or 'tada', got '${i??"(missing)"}'`);r=i,n+=1;continue}t.push(s)}return{account:r,argv:t}}function _c(){return{hasMember:!1,hasWallet:!1,member:void 0,walletAddress:void 0}}function ig(){let e=et(),t=sg.join(e,"ambient-ride.db");if(!ng.existsSync(t))return _c();try{b(e);let r=St(),n=fr(),s=n.length>0?n:gr();return{hasMember:!!r,hasWallet:s.length>0,member:r,walletAddress:s[0]?.wallet_address}}catch{return _c()}}function K(e={}){let t=e.flag??hs,r=ig();return t?{mode:t,reason:"flag",hasMember:r.hasMember,hasWallet:r.hasWallet,member:r.member,walletAddress:r.walletAddress}:r.hasMember?{mode:"tada",reason:"member-session",hasMember:!0,hasWallet:r.hasWallet,member:r.member,walletAddress:r.walletAddress}:r.hasWallet?{mode:"wallet",reason:"wallet",hasMember:!1,hasWallet:!0,member:void 0,walletAddress:r.walletAddress}:{mode:null,reason:"onboarding",hasMember:!1,hasWallet:!1,member:void 0,walletAddress:void 0}}var og=["wallet-","deposit-","siwe-","ride-pay-","bridge-"],ag=new Set([]);function Ec(e){if(og.some(t=>e.startsWith(t)))return"wallet";if(ag.has(e))return"tada"}function Rc(e,t){return e==="wallet"?"This command is wallet-only. Add '--account=wallet' to this invocation, or run 'amb logout' to fall back to crypto mode.":"This command is TADA/Throo member-only. Add '--account=tada' to this invocation, or run 'amb login' to enter member mode."}var cg={401:"unauthorized",404:"agent_session_not_found",409:"agent_session_already_decided",410:"agent_session_expired"},Y=class extends Error{constructor(r,n){super(`gateway ${r} ${n}`);this.status=r;this.code=n;this.name="GatewayError"}status;code};function ce(e,t){let r=cg[e]??"unknown";try{let n=JSON.parse(t);n&&typeof n.code=="string"&&(r=n.code)}catch{}return new Y(e,r)}var bc="";function gt(e){bc=e.replace(/\/$/,"")}async function Me(e,t,r={}){let n=(r.host??bc).replace(/\/$/,"");if(!n)throw new Error("tada gateway not initialized");let s=r.query?Object.entries(r.query).filter(([,a])=>a!==void 0&&a!=="").map(([a,c])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(c))}`).join("&"):"",i={Authorization:`Bearer ${t}`};r.lang&&(i["Accept-Language"]=r.lang);let o=await fetch(`${n}${e}${s?`?${s}`:""}`,{method:"GET",headers:i});if(!o.ok){let a=await o.text().catch(()=>"");throw ce(o.status,a)}return o.json()}function Tc(e,t){return Me("/v1/cards",t,{host:e})}function Sc(e,t){if(t!=null&&t!=="")return{kind:"selected",uuid:t};let r=e.filter(s=>!s.is_expired);if(r.length===0)return{kind:"none",reason:e.length?"all_expired":"no_cards"};if(r.length===1)return{kind:"selected",uuid:r[0].id,card:r[0]};let n=r.filter(s=>s.is_default);return n.length===1?{kind:"selected",uuid:n[0].id,card:n[0]}:{kind:"ambiguous",candidates:r}}async function Mt(e,t,r){if(t)return t;let n;try{n=await e.getCards(r)}catch(i){let a=i.code==="card_api_error"?"Card service is temporarily unavailable. Please try again in a moment.":"Could not load your cards. Your TADA/Throo session may have expired \u2014 run `amb login` again.";return g({error:"CARD_LOOKUP_FAILED",message:a}),process.exit(1),null}let s=Sc(n);return s.kind==="none"?(g({error:"NO_CARD",region_host:r,message:s.reason==="all_expired"?"All your cards are expired. Add or update a card in the TADA/Throo app.":`No payment card found for this pickup region (looked up on ${r}). If a card is already saved in the TADA/Throo app, re-check the pickup coordinates before adding another.`}),process.exit(1),null):s.kind==="ambiguous"?(w({needs_card_selection:!0,cards:s.candidates.map(i=>({id:i.id,card_brand:i.card_brand,card_last4:i.card_last4,is_default:i.is_default,is_expired:i.is_expired})),next_action:"ASK_USER_TO_PICK_CARD_THEN_RERUN_WITH_payment_item_uuid"}),process.exit(0),null):s.uuid}var Ut="";function Ue(e){Ut=e.replace(/\/$/,"")}function lg(e){return`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`}async function ws(e,t,r,n){if(!Ut)throw new Error("tada gateway api not initialized");let s=await fetch(`${Ut}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:lg(e)},body:n!==void 0?JSON.stringify(n):void 0});if(!s.ok){let i=await s.text().catch(()=>"");throw ce(s.status,i)}return s.json()}function Ac(e){return ws(e,"POST","/v1/agent-session")}function Ic(e,t,r){return ws(e,"POST","/v1/oauth/token",{grant_type:"agent_session",session_token:t,user_code:r})}function xc(e,t){return ws(e,"POST","/v1/oauth/token",{grant_type:"refresh_token",refresh_token:t})}async function vc(e){if(!Ut)throw new Error("tada gateway api not initialized");let t=await fetch(`${Ut}/v1/me`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let r=await t.text().catch(()=>"");throw ce(t.status,r)}return t.json()}function Nc(e){try{let t=e.split(".")[1];if(!t)return null;let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof r.sub=="string"?r.sub:null}catch{return null}}function kc(e){try{let t=e.split(".")[1];if(!t)return null;let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof r.exp=="number"?r.exp:null}catch{return null}}function ug(){return Math.floor(Date.now()/1e3)}async function Es(e){let t=await Ac(e);return{sessionToken:t.session_token,approvalUrl:t.approval_url,expiresAt:t.expires_at,pollIntervalSec:t.polling_interval_seconds}}async function Rs(e,t,r){let n=await Ic(e,t,r),s=Nc(n.access_token);if(!s)throw new Error("access token missing sub claim");let i=await pg(n.access_token);return ro({id:s,display_name:i?.name??void 0,phone:i?.phone??void 0}),Cc(s,n.access_token,n.expires_in,n.refresh_token),{memberId:s}}async function pg(e){try{let t=await vc(e);return{name:t.name,phone:t.phone}}catch(t){return oe(`[tada-auth] /v1/me profile fetch failed; persisting member id only: ${String(t)}
441
- `),null}}function Cc(e,t,r,n){Ki(e,t,ug()+r,n,kc(n))}async function an(e){let t=St();if(!t)return null;let r=P(t.id,"member");if(r)return r;let n=wr(t.id);if(!n)return oe(`[tada-auth] no usable member refresh token (expired or pruned); re-login required
442
- `),null;try{let s=await xc(e,n.refresh_token);return Cc(t.id,s.access_token,s.expires_in,s.refresh_token),s.access_token}catch(s){return oe(`[tada-auth] member token refresh failed; re-login required: ${String(s)}
443
- `),null}}function Dc(){let e=St();return e?(no(e.id),!0):!1}import{EventEmitter as fg}from"events";import{io as _g}from"socket.io-client";import gg from"path";var cn=1e4;function ln(e,t){return gg.join(e,"run",`chat-${t}.sock`)}function bs(e,t){if(!Hi())return;let r={ts:new Date().toISOString(),msg:e,...t??{}};oe("[chat-debug] "+JSON.stringify(r)+`
444
- `)}var dn=class extends fg{config;requestId;walletAddress;socket=null;roomId=null;readyEmitted=!1;pendingAcks=[];constructor(t,r,n){super(),this.config=t,this.requestId=r,this.walletAddress=n}connect(){try{let t=P(this.walletAddress);if(!t){this.emit("error",{message:`No valid JWT for wallet ${this.walletAddress}`});return}let r=new URL(this.config.gatewayServerUrl).origin,n=_g(`${r}/chat`,{path:"/tada-ton/chat-socket",transports:["websocket"],auth:{token:t}});this.socket=n,this.bindSocketEvents(n)}catch(t){this.emit("error",{message:`connect failed: ${t.message}`})}}dispose(){this.disconnect()}disconnect(){try{this.socket&&(this.socket.disconnect(),this.socket=null),this.roomId=null,this.readyEmitted=!1,this.drainPendingAcks()}catch(t){this.emit("error",{message:`disconnect cleanup failed: ${t.message}`})}}send(t){return this.roomId===null?Promise.resolve({ok:!1,reason:"not_joined"}):new Promise(r=>{let n=setTimeout(()=>{let s=this.pendingAcks.findIndex(i=>i.resolve===r);s>=0&&this.pendingAcks.splice(s,1),r({ok:!1,reason:"ack_timeout"})},cn);this.pendingAcks.push({resolve:r,timer:n});try{this.socket?.emit("SEND_MESSAGE",{roomId:this.roomId,content:t,type:"TEXT"})}catch(s){let i=this.pendingAcks.findIndex(o=>o.resolve===r);i>=0&&this.pendingAcks.splice(i,1),clearTimeout(n),r({ok:!1,reason:`emit_failed: ${s.message}`})}})}drainPendingAcks(){for(;this.pendingAcks.length;){let t=this.pendingAcks.shift();clearTimeout(t.timer),t.resolve({ok:!1,reason:"disconnected"})}}bindSocketEvents(t){t.on("connect",()=>{bs("socket connect",{requestId:this.requestId,socketId:t.id});try{t.emit("JOIN_ROOM",{rideRequestId:this.requestId})}catch(r){this.emit("error",{message:`JOIN_ROOM emit failed: ${r.message}`})}}),t.on("MESSAGE_SENT",r=>{try{if(r.event==="joined"){let n=this.roomId===null&&!this.readyEmitted;this.roomId=r.roomId,n&&(this.readyEmitted=!0,this.emit("ready",{roomId:this.roomId,pid:process.pid}))}else{let n=this.pendingAcks.shift();n&&(clearTimeout(n.timer),n.resolve({ok:!0}))}}catch(n){this.emit("error",{message:`MESSAGE_SENT handler failed: ${n.message}`})}}),t.on("NEW_MESSAGE",r=>{try{this.emit("message",{data:r})}catch(n){this.emit("error",{message:`NEW_MESSAGE handler failed: ${n.message}`})}}),t.on("disconnect",r=>{bs("socket disconnect",{reason:r});try{this.roomId=null,this.drainPendingAcks()}catch(n){this.emit("error",{message:`disconnect handler failed: ${n.message}`})}}),t.io.on("reconnect_attempt",r=>{try{let n=P(this.walletAddress),s=!!n;n&&t.auth&&(t.auth.token=n),bs("socket reconnect_attempt",{attempt:r,jwtRefreshed:s}),this.emit("reconnecting",{attempt:r})}catch(n){this.emit("error",{message:`reconnect_attempt handler failed: ${n.message}`})}}),t.on("error",r=>{this.emit("error",{message:r.message})}),t.on("connect_error",r=>{this.emit("error",{message:`connect_error: ${r.message}`})})}};var Be=class extends Error{code="NOT_SUPPORTED";constructor(t){super(t),this.name="NotSupportedError"}},ft=class extends Error{code="SHARE_NOT_AVAILABLE";constructor(t){super(t),this.name="ShareNotAvailableError"}};async function un(e){let{rawTypedData:t,walletAddress:r,target:n}=e;if(ae(r)==null)return{typed_data:t,isSmartAccount:!1};let s=await jo(n);if(s!==n.chainId)throw new Error(`PAYMENT_CHAIN_MISMATCH: payment RPC serves chain ${s} but the payment authorization is for chain ${n.chainId}. Check the build payment network and its AMB_RIDE_RPC_URL_<NETWORK>.`);if(!await Lr(n,r))return{typed_data:t,isSmartAccount:!1};let i=await Or(n,r),o=Cr(t);return{typed_data:Dr({kernelDomain:i,innerDigest:o}),isSmartAccount:!0}}function pn(e,t){return t?Pr(e):e}function yg(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function mn(e){let{request_id:t,price:r,wallet_address:n,config:s}=e,i=yg(n);await ac(i,t,r);let{accepts:o,nonce:a}=await cc(i,t);if(!o.length)throw new Error("TIP_PAY_PROBE_FAILED: Server returned no payment accepts.");let c=o[0],l=String(Math.floor(Date.now()/1e3)+c.maxTimeoutSeconds),d=c.network.split(":")[1],u=d?parseInt(d,10):NaN;if(Number.isNaN(u))throw new Error(`TIP_PAY_PREPARE: Cannot parse chainId from network "${c.network}".`);let m={domain:{name:c.extra.name,version:c.extra.version,chainId:u,verifyingContract:c.asset},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"TransferWithAuthorization",message:{from:n,to:c.payTo,value:c.amount,validAfter:"0",validBefore:l,nonce:a}},{typed_data:p,isSmartAccount:f}=await un({rawTypedData:m,walletAddress:n,target:{rpcUrl:s.paymentRpcUrl,chainId:u}});return Kr(t,{accepts:o,nonce:a,walletAddress:n,validBefore:l,expiresAt:Date.now()+c.maxTimeoutSeconds*1e3,isSmartAccount:f}),{typed_data:p}}function hg(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function gn(e){let{request_id:t,signature:r}=e,n=Yr(t);if(!n)throw new Error("PAYMENT_CACHE_MISS: request_id not found or expired. Call tip_prepare again.");let{accepts:s,nonce:i,walletAddress:o,validBefore:a,isSmartAccount:c}=n,l=hg(o),d=s[0],u={x402Version:2,accepted:d,payload:{authorization:{from:o,to:d.payTo,value:d.amount,validAfter:"0",validBefore:a,nonce:i},signature:pn(r,c===!0)}},m=Buffer.from(JSON.stringify(u)).toString("base64"),p=await lc(l,t,m);return{success:p.success,tx_hash:p.transaction}}function fn(e,t){if(e?.length)return e.find(r=>!t(r)?.toLowerCase().includes("driver"))??e[0]}function X(e){return e.replace(/([\\`*_{}\[\]()<>#+!|])/g,"\\$1")}function Ts(e){return`${X(e.amount)} ${e.currency?X(e.currency):"currency unavailable"}`}function Lc(e,t){return[`${" ".repeat(t)}- ${X(e.label)}: ${Ts(e.amount)}`,...(e.children??[]).flatMap(r=>Lc(r,t+1))]}function Pc(e){let t=e.name.trim(),r=e.address.replace(/^[\s,;:–—-]+/u,"").trim();return X(t&&r&&t!==r?`${t} \u2014 ${r}`:t||r)}function wg(e){return e.replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\s/g,"%20")}function Oc(e){return new Set(e.flatMap(t=>[t.amount.currency,...Oc(t.children??[])]).filter(t=>!!t))}function Mc(e){let t=["# Ride receipt"];if(e.total&&t.push("","## Total fee charged",`**${Ts(e.total)}**`),e.fareItems.length){t.push("","## Fare breakdown");for(let n of e.fareItems)t.push(...Lc(n,0))}let r=Oc(e.fareItems);if(e.total?.currency&&r.size===1&&!r.has(e.total.currency)){let n=[...r][0];t.push("",`> Currency conversion: fare is shown in ${X(n)} and the charge in ${X(e.total.currency)}${e.exchangeRate?`; exchange rate ${X(e.exchangeRate)}`:""}.`)}if(e.transactions?.length){t.push("","## Transactions");for(let n of e.transactions){let s=n.explorerUrl?`[${X(n.hash)}](${wg(n.explorerUrl)})`:X(n.hash),i=n.network?` (${X(n.network)})`:"",o=n.amount?` \u2014 ${Ts(n.amount)}`:"";t.push(`- ${n.kind[0].toUpperCase()}${n.kind.slice(1)}${i}: ${s}${o}`)}}if(t.push("","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","","## Ride details"),e.pickupAt){let n=e.dropoffAt&&e.dropoffAt!==e.pickupAt?`${e.pickupAt} ~ ${e.dropoffAt}`:e.pickupAt;t.push(`- Date and time: ${X(n)}`)}return e.rideType&&t.push(`- Ride type: ${X(e.rideType)}`),e.driverName&&t.push(`- Driver: ${X(e.driverName)}`),e.passengerName&&t.push(`- Passenger: ${X(e.passengerName)}`),t.push(`- Ride ID: ${X(e.rideId)}`),e.pickup&&t.push(`- Pickup: ${Pc(e.pickup)}`),e.dropoff&&t.push(`- Destination: ${Pc(e.dropoff)}`),e.paymentMethod&&t.push(`- Payment method: ${X(e.paymentMethod)}`),`${t.join(`
544
+ `).run(s!==void 0?1:0,s??null,e,t),S().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function pv(e,t){let r=Nn(t);if(r)return S().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r)}function mv(e,t){let r=Ns(e,t);return r?r.is_favorite===0?r:(S().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
545
+ WHERE wallet_address = ? AND id = ?`).run(e,t),S().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)):null}function fv(e,t){let r=Nn(t);if(!r)return null;let n=S().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?n.is_favorite===0?n:(S().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
546
+ WHERE wallet_address = ? AND id = ?`).run(e,n.id),S().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,n.id)):null}function gv(e){for(let t of e.locations){let r=t.googlePlaceId??t.placeId,n=Cn({placeId:r,latitude:t.latitude,longitude:t.longitude});if(!n){process.stderr.write(`[place-history] skip location (no placeId + invalid coords): name=${t.name}
547
+ `);continue}uv({wallet_address:e.wallet_address,name:t.name,formatted_address:t.address,latitude:t.latitude,longitude:t.longitude,google_place_id:r??null,region:e.region,dedup_key:n,ts:e.ts})}}function rM(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function to(e,t){let r=rM(e.wallet_address),n=Ka(e.search_id);if(!n)throw new Error("SEARCH_CACHE_MISS: search_id not found or expired. Call ride_search again.");let a=(JSON.parse(n).products??[]).find(f=>f.code===e.product_code);if(!a)throw new Error(`PRODUCT_NOT_FOUND: product_code ${e.product_code} not found in search result.`);let c=(a.priceInfos??[]).find(f=>f.currencyId===e.pay_currency);if(!c)throw new Error(`CURRENCY_NOT_FOUND: pay_currency ${e.pay_currency} not available for product ${e.product_code}.`);let u=c.walletProviderId,l=await Kb(r,{region:e.region,productCode:e.product_code,walletProviderId:u,payCurrency:e.pay_currency,locations:e.locations,rider:e.rider,baseSearchResponse:n,userWallet:{network:t.paymentNetwork,address:e.wallet_address,name:e.wallet_address}}),d=e.locations[0],m=e.locations[e.locations.length-1];Ga({request_id:l.requestId,wallet_address:e.wallet_address,region:e.region,product_code:e.product_code,price:l.price,pay_currency:e.pay_currency,origin_name:d?.name,origin_addr:d?.address,origin_lat:d?.latitude,origin_lng:d?.longitude,dest_name:m?.name,dest_addr:m?.address,dest_lat:m?.latitude,dest_lng:m?.longitude,rider_name:e.rider.name,rider_phone:e.rider.phone});try{gv({wallet_address:e.wallet_address,region:e.region,locations:e.locations,ts:Math.floor(Date.now()/1e3)})}catch(f){process.stderr.write(`[place-history] record failed: ${f.message}
548
+ `)}return{request_id:l.requestId,price:l.price,currency:l.currency}}p();var ro;function hr(e){ro=e.replace(/\/$/,"")}async function no(e,t,r,n,s){let i={"Content-Type":"application/json",Authorization:`Bearer ${r}`},a=s?`${ro}${t}?${new URLSearchParams(s).toString()}`:`${ro}${t}`,o=await fetch(a,{method:e,headers:i,body:n!==void 0?JSON.stringify(n):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`HTTP ${o.status} ${o.statusText} on ${e} ${t}: ${c}`)}return o.json()}async function hv(e,t,r){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`};r&&(n["payment-signature"]=r,n["x-signature-interpret-mode"]="general");let s=await fetch(`${ro}/payment/tip`,{method:"POST",headers:n,body:JSON.stringify(t)});if(s.status===402){let a=s.headers.get("payment-required");if(!a)throw new Error("402 response missing payment-required header");let o=JSON.parse(Buffer.from(a,"base64").toString("utf-8"));return{status:402,accepts:o.accepts,nonce:o.nonce}}if(s.status===200||s.status===201){let a=s.headers.get("payment-response"),o=a?JSON.parse(Buffer.from(a,"base64").toString("utf-8")):{network:"",payer:"",success:!0,transaction:""};return{status:s.status,paymentResponse:o}}let i=await s.text().catch(()=>"");throw new Error(`HTTP ${s.status} ${s.statusText} on POST /payment/tip: ${i}`)}function yv(e,t){return no("GET","/tip/config",e,void 0,{region:t})}function _v(e,t,r){return no("POST",`/v2/rides/request/${t}/tip/pre-request`,e,{price:r})}function Ev(e,t){return hv(e,{rideRequestId:t}).then(r=>{if(r.status!==402)throw new Error(`Expected 402 from tip payment probe, got ${r.status}`);return{accepts:r.accepts,nonce:r.nonce}})}function Tv(e,t,r){return hv(e,{rideRequestId:t},r).then(n=>{if(n.status!==200&&n.status!==201)throw new Error(`Expected 200/201 from tip payment submit, got ${n.status}`);return n.paymentResponse})}async function bv(e,t=20){let r=await no("GET","/v2/rides/request/history",e,void 0,{status:"completed",limit:String(t)});return{items:r.items??[],nextCursor:r.nextCursor??null}}function so(e,t){return no("GET",`/v2/ride-histories/detail/${t}`,e)}p();import _u from"fs";import{spawn as sM}from"child_process";import Eu from"path";p();import Nt from"fs";import vv from"path";function io(e,t){return vv.join(e,"run",`${t}.pid`)}function hu(e){try{let t=parseInt(Nt.readFileSync(e,"utf8").trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function xv(e){try{return process.kill(e,0),!0}catch{return!1}}function Ln(e,t){let r=hu(io(e,t));return r!==null&&xv(r)}function yu(e,t){if(Nt.existsSync(`${e}.amb-migration-quiesced`))return!1;let r=io(e,t);Nt.mkdirSync(vv.dirname(r),{recursive:!0});try{let n=Nt.openSync(r,"wx");return Nt.writeSync(n,String(process.pid)),Nt.closeSync(n),!0}catch{let n=hu(r);if(n===process.pid||n!==null&&xv(n))return!1;try{Nt.unlinkSync(r)}catch{}try{let s=Nt.openSync(r,"wx");return Nt.writeSync(s,String(process.pid)),Nt.closeSync(s),!0}catch{return!1}}}function ao(e,t){try{hu(io(e,t))===process.pid&&Nt.unlinkSync(io(e,t))}catch{}}p();import{createHash as Rv}from"crypto";var Av=1,nM=new Set(["FINISHED","COMPLETED","CANCELED","USER_CANCELED","USER_CANCELED_BEFORE_CALL","USER_CANCELED_NO_FREE","DRIVER_CANCELED","DRIVER_CANCELED_RECALLABLE","COMPANY_CANCELED","COMPANY_CANCELED_RECALLABLE","EXPIRED","EXPIRED_RECALLABLE","EXPIRED_BEFORE_PAY","NOT_MATCHED","ERROR_PAYMENT","ERROR","ACCIDENT_CANCELED"]);function Lt(e){return nM.has(e.toUpperCase())}function Wr(e){let t=e.kind==="ride_status"?`${e.rideId}|ride_status|${e.status??""}`:`${e.rideId}|${e.kind}|${Rv("sha256").update(e.content??"").digest("hex")}`;return"evt_"+Rv("sha256").update(t).digest("hex").slice(0,24)}function iM(){let e=process.argv[1]??"",t=e?Eu.resolve(e):"";if(!t||!_u.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}async function nr(e,t={}){try{let r=Ae(e);if(!r||Lt(r.status)||Ln(ge(),`sup-${e}`))return!1;let n=t.spawn??sM,s=iM();return n(process.execPath,[s,"monitor-supervisor",e],{detached:!0,stdio:"ignore"}).unref?.(),!0}catch(r){try{let n=Eu.join(ge(),"run",`monitor-trace-${e}.log`);_u.mkdirSync(Eu.dirname(n),{recursive:!0}),_u.appendFileSync(n,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:"ensure_monitor_failed",rideId:e,error:String(r)})+`
549
+ `)}catch{}return!1}}p();import aM from"fs";import oM from"path";p();function wv(e){let t=Math.floor(Date.now()/1e3),r=S();r.prepare("DELETE FROM tada_members WHERE id <> ?").run(e.id),r.prepare(`
550
+ INSERT INTO tada_members (id, phone, display_name, region, created_at, last_active_at)
551
+ VALUES (?, ?, ?, ?, ?, ?)
552
+ ON CONFLICT(id) DO UPDATE SET
553
+ phone = excluded.phone,
554
+ display_name = excluded.display_name,
555
+ region = excluded.region,
556
+ last_active_at = excluded.last_active_at
557
+ `).run(e.id,e.phone??null,e.display_name??null,e.region??null,t,t)}function Ls(){return S().prepare("SELECT * FROM tada_members ORDER BY last_active_at DESC LIMIT 1").get()}function Sv(e){let t=S();t.prepare("DELETE FROM jwt_cache WHERE cache_key = ? AND kind = 'member'").run(e),t.prepare("DELETE FROM tada_members WHERE id = ?").run(e)}var Tu;function Pv(e){Tu=e}function Dv(){return Tu}function Ov(e){let t=[],r;for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--account=")){let i=s.slice(10);if(i!=="wallet"&&i!=="tada")throw new Error(`--account: expected 'wallet' or 'tada', got '${i}'`);r=i;continue}if(s==="--account"){let i=e[n+1];if(i!=="wallet"&&i!=="tada")throw new Error(`--account: expected 'wallet' or 'tada', got '${i??"(missing)"}'`);r=i,n+=1;continue}t.push(s)}return{account:r,argv:t}}function Iv(){return{hasMember:!1,hasWallet:!1,member:void 0,walletAddress:void 0}}function cM(){let e=rn(),t=oM.join(e,"ambient-ride.db");if(!aM.existsSync(t))return Iv();try{O(e);let r=Ls(),n=oi(),s=n.length>0?n:ai();return{hasMember:!!r,hasWallet:s.length>0,member:r,walletAddress:s[0]?.wallet_address}}catch{return Iv()}}function ze(e={}){let t=e.flag??Tu,r=cM();return t?{mode:t,reason:"flag",hasMember:r.hasMember,hasWallet:r.hasWallet,member:r.member,walletAddress:r.walletAddress}:r.hasMember?{mode:"tada",reason:"member-session",hasMember:!0,hasWallet:r.hasWallet,member:r.member,walletAddress:r.walletAddress}:r.hasWallet?{mode:"wallet",reason:"wallet",hasMember:!1,hasWallet:!0,member:void 0,walletAddress:r.walletAddress}:{mode:null,reason:"onboarding",hasMember:!1,hasWallet:!1,member:void 0,walletAddress:void 0}}var lM=["wallet-","deposit-","siwe-","ride-pay-","bridge-"],uM=new Set(["wallet-setup","wallet-setup-verify","wallet-status","wallet-balance"]),dM=["coupon-"];function Cv(e){if(!uM.has(e)){if(lM.some(t=>e.startsWith(t)))return"wallet";if(dM.some(t=>e.startsWith(t)))return"tada"}}function Nv(e,t){return e==="wallet"?"This command is wallet-only. Add '--account=wallet' to this invocation, or run 'amb logout' to fall back to crypto mode.":"This command is TADA/Throo member-only. Add '--account=tada' to this invocation, or run 'amb login' to enter member mode."}p();p();p();var Lv="";function kn(e){Lv=e.replace(/\/$/,"")}async function yr(e,t,r={}){let n=(r.host??Lv).replace(/\/$/,"");if(!n)throw new Error("tada gateway not initialized");let s=r.query?Object.entries(r.query).filter(([,o])=>o!==void 0&&o!=="").map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(String(c))}`).join("&"):"",i={Authorization:`Bearer ${t}`};r.lang&&(i["Accept-Language"]=r.lang);let a=await fetch(`${n}${e}${s?`?${s}`:""}`,{method:"GET",headers:i});if(!a.ok){let o=await a.text().catch(()=>"");throw dt(a.status,o)}return a.json()}function kv(e,t){return yr("/v1/cards",t,{host:e})}function Mv(e,t){if(t!=null&&t!=="")return{kind:"selected",uuid:t};let r=e.filter(s=>!s.is_expired);if(r.length===0)return{kind:"none",reason:e.length?"all_expired":"no_cards"};if(r.length===1)return{kind:"selected",uuid:r[0].id,card:r[0]};let n=r.filter(s=>s.is_default);return n.length===1?{kind:"selected",uuid:n[0].id,card:n[0]}:{kind:"ambiguous",candidates:r}}async function Jr(e,t,r){if(t)return t;let n;try{n=await e.getCards(r)}catch(i){let o=i.code==="card_api_error"?"Card service is temporarily unavailable. Please try again in a moment.":"Could not load your cards. Your TADA/Throo session may have expired \u2014 run `amb login` again.";return b({error:"CARD_LOOKUP_FAILED",message:o}),process.exit(1),null}let s=Mv(n);return s.kind==="none"?(b({error:"NO_CARD",region_host:r,message:s.reason==="all_expired"?"All your cards are expired. Add or update a card in the TADA/Throo app.":`No payment card found for this pickup region (looked up on ${r}). If a card is already saved in the TADA/Throo app, re-check the pickup coordinates before adding another.`}),process.exit(1),null):s.kind==="ambiguous"?(w({needs_card_selection:!0,cards:s.candidates.map(i=>({id:i.id,card_brand:i.card_brand,card_last4:i.card_last4,is_default:i.is_default,is_expired:i.is_expired})),next_action:"ASK_USER_TO_PICK_CARD_THEN_RERUN_WITH_payment_item_uuid"}),process.exit(0),null):s.uuid}p();p();p();var ks="";function _r(e){ks=e.replace(/\/$/,"")}function pM(e){return`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`}async function bu(e,t,r,n){if(!ks)throw new Error("tada gateway api not initialized");let s=await fetch(`${ks}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:pM(e)},body:n!==void 0?JSON.stringify(n):void 0});if(!s.ok){let i=await s.text().catch(()=>"");throw dt(s.status,i)}return s.json()}function Uv(e){return bu(e,"POST","/v1/agent-session")}function Fv(e,t,r){return bu(e,"POST","/v1/oauth/token",{grant_type:"agent_session",session_token:t,user_code:r})}function jv(e,t){return bu(e,"POST","/v1/oauth/token",{grant_type:"refresh_token",refresh_token:t})}async function qv(e){if(!ks)throw new Error("tada gateway api not initialized");let t=await fetch(`${ks}/v1/me`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let r=await t.text().catch(()=>"");throw dt(t.status,r)}return t.json()}p();function Bv(e){try{let t=e.split(".")[1];if(!t)return null;let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof r.sub=="string"?r.sub:null}catch{return null}}function Vv(e){try{let t=e.split(".")[1];if(!t)return null;let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof r.exp=="number"?r.exp:null}catch{return null}}function fM(){return Math.floor(Date.now()/1e3)}async function vu(e){let t=await Uv(e);return{sessionToken:t.session_token,approvalUrl:t.approval_url,expiresAt:t.expires_at,pollIntervalSec:t.polling_interval_seconds}}async function xu(e,t,r){let n=await Fv(e,t,r),s=Bv(n.access_token);if(!s)throw new Error("access token missing sub claim");let i=await gM(n.access_token);return wv({id:s,display_name:i?.name??void 0,phone:i?.phone??void 0}),Gv(s,n.access_token,n.expires_in,n.refresh_token),{memberId:s}}async function gM(e){try{let t=await qv(e);return{name:t.name,phone:t.phone}}catch(t){return Tt(`[tada-auth] /v1/me profile fetch failed; persisting member id only: ${String(t)}
558
+ `),null}}function Gv(e,t,r,n){Wd(e,t,fM()+r,n,Vv(n))}async function oo(e){let t=Ls();if(!t)return null;let r=ie(t.id,"member");if(r)return r;let n=_i(t.id);if(!n)return Tt(`[tada-auth] no usable member refresh token (expired or pruned); re-login required
559
+ `),null;try{let s=await jv(e,n.refresh_token);return Gv(t.id,s.access_token,s.expires_in,s.refresh_token),s.access_token}catch(s){return Tt(`[tada-auth] member token refresh failed; re-login required: ${String(s)}
560
+ `),null}}function Hv(){let e=Ls();return e?(Sv(e.id),!0):!1}p();p();import{EventEmitter as _M}from"events";import{io as EM}from"socket.io-client";p();import yM from"path";var co=1e4;function lo(e,t){return yM.join(e,"run",`chat-${t}.sock`)}function Ru(e,t){if(!bd())return;let r={ts:new Date().toISOString(),msg:e,...t??{}};Tt("[chat-debug] "+JSON.stringify(r)+`
561
+ `)}var uo=class extends _M{config;requestId;walletAddress;socket=null;roomId=null;readyEmitted=!1;pendingAcks=[];constructor(t,r,n){super(),this.config=t,this.requestId=r,this.walletAddress=n}connect(){try{let t=ie(this.walletAddress);if(!t){this.emit("error",{message:`No valid JWT for wallet ${this.walletAddress}`});return}let r=new URL(this.config.gatewayServerUrl).origin,n=EM(`${r}/chat`,{path:"/tada-ton/chat-socket",transports:["websocket"],auth:{token:t}});this.socket=n,this.bindSocketEvents(n)}catch(t){this.emit("error",{message:`connect failed: ${t.message}`})}}dispose(){this.disconnect()}disconnect(){try{this.socket&&(this.socket.disconnect(),this.socket=null),this.roomId=null,this.readyEmitted=!1,this.drainPendingAcks()}catch(t){this.emit("error",{message:`disconnect cleanup failed: ${t.message}`})}}send(t){return this.roomId===null?Promise.resolve({ok:!1,reason:"not_joined"}):new Promise(r=>{let n=setTimeout(()=>{let s=this.pendingAcks.findIndex(i=>i.resolve===r);s>=0&&this.pendingAcks.splice(s,1),r({ok:!1,reason:"ack_timeout"})},co);this.pendingAcks.push({resolve:r,timer:n});try{this.socket?.emit("SEND_MESSAGE",{roomId:this.roomId,content:t,type:"TEXT"})}catch(s){let i=this.pendingAcks.findIndex(a=>a.resolve===r);i>=0&&this.pendingAcks.splice(i,1),clearTimeout(n),r({ok:!1,reason:`emit_failed: ${s.message}`})}})}drainPendingAcks(){for(;this.pendingAcks.length;){let t=this.pendingAcks.shift();clearTimeout(t.timer),t.resolve({ok:!1,reason:"disconnected"})}}bindSocketEvents(t){t.on("connect",()=>{Ru("socket connect",{requestId:this.requestId,socketId:t.id});try{t.emit("JOIN_ROOM",{rideRequestId:this.requestId})}catch(r){this.emit("error",{message:`JOIN_ROOM emit failed: ${r.message}`})}}),t.on("MESSAGE_SENT",r=>{try{if(r.event==="joined"){let n=this.roomId===null&&!this.readyEmitted;this.roomId=r.roomId,n&&(this.readyEmitted=!0,this.emit("ready",{roomId:this.roomId,pid:process.pid}))}else{let n=this.pendingAcks.shift();n&&(clearTimeout(n.timer),n.resolve({ok:!0}))}}catch(n){this.emit("error",{message:`MESSAGE_SENT handler failed: ${n.message}`})}}),t.on("NEW_MESSAGE",r=>{try{this.emit("message",{data:r})}catch(n){this.emit("error",{message:`NEW_MESSAGE handler failed: ${n.message}`})}}),t.on("disconnect",r=>{Ru("socket disconnect",{reason:r});try{this.roomId=null,this.drainPendingAcks()}catch(n){this.emit("error",{message:`disconnect handler failed: ${n.message}`})}}),t.io.on("reconnect_attempt",r=>{try{let n=ie(this.walletAddress),s=!!n;n&&t.auth&&(t.auth.token=n),Ru("socket reconnect_attempt",{attempt:r,jwtRefreshed:s}),this.emit("reconnecting",{attempt:r})}catch(n){this.emit("error",{message:`reconnect_attempt handler failed: ${n.message}`})}}),t.on("error",r=>{this.emit("error",{message:r.message})}),t.on("connect_error",r=>{this.emit("error",{message:`connect_error: ${r.message}`})})}};p();var Er=class extends Error{code="NOT_SUPPORTED";constructor(t){super(t),this.name="NotSupportedError"}},Mn=class extends Error{code="SHARE_NOT_AVAILABLE";constructor(t){super(t),this.name="ShareNotAvailableError"}};p();p();async function po(e){let{rawTypedData:t,walletAddress:r,target:n}=e;if(bt(r)==null)return{typed_data:t,isSmartAccount:!1};let s=await qT(n);if(s!==n.chainId)throw new Error(`PAYMENT_CHAIN_MISMATCH: payment RPC serves chain ${s} but the payment authorization is for chain ${n.chainId}. Check the build payment network and its AMB_RIDE_RPC_URL_<NETWORK>.`);if(!await Oa(n,r))return{typed_data:t,isSmartAccount:!1};let i=await Ca(n,r),a=Ia(t);return{typed_data:Pa({kernelDomain:i,innerDigest:a}),isSmartAccount:!0}}function mo(e,t){return t?Da(e):e}function TM(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function fo(e){let{request_id:t,price:r,wallet_address:n,config:s}=e,i=TM(n);await _v(i,t,r);let{accepts:a,nonce:o}=await Ev(i,t);if(!a.length)throw new Error("TIP_PAY_PROBE_FAILED: Server returned no payment accepts.");let c=a[0],u=String(Math.floor(Date.now()/1e3)+c.maxTimeoutSeconds),l=c.network.split(":")[1],d=l?parseInt(l,10):NaN;if(Number.isNaN(d))throw new Error(`TIP_PAY_PREPARE: Cannot parse chainId from network "${c.network}".`);let m={domain:{name:c.extra.name,version:c.extra.version,chainId:d,verifyingContract:c.asset},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"TransferWithAuthorization",message:{from:n,to:c.payTo,value:c.amount,validAfter:"0",validBefore:u,nonce:o}},{typed_data:f,isSmartAccount:g}=await po({rawTypedData:m,walletAddress:n,target:{rpcUrl:s.paymentRpcUrl,chainId:d}});return Ya(t,{accepts:a,nonce:o,walletAddress:n,validBefore:u,expiresAt:Date.now()+c.maxTimeoutSeconds*1e3,isSmartAccount:g}),{typed_data:f}}p();function bM(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function go(e){let{request_id:t,signature:r}=e,n=On(t);if(!n)throw new Error("PAYMENT_CACHE_MISS: request_id not found or expired. Call tip_prepare again.");let{accepts:s,nonce:i,walletAddress:a,validBefore:o,isSmartAccount:c}=n,u=bM(a),l=s[0],d={x402Version:2,accepted:l,payload:{authorization:{from:a,to:l.payTo,value:l.amount,validAfter:"0",validBefore:o,nonce:i},signature:mo(r,c===!0)}},m=Buffer.from(JSON.stringify(d)).toString("base64"),f=await Tv(u,t,m);return{success:f.success,tx_hash:f.transaction}}p();function ho(e,t){if(e?.length)return e.find(r=>!t(r)?.toLowerCase().includes("driver"))??e[0]}function Xe(e){return e.replace(/([\\`*_{}\[\]()<>#+!|])/g,"\\$1")}function Au(e){return`${Xe(e.amount)} ${e.currency?Xe(e.currency):"currency unavailable"}`}function Wv(e,t){return[`${" ".repeat(t)}- ${Xe(e.label)}: ${Au(e.amount)}`,...(e.children??[]).flatMap(r=>Wv(r,t+1))]}function $v(e){let t=e.name.trim(),r=e.address.replace(/^[\s,;:–—-]+/u,"").trim();return Xe(t&&r&&t!==r?`${t} \u2014 ${r}`:t||r)}function vM(e){return e.replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\s/g,"%20")}function Jv(e){return new Set(e.flatMap(t=>[t.amount.currency,...Jv(t.children??[])]).filter(t=>!!t))}function Kv(e){let t=["# Ride receipt"];if(e.total&&t.push("","## Total fee charged",`**${Au(e.total)}**`),e.fareItems.length){t.push("","## Fare breakdown");for(let n of e.fareItems)t.push(...Wv(n,0))}let r=Jv(e.fareItems);if(e.total?.currency&&r.size===1&&!r.has(e.total.currency)){let n=[...r][0];t.push("",`> Currency conversion: fare is shown in ${Xe(n)} and the charge in ${Xe(e.total.currency)}${e.exchangeRate?`; exchange rate ${Xe(e.exchangeRate)}`:""}.`)}if(e.transactions?.length){t.push("","## Transactions");for(let n of e.transactions){let s=n.explorerUrl?`[${Xe(n.hash)}](${vM(n.explorerUrl)})`:Xe(n.hash),i=n.network?` (${Xe(n.network)})`:"",a=n.amount?` \u2014 ${Au(n.amount)}`:"";t.push(`- ${n.kind[0].toUpperCase()}${n.kind.slice(1)}${i}: ${s}${a}`)}}if(t.push("","\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","","## Ride details"),e.pickupAt){let n=e.dropoffAt&&e.dropoffAt!==e.pickupAt?`${e.pickupAt} ~ ${e.dropoffAt}`:e.pickupAt;t.push(`- Date and time: ${Xe(n)}`)}return e.rideType&&t.push(`- Ride type: ${Xe(e.rideType)}`),e.driverName&&t.push(`- Driver: ${Xe(e.driverName)}`),e.passengerName&&t.push(`- Passenger: ${Xe(e.passengerName)}`),t.push(`- Ride ID: ${Xe(e.rideId)}`),e.pickup&&t.push(`- Pickup: ${$v(e.pickup)}`),e.dropoff&&t.push(`- Destination: ${$v(e.dropoff)}`),e.paymentMethod&&t.push(`- Payment method: ${Xe(e.paymentMethod)}`),`${t.join(`
445
562
  `)}
446
- `}function Uc(e,t){return{label:e.displayName,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>Uc(r,t))}:{}}}function Eg(e){let t=fn(e.receiptBreakdown,d=>d.subtotalName),r=e.locations[0],n=e.locations.at(-1),s=e.receiptInfo?.paidNetwork??void 0,i=[],o=(d,u,m,p)=>{if(!m)return;let f=ut(u??null,m);i.push({kind:d,hash:m,...u?{network:u}:{},...f?{explorerUrl:f}:{},...p?{amount:p}:{}})};o("payment",s,e.receiptInfo?.paidTxHash,e.receiptInfo?{amount:e.receiptInfo.paidAmount,...e.receiptInfo.paidCurrency?{currency:e.receiptInfo.paidCurrency}:{}}:void 0),o("refund",e.refundReceiptInfo?.refundNetwork??s,e.refundReceiptInfo?.refundTxHash),o("tip",e.tipInfo?.tipRequest?.network??void 0,e.tipInfo?.tipRequest?.txHash,e.tipInfo?.tipRequest?.payAmount?{amount:e.tipInfo.tipRequest.payAmount,...e.tipInfo.tipRequest.payCurrency||e.tipInfo.tipCurrency?{currency:e.tipInfo.tipRequest.payCurrency??e.tipInfo.tipCurrency??void 0}:{}}:void 0);let a=["FINISHED","COMPLETED","REFUNDED"].includes(e.status.toUpperCase()),c=e.isFreeRide||["PAID","COMPLETED","FINISHED","REFUNDED","PARTIALLY_REFUNDED"].includes(e.receiptInfo?.receiptStatus?.toUpperCase()??""),l=e.receiptInfo?{amount:e.receiptInfo.paidAmount,...e.receiptInfo.paidCurrency?{currency:e.receiptInfo.paidCurrency}:{}}:e.isFreeRide?{amount:"0",...t?.currency?{currency:t.currency}:{}}:void 0;return{ready:a&&c,...l?{total:l}:{},fareItems:t?.fareItems.map(d=>Uc(d,t.currency))??[],...e.exchangeRate!=null?{exchangeRate:String(e.exchangeRate)}:{},...i.length?{transactions:i}:{},...e.rideDate?{pickupAt:e.rideDate}:{},...e.rideEndDate?{dropoffAt:e.rideEndDate}:{},...e.rideType?{rideType:e.rideType}:{},...e.driverInfo?.name?{driverName:e.driverInfo.name}:{},rideId:e.id,...r?{pickup:r}:{},...n?{dropoff:n}:{},...e.paymentMethod?{paymentMethod:e.paymentMethod}:{}}}var Bt=class{constructor(t,r,n,s=Ce){this.config=t;this.jwt=r;this.walletAddress=n;this.walletSigner=s;H(t.gatewayServerUrl),Oe(t.gatewayServerUrl),t.appServerUrl&&O(t.appServerUrl)}config;jwt;walletAddress;walletSigner;async searchRides(t){return Zr(t)}getCancelPenalty(t){throw new Be("getCancelPenalty: not supported in crypto mode (cancellation fee is reported on cancel via isFreeCancel)")}getCancelReasons(t){throw new Be("getCancelReasons: not supported in crypto mode")}getCards(t){throw new Be("Card list is only available for TADA/Throo members.")}async getTipConfig(t){let r=await oc(this.jwt,t),n=r.tipMetadata;return{enabled:!!r.enabled,minAmount:n?.minAmount??0,...n?.maxAmount!==void 0?{maxAmount:n.maxAmount}:{},currency:n?.currency??""}}async payTip(t,r){let{typed_data:n}=await mn({request_id:t,price:r.amount,wallet_address:this.walletAddress,config:this.config}),s=Buffer.from(this.config.passphrase,"utf8"),{wallet_signature:i}=await this.walletSigner({wallet_address:this.walletAddress,sign_method:"eth_signTypedData_v4",message:n},this.config,s),o=await gn({request_id:t,signature:i});return{tipStatus:o.success?"PAID":"FAILED",...o.tx_hash?{txHash:o.tx_hash}:{}}}async bookRide(t){let n=await en(t,this.config);return{rideId:n.request_id,price:n.price,currency:n.currency}}getRideStatus(t){return Ot(this.jwt,t)}async getReceipt(t){return Eg(await nn(this.jwt,t))}async getShareLink(t){let r=await Ot(this.jwt,t);if(!r.rideShareUrl)throw new ft("Share link is available after a driver is assigned.");return{url:r.rideShareUrl}}cancelRide(t,r,n){return Wr(this.jwt,t,r,n)}async sendChat(t,r){if(r.image)return Jr(this.jwt,t,r.image.buffer,r.image.mimetype);throw new Error("MvlBackend.sendChat: text-only HTTP send not implemented. Use the monitor chat-control socket (chat-monitor-client) for crypto-mode text.")}subscribeChat(t){return new dn(this.config,t,this.walletAddress)}getMessages(t,r){return Vr(t,this.jwt,r!=null?String(r):void 0)}};async function Qe(e,t,r,n,s,i){if(!e)throw new Error("TADA ride API: host required");let o=e.replace(/\/$/,""),a=await fetch(`${o}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...i},body:s!==void 0?JSON.stringify(s):void 0});if(!a.ok){let c=await a.text().catch(()=>"");throw ce(a.status,c)}return a.json()}function Rg(e){if(e)return{name:e.name,phone:e.phone,carModel:e.car_model??"",carPlate:e.car_plate??"",carColor:e.car_color,profilePhotoUrl:e.photo_url??""}}function Bc(e){let t=[];return e.pickup&&t.push(e.pickup),e.waypoints&&t.push(...e.waypoints),e.destination&&t.push(e.destination),{id:e.ride_id,status:e.ride_status,statusMessage:"",driverInfo:Rg(e.driver),locations:t,region:e.region,netPrice:e.net_price,payStatus:e.pay_status,tipAmount:e.tip_amount,riderName:e.rider_name}}function Ft(e,t,r){return Qe(e,"GET",`/v1/rides/${encodeURIComponent(r)}`,t)}function Ss(e,t,r){return Qe(e,"POST","/v1/products/search",t,r)}function Fc(e,t,r){return Qe(e,"POST","/v1/rides",t,r)}function $c(e,t,r,n){return Qe(e,"POST",`/v1/rides/${encodeURIComponent(r)}/cancel`,t,n)}function Hc(e,t,r,n){let s=n!=null?`?cancelReasonType=${n}`:"";return Qe(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-penalty${s}`,t)}function qc(e,t,r,n="en"){return Qe(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-reasons`,t,void 0,{"Accept-Language":n})}function jc(e){return{url:e.url,urlId:e.url_id,...e.message!=null?{message:e.message}:{},...e.chat_url!=null?{chatUrl:e.chat_url}:{}}}function Gc(e,t,r,n="en"){return Qe(e,"POST",`/v1/rides/${encodeURIComponent(r)}/share`,t,void 0,{"Accept-Language":n})}var bg={SEDAN:0,VAN:1,BUSINESS_VAN:4,EXECUTIVE_LARGE:8,BLACK_SEDAN:13,SUV:31,PREMIUM_SUV:33,SUV_LARGE:34,PREMIUM_SUV_LARGE:35,TAXI_STANDARD:1e4,TAXI_STANDARD_LARGE:10001,TAXI_PREMIUM:10002,TAXI_PREMIUM_LARGE:10003,WAV:4e4,WAV_LARGE:40001},Tg={PH:10,TAXI:11,ANYTADA:12,STUDENT:13,EV:14,TADAFAST:15,TADASAVER:16};function Wc(e){if(e!=null)return bg[e]}function Vc(e){if(e!=null)return Tg[e]}function Jc(e){return e?e.split("_").map(t=>t&&t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" "):""}async function Kc(e,t,r,n,s){if(!e)throw new Error("TADA tip API: host required");let i=e.replace(/\/$/,""),o=await fetch(`${i}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:s!==void 0?JSON.stringify(s):void 0});if(!o.ok){let a=await o.text().catch(()=>"");throw ce(o.status,a)}return o.json()}function Yc(e,t,r){return Kc(e,"GET",`/v1/rides/tip-config?region=${encodeURIComponent(r)}`,t)}function Xc(e,t,r,n){return Kc(e,"POST",`/v1/rides/${encodeURIComponent(r)}/tip`,t,n)}function zc(e){return{enabled:!!e.enabled,minAmount:e.min_amount??0,...e.max_amount&&e.max_amount>0?{maxAmount:e.max_amount}:{},currency:e.currency??"",...e.amount_presets?{presets:e.amount_presets}:{}}}function Qc(e){return{tipStatus:e.tip_status}}import{EventEmitter as Sg}from"events";async function Zc(e,t,r,n){let s=`${e}/v2/chat/${encodeURIComponent(r)}/messages`,i={Authorization:`Bearer ${t}`},o;if(n.image){let c={};n.message&&(c.message=n.message);let l=new FormData;l.append("dto",new Blob([JSON.stringify(c)],{type:"application/json"})),l.append("image",new Blob([new Uint8Array(n.image.buffer)],{type:n.image.mimetype}),"image"),o=l}else i["Content-Type"]="application/json",o=JSON.stringify({message:n.message});let a=await fetch(s,{method:"POST",headers:i,body:o});if(!a.ok)throw ce(a.status,await a.text().catch(()=>""));return a.json()}var el=10;async function As(e,t,r,n={}){let s=[];n.since!=null&&Number.isFinite(n.since)&&s.push(`since=${n.since}`),n.wait!=null&&s.push(`wait=${n.wait}`),n.limit!=null&&s.push(`limit=${n.limit}`);let i=`${e}/v2/chat/${encodeURIComponent(r)}/messages${s.length?`?${s.join("&")}`:""}`,o=n.signal??AbortSignal.timeout(((n.wait??0)+el)*1e3),a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o});if(!a.ok)throw ce(a.status,await a.text().catch(()=>""));return a.json()}var Ag=25,Ig=2e3;function xg(e){return new Promise(t=>setTimeout(t,e))}var _n=class extends Sg{constructor(r,n,s,i={}){super();this.host=r;this.jwt=n;this.rideId=s;this.wait=i.wait??Ag,this.backoffMs=i.backoffMs??Ig,this.since=i.startSince??i.nowMs??Date.now(),this.sleepFn=i.sleepFn??xg}host;jwt;rideId;stopped=!1;started=!1;controller;since;wait;backoffMs;sleepFn;connect(){this.started||(this.started=!0,this.loop())}disconnect(){this.stopped=!0,this.controller?.abort()}dispose(){this.disconnect()}async loop(){for(;!this.stopped;){let r=new AbortController;this.controller=r;let n=setTimeout(()=>r.abort(),(this.wait+el)*1e3);try{let s=await As(this.host,this.jwt,this.rideId,{since:this.since,wait:this.wait,signal:r.signal});if(this.stopped)break;for(let i of s.messages)i.sender_role!=="RIDER"&&this.emit("message",{data:{content:i.message??(i.file_url?"[image]":""),senderType:i.sender_role,file_url:i.file_url,message_id:i.message_id,created_at:i.created_at}});this.since=s.next_since??this.since}catch(s){if(this.stopped)break;this.emit("error",{message:s.message}),await this.sleepFn(this.backoffMs)}finally{clearTimeout(n)}}}};function tl(e,t){return{label:e.display_name,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>tl(r,t))}:{}}}function vg(e){let t=fn(e.receipt_breakdown,l=>l.subtotal_name),r=e.start_time??e.create_time,n=e.product_type??e.car_type,s=e.pickup,i=e.destination,o=["FINISHED","COMPLETED","REFUNDED"].includes(e.ride_status.toUpperCase()),a=e.net_price===0||["PAID","COMPLETED","FINISHED","REFUNDED","PARTIALLY_REFUNDED"].includes(e.pay_status?.toUpperCase()??""),c=t?.total_fare??e.net_price??e.ride_fare;return{ready:o&&a,...c!=null?{total:{amount:String(c),...e.currency?{currency:e.currency}:{}}}:{},fareItems:t?.fare_items.map(l=>tl(l,t.currency))??[],...r?{pickupAt:r}:{},...e.drop_off_time?{dropoffAt:e.drop_off_time}:{},...n?{rideType:n}:{},...e.driver?.name?{driverName:e.driver.name}:{},...e.rider_name?{passengerName:e.rider_name}:{},rideId:e.ride_id,...s?{pickup:s}:{},...i?{dropoff:i}:{},...e.payment_method?{paymentMethod:e.payment_method}:{}}}var $t=class{constructor(t,r,n,s){this.config=t;this.jwt=r;this.memberId=n;this.rideHost=s}config;jwt;memberId;rideHost;sgHost(){return ie("SG",this.config.cliGatewayHosts,this.config.cliGatewayHost)}hostForPickup(t){let r=t[0];if(!r)throw new Error("Cannot route a ride without a pickup location.");return ie(pt(r.latitude,r.longitude),this.config.cliGatewayHosts,this.config.cliGatewayHost)}followupHost(){return this.rideHost??this.sgHost()}async bookRide(t){let r=t,n=this.hostForPickup(r.locations),i=(await Ss(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid})).products.filter(l=>!l.na&&l.price_entry),o=r.productId!=null?i.find(l=>l.id===r.productId):i[0];if(!o||!o.price_entry)throw new Error("No bookable product for the given locations (check region / card).");let a=o.price_entry,c=await Fc(n,this.jwt,{locations:r.locations,product_id:o.id,ride_price:a.ride_price,currency:a.currency,payment_item_uuid:r.paymentItemUuid,...r.avoidToll?{avoid_toll:!0}:{},...r.riderNote?{rider_note:r.riderNote}:{}});return Er({request_id:c.ride_id,member_id:this.memberId,region:c.region??"",status:c.ride_status,price:c.net_price!=null?String(c.net_price):void 0,pay_currency:c.currency}),{rideId:c.ride_id,price:c.net_price,currency:c.currency}}async getRideStatus(t){return Bc(await Ft(this.followupHost(),this.jwt,t))}async getReceipt(t){let r=await Ft(this.followupHost(),this.jwt,t);return vg(r)}async searchRides(t){let r=t,n=this.hostForPickup(r.locations),s=await Ss(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid}),i=r.locations[0],o=Qr(pt(i.latitude,i.longitude));return{options:s.products.map(c=>{let l=c.na===!0||!c.price_entry;return{product_id:c.id,product_name:Xr(c.region,Vc(c.product_type),Wc(c.car_type),c.description_local??Jc(c.car_type)),price:l?null:String(c.price_entry.net_price),price_currency:l?null:c.price_entry.currency,na:l}}),routes:zr(s.routes,o)}}async cancelRide(t,r,n){return $c(this.followupHost(),this.jwt,t,{cancel_reason_type:n??null,cancel_reason:r??null})}getCancelPenalty(t,r){return Hc(this.followupHost(),this.jwt,t,r)}async getCancelReasons(t){return((await qc(this.followupHost(),this.jwt,t)).reasons??[]).map(n=>({id:n.reason_id,title:n.title}))}async getShareLink(t,r="en"){return jc(await Gc(this.followupHost(),this.jwt,t,r))}getCards(t){return Tc(t,this.jwt)}hostForRegion(t){return ie(we(t),this.config.cliGatewayHosts,this.config.cliGatewayHost)}async getTipConfig(t){return zc(await Yc(this.hostForRegion(t),this.jwt,t))}async payTip(t,r){if(!r.paymentItemUuid)throw new Error("NO_CARD: member tip requires a payment_item_uuid (card).");let n={amount:r.amount,currency:r.currency??"",payment_item_uuid:r.paymentItemUuid};return Qc(await Xc(this.followupHost(),this.jwt,t,n))}sendChat(t,r){return Zc(this.followupHost(),this.jwt,t,r)}subscribeChat(t){return new _n(this.followupHost(),this.jwt,t)}getMessages(t,r){return As(this.followupHost(),this.jwt,t,{since:r})}};async function te(e,t){if(t.wallet_address){let o=P(t.wallet_address);if(!o)throw new Error("JWT_NOT_FOUND: no valid wallet JWT. Run siwe-request-message + siwe-submit first.");return{backend:new Bt(e,o,t.wallet_address),jwt:o,identity:t.wallet_address,mode:"wallet"}}Ue(ee(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await an(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member_id??"",i=ie(we(t.region),e.cliGatewayHosts,e.cliGatewayHost);return{backend:new $t(e,n,s,i),jwt:n,identity:s,mode:"tada"}}async function Ht(e){let t=K();if(t.mode==="wallet"){let r=t.walletAddress;if(!r)throw new Error("No registered wallet. Run wallet setup first.");let n=P(r);if(!n)throw new Error("JWT_NOT_FOUND: no valid wallet JWT. Run siwe-request-message + siwe-submit first.");return{backend:new Bt(e,n,r),jwt:n,identity:r,mode:"wallet"}}if(t.mode==="tada"){Ue(ee(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await an(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member?.id??"";return{backend:new $t(e,n,s),jwt:n,identity:s,mode:"tada"}}throw new Error("No active account. Run `amb login` (TADA/Throo member) or wallet setup (crypto) first.")}async function Fe(e){Ue(ee(e.cliGatewayHosts,e.cliGatewayHost));let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},r=await an(t);if(!r)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");return r}function ge(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return null}var rl=["lat_lng","locationPoint"];function Ng(e){if(e==null||typeof e!="object")return null;let t=rl.map(i=>e[i]).find(i=>i!=null&&typeof i=="object"),r=ge(e.latitude)??ge(e.lat)??ge(t?.latitude),n=ge(e.longitude)??ge(e.lng)??ge(t?.longitude);if(r==null||n==null)return null;let s={...e};for(let i of["latitude","longitude","lat","lng",...rl])delete s[i];return{...s,latitude:r,longitude:n}}function nl(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){let n=Ng(r);if(n==null)return null;t.push(n)}return t}var kg=new Set(["ASSIGNED","PICKUP","PICKUP_ARRIVED"]),Cg=new Set(["INUSE","INUSE_WITH_CANCEL_PENDING"]),Dg=new Set(["PAYCONFIRMED","PENDING","ASSIGNED","PICKUP","PICKUP_ARRIVED"]);function yn(e){let{status:t,mode:r,supportsReasons:n,hasReasonType:s}=e;return Ie(t)?{kind:"not_cancelable",why:`ride already ended (${t})`}:Cg.has(t)?{kind:"not_cancelable",why:`ride is in progress (${t}) \u2014 it cannot be cancelled`}:r==="crypto"&&!Dg.has(t)?{kind:"not_cancelable",why:`ride cannot be cancelled in status ${t}`}:kg.has(t)&&n&&!s?{kind:"needs_reason"}:{kind:"immediate"}}var Pg=async e=>{let t=R();if(b(t.dataDir),K().mode==="tada"){let[d,u,m,p,f]=e;(!d||!u||!m||!p)&&(console.error("error: Usage:"),console.error(" [crypto] amb ride-search <wallet_address> <region> <origin_lat> <origin_lng> <dest_lat> <dest_lng>"),console.error(" [member] amb ride-search <origin_lat> <origin_lng> <dest_lat> <dest_lng> [card_uuid]"),console.error("hint: card_uuid is optional \u2014 the default/only card is auto-selected when omitted."),process.exit(1));let _=ge(d),h=ge(u),I=ge(m),E=ge(p);if(_==null||h==null||I==null||E==null){g({error:"INVALID_COORDINATES",message:"origin/destination lat and lng must all be numbers."}),process.exit(1);return}let A;try{A=await Ht(t)}catch(U){g({error:U.message}),process.exit(1);return}let N=ie(pt(_,h),t.cliGatewayHosts,t.cliGatewayHost),C=await Mt(A.backend,f,N);if(C==null)return;try{let U=await A.backend.searchRides({locations:[{latitude:_,longitude:h},{latitude:I,longitude:E}],paymentItemUuid:C});w(U)}catch(U){g({error:U.message}),process.exit(1)}return}let[s,i,o,a,c,l]=e;(!s||!i||!o||!a||!c||!l)&&(console.error("error: Usage:"),console.error(" [crypto] amb ride-search <wallet_address> <region> <origin_lat> <origin_lng> <dest_lat> <dest_lng>"),console.error(" [member] amb ride-search <origin_lat> <origin_lng> <dest_lat> <dest_lng> <card_uuid>"),console.error("hint: region: SG (Singapore), NY (New York)"),process.exit(1)),k(s),$(s),O(t.appServerUrl),H(t.gatewayServerUrl);try{let d=await Zr({wallet_address:s,region:i,locations:[{latitude:parseFloat(o),longitude:parseFloat(a)},{latitude:parseFloat(c),longitude:parseFloat(l)}],payCurrency:t.payCurrency});w(d)}catch(d){g({error:d.message}),process.exit(1)}},Lg=async e=>{let t=R();if(b(t.dataDir),K().mode==="tada"){let c=e[0];c||(console.error("error: Usage: amb ride-request <json_params>"),console.error('hint: [member] json_params: {"locations":[...], "payment_item_uuid":"<uuid, optional \u2014 auto-selected if omitted>", "product_id":<optional>}'),process.exit(1));let l;try{l=JSON.parse(c)}catch{g({error:"INVALID_JSON",message:"Failed to parse json_params argument."}),process.exit(1);return}let d=l.locations,u=l.payment_item_uuid,m=l.product_id;if(!d||d.length===0){g({error:"MISSING_FIELD",message:"locations is required in json_params (member mode) and must contain [origin, destination]."}),process.exit(1);return}let p;try{p=await Ht(t)}catch(E){g({error:"RIDE_REQUEST_FAILED",message:E.message}),process.exit(1);return}let f=nl(d);if(f==null){g({error:"INVALID_COORDINATES",message:"Every entry in locations needs numeric coordinates (latitude/longitude, or lat/lng)."}),process.exit(1);return}let _=f[0],h=ie(pt(_.latitude,_.longitude),t.cliGatewayHosts,t.cliGatewayHost),I=await Mt(p.backend,u,h);if(I==null)return;try{let E=await p.backend.bookRide({locations:f,paymentItemUuid:I,...m!=null?{productId:m}:{}});await xe(E.rideId),w(E)}catch(E){g({error:"RIDE_REQUEST_FAILED",message:E.message}),process.exit(1)}return}let s=e[0];s||(console.error("error: Usage: amb ride-request <json_params>"),console.error("hint: see references/ride.md for the full json_params schema"),process.exit(1));let i;try{i=JSON.parse(s)}catch{g({error:"INVALID_JSON",message:"Failed to parse json_params argument."}),process.exit(1);return}let o=i.wallet_address,a=i.rider?.phone;if(!o){g({error:"MISSING_FIELD",message:"wallet_address is required in json_params."}),process.exit(1);return}if(k(o),$(o),a&&!eo(o,a)){g({error:"PHONE_NOT_VERIFIED",message:`Phone ${a} is not verified.`,action:"Run `amb phone-verify-start` + `amb phone-verify-confirm` first."}),process.exit(1);return}O(t.appServerUrl),H(t.gatewayServerUrl);try{let c=await en(i,t);await xe(c.request_id),w(c)}catch(c){let l=c.message??"";l.toLowerCase().includes("deposit")||l.toLowerCase().includes("collateral")?g({error:"INSUFFICIENT_DEPOSIT",message:l,action:"Run `amb deposit-status` to identify the network, then `amb deposit-add <wallet> <network> <token> <amount>`."}):g({error:"RIDE_REQUEST_FAILED",message:l,action:"Run `amb deposit-status` + `amb wallet-balance` to diagnose."}),process.exit(1)}};function il(e){let t=[],r;for(let n=0;n<e.length;n++){let s=e[n],i="--reason-type=";if(s==="--reason-type"||s.startsWith(i)){let o=s.startsWith(i)?s.slice(i.length):e[++n];(o==null||!/^\d+$/.test(o))&&(g({error:"INVALID_ARGUMENT",message:`--reason-type must be an integer id (got: ${o??"<missing>"}). Get valid ids from the cancel_pending reasons list.`}),process.exit(1)),r=parseInt(o,10)}else t.push(s)}return{positional:t,reasonType:r}}async function ol(e,t,r,n){let s=await e.getCancelReasons(t),i;if(n==="member")try{i=await e.getCancelPenalty(t)}catch{}w({cancel_pending:!0,ride_status:r,reasons:s,...i?.cancellation_fee!=null?{cancellation_fee:i.cancellation_fee,cancellation_fee_currency:i.cancellation_fee_currency,fee_varies_by_reason:!0}:{},message:n==="member"?"Ride is NOT cancelled yet. Show these reasons to the rider, let them pick one, then re-run with --reason-type <id>. Do not pick a reason on the rider's behalf. The fee shown is the default \u2014 it can differ by reason (re-check with `amb ride-cancel-penalty <request_id> --reason-type <id>`).":"Ride is NOT cancelled yet. Show these reasons to the rider, let them pick one, then re-run with --reason-type <id>. Do not pick a reason on the rider's behalf. The cancellation fee is reported after cancelling (isFreeCancel)."})}async function sl(e,t,r,n){return await ol(e,t,r,n),{kind:"done"}}async function Og(e,t,r,n,s,i){let o;try{o=await e.cancelRide(t,r,n)}catch(l){if(!(l instanceof Y))throw l;if(l.status===409&&l.code==="ride_cancel_not_allowed"){let d=await e.getRideStatus(t),u=yn({status:d.status,mode:s,supportsReasons:i,hasReasonType:n!=null});return u.kind==="needs_reason"?sl(e,t,d.status,s):u.kind==="not_cancelable"?{kind:"not_cancelable",why:u.why,status:d.status}:{kind:"hold",status:d.status}}if(l.status===400&&l.code==="invalid_parameter"&&n!=null&&i){let d=await e.getRideStatus(t),u=yn({status:d.status,mode:s,supportsReasons:i,hasReasonType:!1});return u.kind==="not_cancelable"?{kind:"not_cancelable",why:u.why,status:d.status}:sl(e,t,d.status,s)}return{kind:"failed",message:l.message}}let a=o,c=s==="member"?a?.ride_status??"USER_CANCELED":a?.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED";return Ve(t,c),w(o),{kind:"done"}}var Mg=async e=>{let{positional:t,reasonType:r}=il(e),n=t[0];n||(console.error("error: Usage: amb ride-cancel <request_id> [wallet_address] [reason] [--reason-type <id>]"),process.exit(1));let s=R();b(s.dataDir),await xe(n);let i=V(n);if(i?.status?.startsWith("EXPIRED")&&(w({already_expired:!0,status:i.status,message:"Ride has already expired. No active ride to cancel."}),process.exit(0)),i){let d=i.wallet_address?"crypto":"member",u=d==="crypto"?t[2]:t[1],m=d==="member",p;try{let{backend:f}=await te(s,i),_=await f.getRideStatus(n),h=yn({status:_.status,mode:d,supportsReasons:m,hasReasonType:r!=null});h.kind==="not_cancelable"?p={kind:"not_cancelable",why:h.why,status:_.status}:h.kind==="needs_reason"?(await ol(f,n,_.status,d),p={kind:"done"}):p=await Og(f,n,u,r,d,m)}catch(f){p={kind:"failed",message:f.message}}if(p.kind==="done")return;if(p.kind==="not_cancelable"){g({error:"RIDE_NOT_CANCELABLE",message:p.why,status:p.status}),process.exit(1);return}if(p.kind==="hold"){g({error:"RIDE_CANCEL_FAILED",message:"the payment is being held \u2014 retry in a moment",status:p.status}),process.exit(1);return}g({error:"RIDE_CANCEL_FAILED",message:p.message}),process.exit(1);return}let o=t[1],a=t[2],c=o;if(!c){g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}. Provide wallet_address as 2nd argument.`}),process.exit(1);return}k(c),$(c),O(s.appServerUrl),H(s.gatewayServerUrl);let l=P(c);if(!l){g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let d=await Wr(l,n,a,r);Ve(n,d.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED"),w(d)}catch(d){g({error:"RIDE_CANCEL_FAILED",message:d.message}),process.exit(1)}},Ug=async e=>{let t=e[0],r=e[1];t||(console.error("error: Usage: amb ride-status <request_id> [wallet_address]"),process.exit(1));let n=R();b(n.dataDir),await xe(t);let s=V(t);if(s){try{let{backend:a}=await te(n,s),c=await a.getRideStatus(t);Ve(t,c.status),w(c)}catch(a){g({error:"RIDE_STATUS_FAILED",message:a.message}),process.exit(1)}return}let i=r;if(!i){g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}. Provide wallet_address as 2nd argument.`}),process.exit(1);return}k(i),$(i),O(n.appServerUrl),H(n.gatewayServerUrl);let o=P(i);if(!o){g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let a=await Ot(o,t);Ve(t,a.status),w(a)}catch(a){g({error:"RIDE_STATUS_FAILED",message:a.message}),process.exit(1)}},Bg=async e=>{let{positional:t,reasonType:r}=il(e),n=t[0];if(!n){console.error("error: Usage: amb ride-cancel-penalty <request_id> [--reason-type <id>]"),process.exit(1);return}let s=R();b(s.dataDir);let i=V(n);if(!i){g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}try{let{backend:o}=await te(s,i),a=await o.getCancelPenalty(n,r);w(a)}catch(o){o instanceof Be?g({error:"NOT_SUPPORTED",message:"Cancellation fee pre-check is TADA/Throo member-mode only; in crypto mode the fee is reported on cancel (isFreeCancel)."}):g({error:"RIDE_CANCEL_PENALTY_FAILED",message:o.message??""}),process.exit(1)}},Fg=async e=>{let t="en",r=[];for(let o=0;o<e.length;o++){let a=e[o];a==="--lang"&&e[o+1]!=null?t=e[++o]:r.push(a)}let n=r[0];if(!n){console.error("error: Usage: amb ride-share <request_id> [--lang TAG]"),process.exit(1);return}let s=R();b(s.dataDir);let i=V(n);if(!i){g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}try{let{backend:o}=await te(s,i),a=await o.getShareLink(n,t);w(a)}catch(o){if(o instanceof ft){g({error:o.code,message:o.message}),process.exit(1);return}g({error:"SHARE_LINK_FAILED",message:o.message}),process.exit(1)}},$g=async e=>{let[t,r]=e,n=r?parseInt(r,10):20;t||(console.error("error: Usage: amb ride-history <wallet_address> [limit]"),console.error("hint: limit: max history entries (default 20)"),process.exit(1));let s=R();b(s.dataDir),k(t),$(t),Oe(s.gatewayServerUrl);let i=P(t);if(!i){g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let o=await dc(i,n);w(o)}catch(o){g({error:"RIDE_HISTORY_FAILED",message:o.message}),process.exit(1)}};function Hg(e,t){let r=V(t);return r?.region?ie(we(r.region),e.cliGatewayHosts,e.cliGatewayHost):e.cliGatewayHost}function qg(e){if(!e.ready){g({error:"RECEIPT_NOT_READY",message:"Receipt settlement is still pending. Please try again shortly."}),process.exitCode=75;return}console.log(Mc(e))}var jg=async e=>{let t=e.filter(c=>c.startsWith("--format"));if(t.length>1||t[0]&&t[0]!=="--format=markdown"||wt()==="json"){g({error:"INVALID_RECEIPT_OPTIONS",message:"ride-receipt emits Markdown; '--format=markdown' is optional and --json is not supported."}),process.exit(1);return}let r=e.filter(c=>!c.startsWith("--format"));if(r.length!==1){g({error:"INVALID_RECEIPT_USAGE",message:"Usage: amb ride-receipt <request_id>. For raw detail, use ride-history-detail."}),process.exit(1);return}let n=r[0],s=R();b(s.dataDir);let i=V(n);if(!i){g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}let o=hc(),a=i.wallet_address?"wallet":"tada";if(o&&o!==a){g({error:"RECEIPT_ACCOUNT_CONFLICT",message:`This ride belongs to the ${a} account; remove --account=${o}.`}),process.exit(1);return}try{let{backend:c}=await te(s,i);qg(await c.getReceipt(n))}catch(c){g({error:"RIDE_RECEIPT_FAILED",message:c.message}),process.exit(1)}},Gg=async e=>{if(K().mode==="tada"){let[o]=e;if(!o){console.error("error: Usage: amb ride-history-detail <request_id>"),process.exit(1);return}let a=R();b(a.dataDir);let c;try{c=await Fe(a)}catch(l){g({error:"MEMBER_SESSION_EXPIRED",message:l.message}),process.exit(1);return}try{let l=await Ft(Hg(a,o),c,o);w(l)}catch(l){g({error:"RIDE_HISTORY_DETAIL_FAILED",message:l.message}),process.exit(1)}return}let[r,n]=e;(!r||!n)&&(console.error("error: Usage: amb ride-history-detail <wallet_address> <request_id>"),process.exit(1));let s=R();b(s.dataDir),k(r),$(r),Oe(s.gatewayServerUrl);let i=P(r);if(!i){g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let o=await nn(i,n);if(wt()==="plain"){let a=o.receiptInfo?.paidNetwork??null,c={...o},l=ut(a,o.receiptInfo?.paidTxHash??null);if(l&&(c.receiptInfo={...o.receiptInfo,explorerUrl:l}),o.refundReceiptInfo){let u=ut(o.refundReceiptInfo.refundNetwork??a,o.refundReceiptInfo.refundTxHash);c.refundReceiptInfo=u?{...o.refundReceiptInfo,explorerUrl:u}:o.refundReceiptInfo}let d=o.tipInfo?.tipRequest?.txHash??null;if(d){let u=ut(o.tipInfo?.tipRequest?.network??null,d);u&&o.tipInfo&&(c.tipInfo={...o.tipInfo,tipRequest:{...o.tipInfo.tipRequest,explorerUrl:u}})}w(c)}else w(o)}catch(o){g({error:"RIDE_HISTORY_DETAIL_FAILED",message:o.message}),process.exit(1)}},al={"ride-search":Pg,"ride-request":Lg,"ride-cancel":Mg,"ride-status":Ug,"ride-cancel-penalty":Bg,"ride-share":Fg,"ride-history":$g,"ride-history-detail":Gg,"ride-receipt":jg};function Wg(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function cl(e){let{request_id:t,wallet_address:r,config:n}=e,s=Wg(r),{accepts:i,nonce:o}=await Ya(s,t),a=i[0],c=String(Math.floor(Date.now()/1e3)+a.maxTimeoutSeconds),l=parseInt(a.network.split(":")[1],10),d={domain:{name:a.extra.name,version:a.extra.version,chainId:l,verifyingContract:a.asset},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"TransferWithAuthorization",message:{from:r,to:a.payTo,value:a.amount,validAfter:"0",validBefore:c,nonce:o}},{typed_data:u,isSmartAccount:m}=await un({rawTypedData:d,walletAddress:r,target:{rpcUrl:n.paymentRpcUrl,chainId:l}});return Kr(t,{accepts:i,nonce:o,walletAddress:r,validBefore:c,expiresAt:Date.now()+a.maxTimeoutSeconds*1e3,isSmartAccount:m}),{typed_data:u}}function Vg(e){let t=j(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function ll(e){let{request_id:t,signature:r}=e,n=Yr(t);if(!n)throw new Error("PAYMENT_CACHE_MISS: request_id not found or expired. Call ride_pay_prepare again.");let{accepts:s,nonce:i,walletAddress:o,validBefore:a,isSmartAccount:c}=n,l=Vg(o),d=s[0],u={x402Version:2,accepted:d,payload:{authorization:{from:o,to:d.payTo,value:d.amount,validAfter:"0",validBefore:a,nonce:i},signature:pn(r,c===!0)}},m=Buffer.from(JSON.stringify(u)).toString("base64"),p=await Xa(l,t,m);return{success:p.success,tx_hash:p.transaction}}var Jg=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb ride-pay-prepare <request_id> <wallet_address>"),process.exit(1));let n=R();b(n.dataDir),k(r),$(r),O(n.appServerUrl),H(n.gatewayServerUrl);try{let s=await cl({request_id:t,wallet_address:r,config:n});w(s)}catch(s){g({error:s.message}),process.exit(1)}},Kg=async e=>{let[t,r,...n]=e;(!t||!r||n.length>0)&&(console.error("error: Usage: amb ride-pay-confirm <request_id> <signature>"),console.error("hint: signature: hex from `amb wallet-sign` with sign_method=eth_signTypedData_v4"),n.length>0&&console.error(`error: unexpected extra argument(s): ${n.join(" ")}`),process.exit(1)),/^0x[0-9a-fA-F]{100,}$/.test(r)||(console.error("error: signature looks too short to be a valid hex signature (got length "+r.length+")"),console.error("hint: pass the wallet_signature returned by `amb wallet-sign`, not the wallet address"),process.exit(1));let s=R();b(s.dataDir),O(s.appServerUrl),H(s.gatewayServerUrl);try{let i=await ll({request_id:t,signature:r});w(i)}catch(i){let o=i.message??"";o.toLowerCase().includes("insufficient")||o.toLowerCase().includes("balance")?g({error:"INSUFFICIENT_BALANCE",message:o,action:"Run `amb wallet-balance` and top up your wallet."}):g({error:"RIDE_PAY_CONFIRM_FAILED",message:o,action:"Check `amb wallet-balance` for wallet balance."}),process.exit(1)}},dl={"ride-pay-prepare":Jg,"ride-pay-confirm":Kg};function Yg(e){let t=[],r,n;for(let s=0;s<e.length;s++)e[s]==="--currency"&&e[s+1]!=null?r=e[++s]:e[s]==="--card"&&e[s+1]!=null?n=e[++s]:t.push(e[s]);return{positionals:t,currency:r,card:n}}var Xg=async e=>{let t=e[0];if(!t){console.error("error: Usage: amb tip-config <region>"),console.error("hint: region: SG (Singapore), NY (New York). Member mode resolves the active account; crypto uses the registered wallet."),process.exit(1);return}let r=R();b(r.dataDir);let n;try{n=await Ht(r)}catch(s){g({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1);return}try{w(await n.backend.getTipConfig(t))}catch(s){g({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1)}},zg=async e=>{let{positionals:t,currency:r,card:n}=Yg(e),[s,i]=t,o=i?parseFloat(i):NaN;if(!s||Number.isNaN(o)){console.error("error: Usage: amb tip <ride_id> <amount> [--currency C] [--card uuid]"),console.error("hint: amount within the tip-config min/max. Member: card auto-selected if --card omitted; crypto: pays from the wallet."),process.exit(1);return}let a=R();b(a.dataDir);let c=V(s);if(!c){g({error:"RIDE_NOT_FOUND",message:`No local record for ride_id: ${s}.`}),process.exit(1);return}let l;try{l=await te(a,c)}catch(f){g({error:"TIP_FAILED",message:f.message}),process.exit(1);return}let{backend:d,mode:u}=l,m=r,p;if(u==="tada"){let f;try{f=await d.getTipConfig(c.region)}catch(I){g({error:"TIP_CONFIG_FAILED",message:I.message}),process.exit(1);return}if(!f.enabled){g({error:"TIP_NOT_AVAILABLE",message:"Tipping is not available for this ride/region."}),process.exit(1);return}m=r??f.currency;let _=ie(we(c.region),a.cliGatewayHosts,a.cliGatewayHost),h=await Mt(d,n,_);if(h==null)return;p=h}try{let f=await d.payTip(s,{amount:o,currency:m,paymentItemUuid:p});w(f)}catch(f){if(f instanceof Y)f.code==="tip_not_available"?g({error:"TIP_NOT_AVAILABLE",message:"Tipping is not available yet. The fare may still be settling (try again in a moment), or the tip window has passed / the region is disabled."}):f.code==="tip_already_paid"?g({error:"TIP_ALREADY_PAID",message:"This ride has already been tipped."}):f.status===402?g({error:"TIP_PAYMENT_FAILED",message:"Payment failed. Check the card and try again."}):f.status===400?g({error:"TIP_AMOUNT_INVALID",message:"Tip amount is outside the allowed range. Run `amb tip-config <region>`."}):f.status===401||f.code==="unauthorized"?g({error:"SESSION_EXPIRED",message:"Your TADA/Throo session expired. Run `amb login` again."}):g({error:"TIP_FAILED",message:f.message});else{let _=f.message??"";_.toLowerCase().includes("insufficient")||_.toLowerCase().includes("balance")?g({error:"INSUFFICIENT_BALANCE",message:_,action:"Run `amb wallet-balance` and top up your wallet."}):g({error:"TIP_FAILED",message:_})}process.exit(1)}},Qg=async e=>{let[t,r,n]=e,s=r?parseFloat(r):NaN;(!t||isNaN(s)||!n)&&(console.error("error: Usage: amb tip-prepare <request_id> <price> <wallet_address>"),process.exit(1));let i=R();b(i.dataDir),k(n),$(n),H(i.gatewayServerUrl),Oe(i.gatewayServerUrl);try{let o=await mn({request_id:t,price:s,wallet_address:n,config:i});w(o)}catch(o){g({error:"TIP_PREPARE_FAILED",message:o.message}),process.exit(1)}},Zg=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb tip-confirm <request_id> <signature>"),console.error("hint: signature: hex from `amb wallet-sign` with sign_method=eth_signTypedData_v4"),process.exit(1));let n=R();b(n.dataDir),Oe(n.gatewayServerUrl);try{let s=await gn({request_id:t,signature:r});w(s)}catch(s){let i=s.message??"";i.includes("PAYMENT_CACHE_MISS")?g({error:"PAYMENT_CACHE_MISS",message:i,action:"Session expired. Run `amb tip-prepare` again."}):i.toLowerCase().includes("insufficient")||i.toLowerCase().includes("balance")?g({error:"INSUFFICIENT_BALANCE",message:i,action:"Run `amb wallet-balance` and top up your wallet."}):g({error:"TIP_CONFIRM_FAILED",message:i}),process.exit(1)}},ul={"tip-config":Xg,tip:zg,"tip-prepare":Qg,"tip-confirm":Zg};var ml=new Set(["maps.app.goo.gl","goo.gl"]),ef=new Set(["www.google.com","google.com","maps.google.com"]),pl=5;function $e(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function tf(e){let t=e;for(let r=0;r<pl;r++){let n=new URL(t);if(!ml.has(n.host))return t;let s;try{s=await fetch(t,{redirect:"manual",method:"HEAD"})}catch(i){$e("URL_RESOLVE_FAILED",i.message)}if(s.status>=300&&s.status<400){let i=s.headers.get("location");i||$e("URL_RESOLVE_FAILED","redirect status without Location header"),t=new URL(i,t).toString();continue}$e("URL_RESOLVE_FAILED",`unexpected status ${s.status} on short link`)}$e("URL_RESOLVE_FAILED",`redirect chain exceeded ${pl}`)}function rf(e){let t=e.match(/\/maps\/place\/([^/]+)/);if(!t)return;let r=decodeURIComponent(t[1].replace(/\+/g," ")),n=r.indexOf(",");return(n>=0?r.slice(0,n):r).trim()}function nf(e){let t=e.match(/!3d(-?\d+(?:\.\d+)?)!4d(-?\d+(?:\.\d+)?)/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function sf(e){let t=e.match(/\/@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function of(e){let t=e.match(/!1s(0x[0-9a-fA-F]+:0x[0-9a-fA-F]+)/);return t?t[1]:void 0}async function Is(e){let t;try{t=new URL(e)}catch{$e("INVALID_URL","not a parseable URL")}if(ml.has(t.host)){let o=await tf(e);return Is(o)}ef.has(t.host)||$e("INVALID_URL",`host ${t.host} not in allowlist`);let r=t.pathname,n=nf(r)??sf(r);n||$e("COORDS_NOT_FOUND_IN_URL");let s=rf(r)??$e("INVALID_URL","no /place/<name>/ segment"),i=of(r);return{name:s,latitude:n.lat,longitude:n.lng,...i&&{ftid:i}}}var xs="";function gl(e){xs=e.replace(/\/$/,"")}function _t(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function fl(e,t){xs||_t("RESOLVE_FAILED","initSavedPlacesApi not called");let r=await fetch(`${xs}/v1/places/resolve-google`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)try{return await r.json()}catch(n){_t("RESOLVE_FAILED",`malformed JSON response: ${n.message}`)}r.status===404&&_t("PLACE_NOT_FOUND"),r.status===422&&_t("REGION_UNSUPPORTED"),r.status===401&&_t("JWT_EXPIRED"),_t("RESOLVE_FAILED",`status ${r.status}`)}function af(e){if(!e)return null;let t=e.match(/^0x[0-9a-fA-F]+:0x([0-9a-fA-F]+)$/);if(!t)return null;try{return BigInt("0x"+t[1])}catch{return null}}function cf(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=Buffer.from(r,"base64");if(n.length<8)throw new Error("place_id too short");let s=0n;for(let i=0;i<8;i++)s|=BigInt(n[n.length-8+i])<<BigInt(8*i);return s}async function _l(e){let t=af(e);if(t===null)return null;let s=`https://www.google.com/maps/preview/place?hl=en&gl=us&pb=${`!1m4!1s${`0x0%3A0x${t.toString(16)}`}!3m2!2m1!1i1`}`;try{let i=await fetch(s,{headers:{"User-Agent":"Mozilla/5.0"}});if(!i.ok)return null;let a=(await i.text()).match(/ChI[A-Za-z0-9_-]{15,}/g)??[];for(let c of a)try{if(cf(c)===t)return c}catch{}return null}catch{return null}}function yl(e,t,r){return Me("/v1/places",e,{query:{query:t.query,region:t.region,city:t.city,originLat:t.originLat,originLng:t.originLng,sessionToken:t.sessionToken},lang:r})}function hl(e,t,r,n){return Me(`/v1/places/${encodeURIComponent(t)}`,e,{query:{region:r.region,city:r.city},lang:n})}function wl(e,t,r){return Me("/v1/places/nearby",e,{query:{latitude:t.latitude,longitude:t.longitude,limit:t.limit},lang:r})}function El(e,t,r){return Me("/v1/places/airports",e,{query:{city:t.city},lang:r})}function Rl(e,t,r){return Me("/v1/places/reverse-geocode",e,{query:{latitude:t.latitude,longitude:t.longitude,region:t.region},lang:r})}function qt(e){let t=[],r,n,s;for(let i=0;i<e.length;i++){let o=e[i];o==="--city"&&e[i+1]!=null?r=e[++i]:o==="--session-token"&&e[i+1]!=null?n=e[++i]:o==="--lang"&&e[i+1]!=null?s=e[++i]:t.push(o)}return{positional:t,city:r,sessionToken:n,lang:s}}function jt(e){switch(e.code){case"unsupported_region":return"Region not supported (currently NY, SG). Re-run with a supported region.";case"place_not_found":return"Place not found. Check the place id or coordinates and try again.";case"invalid_parameter":return"Invalid parameter. Check the query, region, or coordinates.";case"place_api_error":return"Place search is temporarily unavailable. Please try again.";default:return e.message}}function vs(e){g({error:"NOT_SUPPORTED",message:`tada ${e} is only available for TADA/Throo members. Run 'amb login' first.`}),process.exit(1)}var lf=async e=>{if(K().mode==="tada"){let{positional:u,city:m,sessionToken:p,lang:f}=qt(e),[_,h,I,E]=u;(!_||!h)&&(console.error("error: Usage: amb place-search <query> <region> [originLat originLng] [--city CODE] [--session-token UUID] [--lang TAG]"),console.error("hint: region: NY, SG. multi-word query is quoted."),process.exit(1)),I!==void 0!=(E!==void 0)&&(g({error:"INVALID_COORDINATES",message:"originLat and originLng must be provided together."}),process.exit(1));let A=I!==void 0?parseFloat(I):void 0,N=E!==void 0?parseFloat(E):void 0;(A!==void 0&&isNaN(A)||N!==void 0&&isNaN(N))&&(g({error:"INVALID_COORDINATES",message:"originLat and originLng must be valid numbers."}),process.exit(1));let C=R();b(C.dataDir),gt(ee(C.cliGatewayHosts,C.cliGatewayHost));let U;try{U=await Fe(C)}catch(re){g({error:"MEMBER_AUTH_FAILED",message:re.message}),process.exit(1);return}try{let re=await yl(U,{query:_,region:h,city:m,originLat:A,originLng:N,sessionToken:p},f);w({...re,next_action:"PICK_A_PLACE_THEN_BUILD_RIDE_LOCATIONS",must:"Copy place_id / sub_places[].id / lat_lng / name / address verbatim from this response. Never fabricate them. A Google candidate with lat_lng:null must be resolved via place-detail before booking."})}catch(re){g({error:"PLACE_SEARCH_FAILED",message:jt(re)}),process.exit(1)}return}let t=e[0],r=e[1],n=e[2],s=e[3],i=e[4];(!t||!r||!n)&&(console.error("error: Usage: amb place-search <wallet_address> <city> <query> [latitude] [longitude]"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let o=Lt(r);o||(g({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${r}". Use codes like SIN, BKK, DEN or full names like Singapore, Bangkok, Denver.`}),process.exit(1));let a=s!==void 0?parseFloat(s):void 0,c=i!==void 0?parseFloat(i):void 0;s!==void 0!=(i!==void 0)&&(g({error:"INVALID_COORDINATES",message:"latitude and longitude must both be provided together."}),process.exit(1)),(s!==void 0&&isNaN(a)||i!==void 0&&isNaN(c))&&(g({error:"INVALID_COORDINATES",message:"latitude and longitude must be valid numbers."}),process.exit(1));let l=R();b(l.dataDir),k(t),$(t),O(l.appServerUrl),H(l.gatewayServerUrl);let d=P(t);d||(g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let u=await za(d,n,o,a,c);u.length===0?w({results:[],next_action:"REPORT_NO_MATCHES_TO_USER"}):w({results:u,next_action:"ASK_USER_TO_PICK_ONE_RESULT",must:"placeId passed to any subsequent command (amb place-detail, amb map-session-create, amb ride-request) MUST be a value taken verbatim from results[].placeId of this response. NEVER fabricate or substitute a place ID from any external system or from your own model knowledge. If a chosen result has subPlaces, amb map-session-create + amb map-session-verify is mandatory and the user must pick a subPlace on the map \u2014 do NOT enumerate subPlaces as text."})}catch(u){g({error:"PLACE_SEARCH_FAILED",message:u.message}),process.exit(1)}},df=async e=>{if(K().mode==="tada"){let{positional:a,city:c,lang:l}=qt(e),[d,u,m]=a,p=c??m;(!d||!u)&&(console.error("error: Usage: amb place-detail <place_id> <region> [city] [--lang TAG]"),console.error("hint: region: NY, SG"),process.exit(1));let f=R();b(f.dataDir),gt(ee(f.cliGatewayHosts,f.cliGatewayHost));let _;try{_=await Fe(f)}catch(h){g({error:"MEMBER_AUTH_FAILED",message:h.message}),process.exit(1);return}try{let h=await hl(_,d,{region:u,city:p},l);w(h)}catch(h){g({error:"PLACE_DETAIL_FAILED",message:jt(h)}),process.exit(1)}return}let t=e[0],r=e[1],n=e[2];(!t||!r||!n)&&(console.error("error: Usage: amb place-detail <wallet_address> <city> <place_id>"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let s=Lt(r);s||(g({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${r}". Use codes like SIN, BKK, DEN or full names like Singapore, Bangkok, Denver.`}),process.exit(1));let i=R();b(i.dataDir),k(t),$(t),O(i.appServerUrl),H(i.gatewayServerUrl);let o=P(t);o||(g({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let a=await Qa(o,n,s);w(a)}catch(a){g({error:"PLACE_DETAIL_FAILED",message:a.message}),process.exit(1)}},uf=async e=>{let t=e[0],r=e[1],n,s=!1;for(let f=2;f<e.length;f++)e[f]==="--label"&&e[f+1]!=null?(n=e[f+1],f++):e[f]==="--force"&&(s=!0);(!t||!r)&&(console.error("error: Usage: amb place-save <wallet_address> <google_maps_url> [--label LABEL]"),process.exit(1));let i=R();b(i.dataDir),k(t),$(t),gl(i.gatewayServerUrl);let o=P(t);o||(console.error(JSON.stringify({error:"JWT_NOT_FOUND",message:"No valid JWT. Run siwe-request-message.js + siwe-submit.js first."})),process.exit(1));let a;try{a=await Is(r)}catch(f){let _=f.code??"INVALID_URL";console.error(JSON.stringify({error:_,message:f.message})),process.exit(1)}let c=await _l(a.ftid),l;try{l=await fl(o,{name:a.name,latitude:a.latitude,longitude:a.longitude,...a.ftid&&{ftid:a.ftid},...c&&{resolvedPlaceId:c}})}catch(f){let _=f.code??"RESOLVE_FAILED";console.error(JSON.stringify({error:_,message:f.message})),process.exit(1)}l.match==="approximate"&&!s&&(console.error(JSON.stringify({error:"APPROXIMATE_MATCH_NEEDS_FORCE",message:"This URL did not resolve to an exact place. Confirm the place below with the user, then re-run with --force to save it.",candidate:{name:l.name,formatted_address:l.formattedAddress},match:l.match})),process.exit(1));let d=st({placeId:l.googlePlaceId,latitude:l.location.latitude,longitude:l.location.longitude}),u,m=!1,p={wallet_address:t,label:n??null,name:l.name,formatted_address:l.formattedAddress,latitude:l.location.latitude,longitude:l.location.longitude,google_place_id:l.googlePlaceId,city:l.city,region:l.region,ftid:a.ftid??null,kg_id:null,source_url:r};d?Gn(t,d)?(u=Wn(t,d,{...n!==void 0&&{label:n},source_url:r,google_place_id:l.googlePlaceId,ftid:a.ftid??null,kg_id:null,formatted_address:l.formattedAddress,name:l.name,city:l.city,region:l.region}),m=!0):u=qn(p):u=qn(p),console.log(JSON.stringify({...u,was_promoted:m},null,2))},pf=async e=>{let t=e[0],r=[],n=!1,s=!1,i;for(let d=1;d<e.length;d++){let u=e[d];if(u==="--match"&&e[d+1]!=null)r.push(e[d+1]),d++;else if(u==="--favorites-only")n=!0;else if(u==="--history-only")s=!0;else if(u==="--limit"&&e[d+1]!=null){let m=e[d+1],p=parseInt(m,10);(!/^\d+$/.test(m)||p<=0)&&(console.log(JSON.stringify({error:"INVALID_LIMIT",value:m})),process.exit(1)),i=p,d++}else u==="--limit"&&(console.log(JSON.stringify({error:"INVALID_LIMIT",message:"--limit requires a positive integer value"})),process.exit(1))}t||(console.error("error: Usage: amb place-list <wallet_address> [--match QUERY ...] [--favorites-only|--history-only] [--limit N]"),process.exit(1)),n&&s&&(console.log(JSON.stringify({error:"CONFLICTING_FILTERS"})),process.exit(1));let o=i??50,a=R();b(a.dataDir),k(t);let c={favoritesOnly:n,historyOnly:s,limit:o},l;r.length===0?l={matches:jn(t,c),matched_tier:null,normalized_queries:[]}:l=ao(t,r,c),console.log(JSON.stringify({matches:l.matches,matched_tier:l.matched_tier,queries:l.normalized_queries,next_action:"USE_FOR_RIDE_OR_FALLBACK_TO_PLACE_SEARCH"},null,2))},mf=async e=>{let t=e[0],r=e[1];(!t||!r)&&(console.error("error: Usage: amb place-remove <wallet_address> <id_or_label>"),process.exit(1));let n=R();b(n.dataDir),k(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i=s!=null?co(t,s):lo(t,r);if(!i){console.log(JSON.stringify({removed:0,error:"NOT_FOUND"}));return}console.log(JSON.stringify({removed:1,id:i.id,label:i.label}))},gf=async e=>{let t=e[0],r=e[1],n;for(let l=2;l<e.length;l++)e[l]==="--label"&&e[l+1]!=null&&(n=e[l+1],l++);(!t||!r)&&(console.error("error: Usage: amb place-favorite <wallet_address> <id_or_dedup_key> [--label LABEL]"),process.exit(1));let s=R();b(s.dataDir),k(t);let i=/^\d+$/.test(r)?parseInt(r,10):null,o;i!=null?o=At(t,i):o=Gn(t,r),o||(console.log(JSON.stringify({error:"NOT_FOUND"})),process.exit(1));let a=o.is_favorite===1,c=i!=null?po(t,i,n):Wn(t,r,{...n!==void 0&&{label:n}});console.log(JSON.stringify({...c,was_favorite_before:a},null,2))},ff=async e=>{let t=e[0],r=e[1];(!t||!r)&&(console.error("error: Usage: amb place-unfavorite <wallet_address> <id_or_label>"),process.exit(1));let n=R();b(n.dataDir),k(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i;if(s!=null?i=At(t,s):i=mo(t,r),i||(console.log(JSON.stringify({error:"NOT_FOUND"})),process.exit(1)),i.is_favorite===0){console.log(JSON.stringify({info:"ALREADY_NOT_FAVORITE",row:i},null,2));return}let o=s!=null?go(t,s):fo(t,r);console.log(JSON.stringify({...o,was_favorite_before:!0},null,2))},_f=async e=>{K().mode!=="tada"&&vs("place-nearby");let{positional:t,lang:r}=qt(e),[n,s,i]=t;(!n||!s)&&(console.error("error: Usage: amb place-nearby <lat> <lng> [limit] [--lang TAG]"),process.exit(1));let o=parseFloat(n),a=parseFloat(s),c=i!==void 0?parseInt(i,10):void 0;(isNaN(o)||isNaN(a)||i!==void 0&&isNaN(c))&&(g({error:"INVALID_COORDINATES",message:"lat/lng (and limit) must be valid numbers."}),process.exit(1));let l=R();b(l.dataDir),gt(ee(l.cliGatewayHosts,l.cliGatewayHost));let d;try{d=await Fe(l)}catch(u){g({error:"MEMBER_AUTH_FAILED",message:u.message}),process.exit(1);return}try{w(await wl(d,{latitude:o,longitude:a,limit:c},r))}catch(u){g({error:"PLACE_NEARBY_FAILED",message:jt(u)}),process.exit(1)}},yf=async e=>{K().mode!=="tada"&&vs("place-airports");let{positional:t,lang:r}=qt(e),[n]=t;n||(console.error("error: Usage: amb place-airports <city> [--lang TAG]"),console.error("hint: city = TADA city code, e.g. NYC"),process.exit(1));let s=R();b(s.dataDir),gt(ee(s.cliGatewayHosts,s.cliGatewayHost));let i;try{i=await Fe(s)}catch(o){g({error:"MEMBER_AUTH_FAILED",message:o.message}),process.exit(1);return}try{w(await El(i,{city:n},r))}catch(o){g({error:"PLACE_AIRPORTS_FAILED",message:jt(o)}),process.exit(1)}},hf=async e=>{K().mode!=="tada"&&vs("place-reverse-geocode");let{positional:t,lang:r}=qt(e),[n,s,i]=t;(!n||!s||!i)&&(console.error("error: Usage: amb place-reverse-geocode <lat> <lng> <region> [--lang TAG]"),console.error("hint: region: NY, SG"),process.exit(1));let o=parseFloat(n),a=parseFloat(s);(isNaN(o)||isNaN(a))&&(g({error:"INVALID_COORDINATES",message:"lat/lng must be valid numbers."}),process.exit(1));let c=R();b(c.dataDir),gt(ee(c.cliGatewayHosts,c.cliGatewayHost));let l;try{l=await Fe(c)}catch(d){g({error:"MEMBER_AUTH_FAILED",message:d.message}),process.exit(1);return}try{w(await Rl(l,{latitude:o,longitude:a,region:i},r))}catch(d){g({error:"PLACE_REVERSE_GEOCODE_FAILED",message:jt(d)}),process.exit(1)}},bl={"place-search":lf,"place-detail":df,"place-save":uf,"place-list":pf,"place-remove":mf,"place-favorite":gf,"place-unfavorite":ff,"place-nearby":_f,"place-airports":yf,"place-reverse-geocode":hf};import{readFileSync as wf}from"fs";async function Ns(e,t,r){let n=r?.pollIntervalMs??1e3,s=r?.timeoutMs??5*6e4,i=r?.authUrl??"",o=Date.now()+s,a=`${e.gatewayServerUrl}/v1/map-session/${t}/result`;for(;;){let c;try{c=await(await fetch(a)).json()}catch(d){process.stderr.write(`map-session-check poll_error: ${d.message}
447
- `)}let l=c?.status;if(l==="completed"&&!c?.result)return{status:"failed",reason:"completed_missing_result"};if(l==="completed"&&c?.result)return{status:"ready",result:c.result};if(l==="jwt_expired"||l==="cancelled"||l==="expired")return{status:"failed",reason:l};if(Date.now()>=o)return{status:"pending",auth_url:i};await new Promise(d=>setTimeout(d,n))}}function Sl(e){let t=[],r,n,s,i=!1;for(let o=0;o<e.length;o++)e[o]==="--subplaces"&&o+1<e.length?r=e[++o]:e[o]==="--subplaces-file"&&o+1<e.length?n=e[++o]:e[o]==="--purpose"&&o+1<e.length?s=e[++o]:e[o]==="--no-wait"?i=!0:t.push(e[o]);return{positional:t,subplacesJson:r,subplacesFile:n,purpose:s,noWait:i}}function ks(e){try{let t=JSON.parse(e);if(Array.isArray(t))return t;if(Array.isArray(t.subPlaces))return t.subPlaces}catch{}}function Al(e,t={}){let r=t.purpose?{...e,purpose:t.purpose}:e;if(wt()==="json"){w(r),e.status==="failed"&&process.exit(1);return}if(e.status==="ready"){let n=e.result.subPlaceId?` (subPlace=${e.result.subPlaceId})`:"";process.stdout.write(`\u2713 Selected: ${e.result.name}, ${e.result.address} (lat=${e.result.lat}, lng=${e.result.lng})${n}
563
+ `}function Yv(e,t){return{label:e.displayName,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>Yv(r,t))}:{}}}function xM(e){let t=ho(e.receiptBreakdown,l=>l.subtotalName),r=e.locations[0],n=e.locations.at(-1),s=e.receiptInfo?.paidNetwork??void 0,i=[],a=(l,d,m,f)=>{if(!m)return;let g=Pn(d??null,m);i.push({kind:l,hash:m,...d?{network:d}:{},...g?{explorerUrl:g}:{},...f?{amount:f}:{}})};a("payment",s,e.receiptInfo?.paidTxHash,e.receiptInfo?{amount:e.receiptInfo.paidAmount,...e.receiptInfo.paidCurrency?{currency:e.receiptInfo.paidCurrency}:{}}:void 0),a("refund",e.refundReceiptInfo?.refundNetwork??s,e.refundReceiptInfo?.refundTxHash),a("tip",e.tipInfo?.tipRequest?.network??void 0,e.tipInfo?.tipRequest?.txHash,e.tipInfo?.tipRequest?.payAmount?{amount:e.tipInfo.tipRequest.payAmount,...e.tipInfo.tipRequest.payCurrency||e.tipInfo.tipCurrency?{currency:e.tipInfo.tipRequest.payCurrency??e.tipInfo.tipCurrency??void 0}:{}}:void 0);let o=["FINISHED","COMPLETED","REFUNDED"].includes(e.status.toUpperCase()),c=e.isFreeRide||["PAID","COMPLETED","FINISHED","REFUNDED","PARTIALLY_REFUNDED"].includes(e.receiptInfo?.receiptStatus?.toUpperCase()??""),u=e.receiptInfo?{amount:e.receiptInfo.paidAmount,...e.receiptInfo.paidCurrency?{currency:e.receiptInfo.paidCurrency}:{}}:e.isFreeRide?{amount:"0",...t?.currency?{currency:t.currency}:{}}:void 0;return{ready:o&&c,...u?{total:u}:{},fareItems:t?.fareItems.map(l=>Yv(l,t.currency))??[],...e.exchangeRate!=null?{exchangeRate:String(e.exchangeRate)}:{},...i.length?{transactions:i}:{},...e.rideDate?{pickupAt:e.rideDate}:{},...e.rideEndDate?{dropoffAt:e.rideEndDate}:{},...e.rideType?{rideType:e.rideType}:{},...e.driverInfo?.name?{driverName:e.driverInfo.name}:{},rideId:e.id,...r?{pickup:r}:{},...n?{dropoff:n}:{},...e.paymentMethod?{paymentMethod:e.paymentMethod}:{}}}var Ms=class{constructor(t,r,n,s=cr){this.config=t;this.jwt=r;this.walletAddress=n;this.walletSigner=s;_e(t.gatewayServerUrl),hr(t.gatewayServerUrl),t.appServerUrl&&le(t.appServerUrl)}config;jwt;walletAddress;walletSigner;async searchRides(t){return Za(t)}getCancelPenalty(t){throw new Er("getCancelPenalty: not supported in crypto mode (cancellation fee is reported on cancel via isFreeCancel)")}getCancelReasons(t){throw new Er("getCancelReasons: not supported in crypto mode")}getCards(t){throw new Er("Card list is only available for TADA/Throo members.")}async getTipConfig(t){let r=await yv(this.jwt,t),n=r.tipMetadata;return{enabled:!!r.enabled,minAmount:n?.minAmount??0,...n?.maxAmount!==void 0?{maxAmount:n.maxAmount}:{},currency:n?.currency??""}}async payTip(t,r){let{typed_data:n}=await fo({request_id:t,price:r.amount,wallet_address:this.walletAddress,config:this.config}),s=Buffer.from(this.config.passphrase,"utf8"),{wallet_signature:i}=await this.walletSigner({wallet_address:this.walletAddress,sign_method:"eth_signTypedData_v4",message:n},this.config,s),a=await go({request_id:t,signature:i});return{tipStatus:a.success?"PAID":"FAILED",...a.tx_hash?{txHash:a.tx_hash}:{}}}async bookRide(t){let n=await to(t,this.config);return{rideId:n.request_id,price:n.price,currency:n.currency}}getRideStatus(t){return Cs(this.jwt,t)}async getReceipt(t){return xM(await so(this.jwt,t))}async getShareLink(t){let r=await Cs(this.jwt,t);if(!r.rideShareUrl)throw new Mn("Share link is available after a driver is assigned.");return{url:r.rideShareUrl}}cancelRide(t,r,n){return Ha(this.jwt,t,r,n)}async sendChat(t,r){if(r.image)return Wa(this.jwt,t,r.image.buffer,r.image.mimetype);throw new Error("MvlBackend.sendChat: text-only HTTP send not implemented. Use the monitor chat-control socket (chat-monitor-client) for crypto-mode text.")}subscribeChat(t){return new uo(this.config,t,this.walletAddress)}getMessages(t,r){return $a(t,this.jwt,r!=null?String(r):void 0)}};p();p();async function Kr(e,t,r,n,s,i){if(!e)throw new Error("TADA ride API: host required");let a=e.replace(/\/$/,""),o=await fetch(`${a}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...i},body:s!==void 0?JSON.stringify(s):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw dt(o.status,c)}return o.json()}function RM(e){if(e)return{name:e.name,phone:e.phone,carModel:e.car_model??"",carPlate:e.car_plate??"",carColor:e.car_color,profilePhotoUrl:e.photo_url??""}}function zv(e){let t=[];return e.pickup&&t.push(e.pickup),e.waypoints&&t.push(...e.waypoints),e.destination&&t.push(e.destination),{id:e.ride_id,status:e.ride_status,statusMessage:"",driverInfo:RM(e.driver),locations:t,region:e.region,netPrice:e.net_price,payStatus:e.pay_status,tipAmount:e.tip_amount,riderName:e.rider_name}}function Us(e,t,r){return Kr(e,"GET",`/v1/rides/${encodeURIComponent(r)}`,t)}function Fs(e,t,r){return Kr(e,"POST","/v1/products/search",t,r)}function Xv(e,t,r){return Kr(e,"POST","/v1/rides",t,r)}function Qv(e,t,r,n){return Kr(e,"POST",`/v1/rides/${encodeURIComponent(r)}/cancel`,t,n)}function Zv(e,t,r,n){let s=n!=null?`?cancelReasonType=${n}`:"";return Kr(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-penalty${s}`,t)}function ex(e,t,r,n="en"){return Kr(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-reasons`,t,void 0,{"Accept-Language":n})}function tx(e){return{url:e.url,urlId:e.url_id,...e.message!=null?{message:e.message}:{},...e.chat_url!=null?{chatUrl:e.chat_url}:{}}}function rx(e,t,r,n="en"){return Kr(e,"POST",`/v1/rides/${encodeURIComponent(r)}/share`,t,void 0,{"Accept-Language":n})}p();var AM={SEDAN:0,VAN:1,BUSINESS_VAN:4,EXECUTIVE_LARGE:8,BLACK_SEDAN:13,SUV:31,PREMIUM_SUV:33,SUV_LARGE:34,PREMIUM_SUV_LARGE:35,TAXI_STANDARD:1e4,TAXI_STANDARD_LARGE:10001,TAXI_PREMIUM:10002,TAXI_PREMIUM_LARGE:10003,WAV:4e4,WAV_LARGE:40001},wM={PH:10,TAXI:11,ANYTADA:12,STUDENT:13,EV:14,TADAFAST:15,TADASAVER:16};function nx(e){if(e!=null)return AM[e]}function sx(e){if(e!=null)return wM[e]}function ix(e){return e?e.split("_").map(t=>t&&t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" "):""}p();async function ax(e,t,r,n,s){if(!e)throw new Error("TADA tip API: host required");let i=e.replace(/\/$/,""),a=await fetch(`${i}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:s!==void 0?JSON.stringify(s):void 0});if(!a.ok){let o=await a.text().catch(()=>"");throw dt(a.status,o)}return a.json()}function ox(e,t,r){return ax(e,"GET",`/v1/rides/tip-config?region=${encodeURIComponent(r)}`,t)}function cx(e,t,r,n){return ax(e,"POST",`/v1/rides/${encodeURIComponent(r)}/tip`,t,n)}function lx(e){return{enabled:!!e.enabled,minAmount:e.min_amount??0,...e.max_amount&&e.max_amount>0?{maxAmount:e.max_amount}:{},currency:e.currency??"",...e.amount_presets?{presets:e.amount_presets}:{}}}function ux(e){return{tipStatus:e.tip_status}}p();import{EventEmitter as SM}from"events";async function dx(e,t,r,n){let s=`${e}/v2/chat/${encodeURIComponent(r)}/messages`,i={Authorization:`Bearer ${t}`},a;if(n.image){let c={};n.message&&(c.message=n.message);let u=new FormData;u.append("dto",new Blob([JSON.stringify(c)],{type:"application/json"})),u.append("image",new Blob([new Uint8Array(n.image.buffer)],{type:n.image.mimetype}),"image"),a=u}else i["Content-Type"]="application/json",a=JSON.stringify({message:n.message});let o=await fetch(s,{method:"POST",headers:i,body:a});if(!o.ok)throw dt(o.status,await o.text().catch(()=>""));return o.json()}var px=10;async function wu(e,t,r,n={}){let s=[];n.since!=null&&Number.isFinite(n.since)&&s.push(`since=${n.since}`),n.wait!=null&&s.push(`wait=${n.wait}`),n.limit!=null&&s.push(`limit=${n.limit}`);let i=`${e}/v2/chat/${encodeURIComponent(r)}/messages${s.length?`?${s.join("&")}`:""}`,a=n.signal??AbortSignal.timeout(((n.wait??0)+px)*1e3),o=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:a});if(!o.ok)throw dt(o.status,await o.text().catch(()=>""));return o.json()}var IM=25,PM=2e3;function DM(e){return new Promise(t=>setTimeout(t,e))}var yo=class extends SM{constructor(r,n,s,i={}){super();this.host=r;this.jwt=n;this.rideId=s;this.wait=i.wait??IM,this.backoffMs=i.backoffMs??PM,this.since=i.startSince??i.nowMs??Date.now(),this.sleepFn=i.sleepFn??DM}host;jwt;rideId;stopped=!1;started=!1;controller;since;wait;backoffMs;sleepFn;connect(){this.started||(this.started=!0,this.loop())}disconnect(){this.stopped=!0,this.controller?.abort()}dispose(){this.disconnect()}async loop(){for(;!this.stopped;){let r=new AbortController;this.controller=r;let n=setTimeout(()=>r.abort(),(this.wait+px)*1e3);try{let s=await wu(this.host,this.jwt,this.rideId,{since:this.since,wait:this.wait,signal:r.signal});if(this.stopped)break;for(let i of s.messages)i.sender_role!=="RIDER"&&this.emit("message",{data:{content:i.message??(i.file_url?"[image]":""),senderType:i.sender_role,file_url:i.file_url,message_id:i.message_id,created_at:i.created_at}});this.since=s.next_since??this.since}catch(s){if(this.stopped)break;this.emit("error",{message:s.message}),await this.sleepFn(this.backoffMs)}finally{clearTimeout(n)}}}};function hx(e,t){return{label:e.display_name,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>hx(r,t))}:{}}}function mx(e){return e==null||typeof e=="string"&&["RATE","AMOUNT","TARGET"].includes(e)}function js(e){let[t,r]=String(e).toLowerCase().split("e"),n=t.split(".")[1]?.length??0;return Math.max(0,n-Number(r??0))}var OM=6;function CM(e,t){let n=10**Math.max(js(e),js(t));return(Math.round(e*n)+Math.round(t*n))/n}function fx(e){let t=e.discount;if(![e.net_price,t.original_price,t.discounted_price].every(Number.isFinite))throw new mr;let n=Math.max(js(e.net_price),js(t.original_price),js(t.discounted_price));if(n>OM)throw new mr;let s=10**n,i=Math.round(e.net_price*s)-Math.round(t.original_price*s)+Math.round(t.discounted_price*s);return String(i/s)}function gx(e){let t=e?.match(/^(\d+)(?:\.(\d+))?$/);if(!t)return;let r=t[1].replace(/^0+(?=\d)/,""),n=(t[2]??"").replace(/0+$/,"");return n?`${r}.${n}`:r}function NM(e){let t=ho(e.receipt_breakdown,u=>u.subtotal_name),r=e.start_time??e.create_time,n=e.product_type??e.car_type,s=e.pickup,i=e.destination,a=["FINISHED","COMPLETED","REFUNDED"].includes(e.ride_status.toUpperCase()),o=e.net_price===0||["PAID","COMPLETED","FINISHED","REFUNDED","PARTIALLY_REFUNDED"].includes(e.pay_status?.toUpperCase()??""),c=e.net_price!=null?CM(e.net_price,e.tip_amount??0):t?.total_fare??e.ride_fare;return{ready:a&&o,...c!=null?{total:{amount:String(c),...e.currency?{currency:e.currency}:{}}}:{},fareItems:t?.fare_items.map(u=>hx(u,t.currency))??[],...r?{pickupAt:r}:{},...e.drop_off_time?{dropoffAt:e.drop_off_time}:{},...n?{rideType:n}:{},...e.driver?.name?{driverName:e.driver.name}:{},...e.rider_name?{passengerName:e.rider_name}:{},rideId:e.ride_id,...s?{pickup:s}:{},...i?{dropoff:i}:{},...e.payment_method?{paymentMethod:e.payment_method}:{}}}var qs=class{constructor(t,r,n,s){this.config=t;this.jwt=r;this.memberId=n;this.rideHost=s}config;jwt;memberId;rideHost;sgHost(){return Ze("SG",this.config.cliGatewayHosts,this.config.cliGatewayHost)}hostForPickup(t){let r=t[0];if(!r)throw new Error("Cannot route a ride without a pickup location.");return Ze(mt(r.latitude,r.longitude),this.config.cliGatewayHosts,this.config.cliGatewayHost)}followupHost(){return this.rideHost??this.sgHost()}async bookRide(t){let r=t;if(r.couponCode&&r.productId==null)throw new mr;let n=this.hostForPickup(r.locations),i=(await Fs(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid,...r.couponCode?{coupon_code:r.couponCode}:{}})).products.filter(u=>!u.na&&u.price_entry&&Number.isFinite(u.price_entry.net_price)),a=r.productId!=null?i.find(u=>u.id===r.productId):i[0];if(!a||!a.price_entry)throw new Error("No bookable product for the given locations (check region / card).");let o=a.price_entry;if(r.couponCode&&(o.discount?.applicable!==!0||o.discount.code!==r.couponCode||!mx(o.discount.discount_type)))throw new mr;if(r.couponCode){let u=gx(fx(o)),l=gx(r.confirmedPrice);if(!u||!l||u!==l)throw new Ea}let c=await Xv(n,this.jwt,{locations:r.locations,product_id:a.id,ride_price:o.ride_price,currency:o.currency,payment_item_uuid:r.paymentItemUuid,...r.couponCode?{coupon_code:r.couponCode}:{},...r.avoidToll?{avoid_toll:!0}:{},...r.riderNote?{rider_note:r.riderNote}:{}});return Ga({request_id:c.ride_id,ride_id:c.ride_id,member_id:this.memberId,region:c.region??"",origin_lat:r.locations[0].latitude,origin_lng:r.locations[0].longitude,status:c.ride_status,price:c.net_price!=null?String(c.net_price):void 0,pay_currency:c.currency}),{rideId:c.ride_id,rideStatus:c.ride_status,price:c.net_price,currency:c.currency}}async getRideStatus(t){return zv(await Us(this.followupHost(),this.jwt,t))}async getReceipt(t){let r=await Us(this.followupHost(),this.jwt,t);return NM(r)}async searchRides(t){let r=t,n=this.hostForPickup(r.locations),s=await Fs(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid,...r.couponCode?{coupon_code:r.couponCode}:{}}),i=r.locations[0],a=Qa(mt(i.latitude,i.longitude));return{options:s.products.map(c=>{let u=c.na===!0||!c.price_entry||!Number.isFinite(c.price_entry.net_price),l=c.price_entry?.discount,d=!u&&l?.applicable===!0&&mx(l.discount_type),m;if(d)try{m=fx(c.price_entry)}catch(f){if(!(f instanceof mr))throw f;d=!1}return{product_id:c.id,product_name:za(c.region,sx(c.product_type),nx(c.car_type),c.description_local??ix(c.car_type)),price:u?null:d?m:String(c.price_entry.net_price),price_currency:u?null:c.price_entry.currency,na:u,...l?{discount:{applicable:d,...Number.isFinite(l.original_price)?{original_price:String(l.original_price)}:{},...Number.isFinite(l.discounted_price)?{discounted_price:String(l.discounted_price)}:{},...Number.isFinite(l.discount_amount)?{discount_amount:String(l.discount_amount)}:{},...Number.isFinite(l.available_coupon_count)?{available_coupon_count:l.available_coupon_count}:{},...l.discount_type!=null?{discount_type:l.discount_type}:{},...l.title!=null?{title:l.title}:{},...l.code!=null?{coupon_code:l.code}:{},...l.promotion_code!=null?{campaign_promotion_code:l.promotion_code}:{}}}:{}}}),routes:Xa(s.routes,a)}}async cancelRide(t,r,n){return Qv(this.followupHost(),this.jwt,t,{cancel_reason_type:n??null,cancel_reason:r??null})}getCancelPenalty(t,r){return Zv(this.followupHost(),this.jwt,t,r)}async getCancelReasons(t){return((await ex(this.followupHost(),this.jwt,t)).reasons??[]).map(n=>({id:n.reason_id,title:n.title}))}async getShareLink(t,r="en"){return tx(await rx(this.followupHost(),this.jwt,t,r))}getCards(t){return kv(t,this.jwt)}hostForRegion(t){return Ze(St(t),this.config.cliGatewayHosts,this.config.cliGatewayHost)}async getTipConfig(t){return lx(await ox(this.hostForRegion(t),this.jwt,t))}async payTip(t,r){if(!r.paymentItemUuid)throw new Error("NO_CARD: member tip requires a payment_item_uuid (card).");let n={amount:r.amount,currency:r.currency??"",payment_item_uuid:r.paymentItemUuid};return ux(await cx(this.followupHost(),this.jwt,t,n))}sendChat(t,r){return dx(this.followupHost(),this.jwt,t,r)}subscribeChat(t){return new yo(this.followupHost(),this.jwt,t)}getMessages(t,r){return wu(this.followupHost(),this.jwt,t,{since:r})}};async function ft(e,t){if(t.wallet_address){let a=ie(t.wallet_address);if(!a)throw new Error("JWT_NOT_FOUND: no valid wallet JWT. Run siwe-request-message + siwe-submit first.");return{backend:new Ms(e,a,t.wallet_address),jwt:a,identity:t.wallet_address,mode:"wallet"}}_r(Ye(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await oo(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member_id??"",i=Ze(St(t.region),e.cliGatewayHosts,e.cliGatewayHost);return{backend:new qs(e,n,s,i),jwt:n,identity:s,mode:"tada"}}async function Yr(e){let t=ze();if(t.mode==="wallet"){let r=t.walletAddress;if(!r)throw new Error("No registered wallet. Run wallet setup first.");let n=ie(r);if(!n)throw new Error("JWT_NOT_FOUND: no valid wallet JWT. Run siwe-request-message + siwe-submit first.");return{backend:new Ms(e,n,r),jwt:n,identity:r,mode:"wallet"}}if(t.mode==="tada"){_r(Ye(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await oo(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member?.id??"";return{backend:new qs(e,n,s),jwt:n,identity:s,mode:"tada"}}throw new Error("No active account. Run `amb login` (TADA/Throo member) or wallet setup (crypto) first.")}async function $t(e){_r(Ye(e.cliGatewayHosts,e.cliGatewayHost));let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},r=await oo(t);if(!r)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");return r}p();var LM=new Set(["NY","NYC","US","CO","DEN","DENVER"]),kM={minLat:40.3,maxLat:41.1,minLng:-74.5,maxLng:-73.3},MM={minLat:39.4,maxLat:40.1,minLng:-105.5,maxLng:-104.4};function Un(e){let t=e?.trim().toUpperCase();return t?t==="SG"||t==="SIN"?{marketCode:t,subMarket:"SG"}:t==="NY"||t==="NYC"?{marketCode:t,subMarket:"NYC"}:t==="CO"||t==="DEN"||t==="DENVER"?{marketCode:t,subMarket:"DENVER"}:t==="US"?{marketCode:t,subMarket:"OTHER"}:{marketCode:"UNKNOWN",subMarket:"OTHER"}:{marketCode:"UNKNOWN",subMarket:"OTHER"}}function Fn(e){let t=e?.trim().toUpperCase();return t&&LM.has(t)?"US":St(e)}function Bs(e,t){return mt(e,t)==="SG"?{marketCode:"SG",subMarket:"SG"}:yx(kM,e,t)?{marketCode:"NYC",subMarket:"NYC"}:yx(MM,e,t)?{marketCode:"DEN",subMarket:"DENVER"}:{marketCode:"US",subMarket:"OTHER"}}function yx(e,t,r){return t>=e.minLat&&t<=e.maxLat&&r>=e.minLng&&r<=e.maxLng}p();function kt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return null}var _x=["lat_lng","locationPoint"];function UM(e){if(e==null||typeof e!="object")return null;let t=_x.map(i=>e[i]).find(i=>i!=null&&typeof i=="object"),r=kt(e.latitude)??kt(e.lat)??kt(t?.latitude),n=kt(e.longitude)??kt(e.lng)??kt(t?.longitude);if(r==null||n==null)return null;let s={...e};for(let i of["latitude","longitude","lat","lng",..._x])delete s[i];return{...s,latitude:r,longitude:n}}function _o(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){let n=UM(r);if(n==null)return null;t.push(n)}return t}p();var FM=new Set(["ASSIGNED","PICKUP","PICKUP_ARRIVED"]),jM=new Set(["INUSE","INUSE_WITH_CANCEL_PENDING"]),qM=new Set(["PAYCONFIRMED","PENDING","ASSIGNED","PICKUP","PICKUP_ARRIVED"]);function Eo(e){let{status:t,mode:r,supportsReasons:n,hasReasonType:s}=e;return Lt(t)?{kind:"not_cancelable",why:`ride already ended (${t})`}:jM.has(t)?{kind:"not_cancelable",why:`ride is in progress (${t}) \u2014 it cannot be cancelled`}:r==="crypto"&&!qM.has(t)?{kind:"not_cancelable",why:`ride cannot be cancelled in status ${t}`}:FM.has(t)&&n&&!s?{kind:"needs_reason"}:{kind:"immediate"}}p();p();function BM(e){if(e.member_id&&!e.wallet_address)return ur(e.member_id);if(e.wallet_address&&!e.member_id)return vt(e.wallet_address)}function jn(e){let t=BM(e);if(!t)return;let r=e.region.trim(),n=r?Fn(r):void 0,s=Un(r);if(!r&&e.journey_id)try{let i=new pt().find(e.journey_id,t);i&&(n=i.region,s=Un(i.market_code))}catch{}return!n&&e.origin_lat!==null&&e.origin_lng!==null&&Number.isFinite(e.origin_lat)&&Number.isFinite(e.origin_lng)&&(n=mt(e.origin_lat,e.origin_lng),s=Bs(e.origin_lat,e.origin_lng)),{...s,accountId:t,journeyId:e.journey_id??void 0,paymentMode:e.member_id?"card":"wallet_usdc",region:n,requestId:e.request_id,rideId:VM(e)}}function VM(e){if(e.ride_id)return e.ride_id;if(e.member_id)return e.request_id}async function To(e,t,r){try{let n=jn(t),s=n?.accountId;if(n&&await OT(e,{...n,...r,rideId:r.rideId??n.rideId}),r.rideId&&(Vb(t.request_id,r.rideId),t.ride_id??=r.rideId),r.rideId&&t.journey_id&&s)try{new pt().link(t.journey_id,s,{link_type:"ride",link_id:r.rideId})}catch{}if(Lt(r.status)&&t.journey_id&&s)try{new pt().close(t.journey_id,s)}catch{}}catch{}}function GM(e){let t=[],r;for(let n=0;n<e.length;n++){let s=e[n];if(s==="--coupon-code"||s.startsWith("--coupon-code=")){if(r!==void 0)throw new Error("--coupon-code may be specified only once.");let i=s.startsWith("--coupon-code="),a=i?s.slice(14):e[++n];if(!a||!i&&a.startsWith("--"))throw new Error("--coupon-code requires a non-empty value.");r=a}else{if(s.startsWith("--"))throw new Error(`Unknown member ride-search option: ${s}. Member ride-search takes <origin_lat> <origin_lng> <dest_lat> <dest_lng> [card_uuid] [--coupon-code CODE].`);t.push(s)}}return{positional:t,...r?{couponCode:r}:{}}}function bx(e){let t=e.code,r=e.detail;if(t==="coupon_price_changed")return{error:"COUPON_PRICE_CHANGED",message:"The coupon total changed after confirmation. Re-quote and ask the user to confirm the new price."};if(t==="invalid_parameter"&&r)return{error:"INVALID_PARAMETER",message:r};if(t==="coupon_not_applicable"||t==="coupon_cannot_apply")return{error:t.toUpperCase(),message:r??"The coupon is no longer applicable. Re-quote it, or ask the user before continuing without it."};let n=Ta(t);return t&&n?{error:t.toUpperCase(),message:n}:void 0}var HM=async e=>{let t=D();if(O(t.dataDir),ze().mode==="tada"){let l;try{l=GM(e)}catch(Z){b({error:"INVALID_ARGUMENT",message:Z.message}),process.exit(1)}let{positional:d,couponCode:m}=l,[f,g,_,E,T]=d;(!f||!g||!_||!E)&&(console.error("error: Usage:"),console.error(" [crypto] amb ride-search <wallet_address> <region> <origin_lat> <origin_lng> <dest_lat> <dest_lng>"),console.error(" [member] amb ride-search <origin_lat> <origin_lng> <dest_lat> <dest_lng> [card_uuid] [--coupon-code CODE]"),console.error("hint: card_uuid is optional \u2014 the default/only card is auto-selected when omitted."),process.exit(1));let x=kt(f),R=kt(g),I=kt(_),N=kt(E);if(x==null||R==null||I==null||N==null){b({error:"INVALID_COORDINATES",message:"origin/destination lat and lng must all be numbers."}),process.exit(1);return}let k;try{k=await Yr(t)}catch(Z){b({error:Z.message}),process.exit(1);return}let B=Ze(mt(x,R),t.cliGatewayHosts,t.cliGatewayHost),Y=await Jr(k.backend,T,B);if(Y==null)return;let re=mt(x,R),q=Bs(x,R);try{let Z=k.identity?ur(k.identity):void 0,Ve,We,ue;if(Z)try{Ve=new pt,We=Ve.findOrCreate({account_id:Z,payment_mode:"card",region:re,market_code:q.marketCode}),ue=Ex(),Ve.link(We.journey_id,Z,{link_type:"search",link_id:ue})}catch{Ve=void 0,We=void 0,ue=void 0}let Ge=await Yl(t.dataDir,{region:re,...q,paymentMode:"card",accountId:Z,journeyId:We?.journey_id,searchId:ue},()=>k.backend.searchRides({locations:[{latitude:x,longitude:R},{latitude:I,longitude:N}],paymentItemUuid:Y,...m?{couponCode:m}:{}}));We&&ue&&Ge&&typeof Ge=="object"?w({...Ge,journey_id:We.journey_id,search_id:ue}):w(Ge)}catch(Z){b(bx(Z)??{error:Z.message}),process.exit(1)}return}let[s,i,a,o,c,u]=e;(!s||!i||!a||!o||!c||!u)&&(console.error("error: Usage:"),console.error(" [crypto] amb ride-search <wallet_address> <region> <origin_lat> <origin_lng> <dest_lat> <dest_lng>"),console.error(" [member] amb ride-search <origin_lat> <origin_lng> <dest_lat> <dest_lng> [card_uuid] [--coupon-code CODE]"),console.error("hint: region: SG (Singapore), NY (New York)"),process.exit(1)),J(s),he(s),le(t.appServerUrl),_e(t.gatewayServerUrl);try{let l=vt(s),d=Un(i),m,f;try{m=new pt,f=m.findOrCreate({account_id:l,payment_mode:"wallet_usdc",region:Fn(i),market_code:d.marketCode})}catch{}let g=Ex(),_,E,T,x=await Yl(t.dataDir,{region:Fn(i),...d,paymentMode:"wallet_usdc",accountId:l,journeyId:f?.journey_id,searchId:g},async()=>{T=await Za({wallet_address:s,region:i,locations:[{latitude:parseFloat(a),longitude:parseFloat(o)},{latitude:parseFloat(c),longitude:parseFloat(u)}],payCurrency:t.payCurrency}),E=T.search_id;let R=Ka(E);if(R)try{return Ja(g,R),_=g,{...T,search_id:_}}catch{}return T},()=>{let R=T?{...T,search_id:""}:void 0;if(!f||!m||!_)return{context:{journeyId:void 0,searchId:void 0},result:R};try{m.link(f.journey_id,l,{link_type:"search",link_id:_,backend_id:E});return}catch{return f=void 0,{context:{journeyId:void 0,searchId:void 0},result:R}}});f&&_?w({...x,search_id:_,journey_id:f.journey_id}):_?w({...x,search_id:_}):E?w({...x,search_id:E}):w(x)}catch(l){b({error:l.message}),process.exit(1)}},$M=async e=>{let t=D();if(O(t.dataDir),ze().mode==="tada"){let c=e[0];c||(console.error("error: Usage: amb ride-request <json_params>"),console.error('hint: [member] json_params: {"locations":[...], "payment_item_uuid":"<uuid, optional \u2014 auto-selected if omitted>", "product_id":<required with coupon_code>, "coupon_code":"<optional>", "confirmed_price":"<required canonical decimal string with coupon_code>"}'),process.exit(1));let u;try{u=JSON.parse(c)}catch{b({error:"INVALID_JSON",message:"Failed to parse json_params argument."}),process.exit(1);return}let l=u.locations,d=u.payment_item_uuid,m=u.product_id,f=u.search_id,g=u.coupon_code,_=u.confirmed_price;if(!l||l.length===0){b({error:"MISSING_FIELD",message:"locations is required in json_params (member mode) and must contain [origin, destination]."}),process.exit(1);return}if(g!==void 0&&(typeof g!="string"||g.length===0)){b({error:"INVALID_ARGUMENT",message:"coupon_code must be a non-empty case-sensitive string."}),process.exit(1);return}if(g!==void 0&&m==null){b({error:"INVALID_ARGUMENT",message:"product_id is required with coupon_code."}),process.exit(1);return}let E=typeof _=="string"?_.trim():void 0;if(g!==void 0&&(!E||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(E))){b({error:"INVALID_ARGUMENT",message:"confirmed_price is required with coupon_code and must be the canonical non-negative decimal string the user approved."}),process.exit(1);return}if(g===void 0&&_!==void 0){b({error:"INVALID_ARGUMENT",message:"confirmed_price may be used only with coupon_code."}),process.exit(1);return}let T;try{T=await Yr(t)}catch(Z){b({error:"RIDE_REQUEST_FAILED",message:Z.message}),process.exit(1);return}let x=_o(l);if(x==null){b({error:"INVALID_COORDINATES",message:"Every entry in locations needs numeric coordinates (latitude/longitude, or lat/lng)."}),process.exit(1);return}let R=x[0],I=Ze(mt(R.latitude,R.longitude),t.cliGatewayHosts,t.cliGatewayHost),N=await Jr(T.backend,d,I);if(N==null)return;let k=T.identity?ur(T.identity):void 0,B=mt(R.latitude,R.longitude),Y=Bs(R.latitude,R.longitude),re=k?new pt:void 0,q;if(re&&f)try{q=re.resolveSearchForBooking(f,k,{payment_mode:"card",region:B,market_code:Y.marketCode}).journey}catch{}try{let Z=q,Ve=await zl(t.dataDir,{region:B,...Y,paymentMode:"card",accountId:k,journeyId:q?.journey_id,searchId:q?f:void 0},()=>T.backend.bookRide({locations:x,paymentItemUuid:N,...m!=null?{productId:m}:{},...typeof g=="string"?{couponCode:g}:{},...E?{confirmedPrice:E}:{}}),Ge=>{if(!(!q||!re))try{re.linkRequestAndRide(q.journey_id,k,Ge.rideId,Ge.rideId);return}catch{return Z=void 0,{context:{journeyId:void 0,searchId:void 0}}}});await nr(Ve.rideId);let{rideStatus:We,...ue}=Ve;Z?w({...ue,journey_id:Z.journey_id}):w(ue)}catch(Z){b(bx(Z)??{error:"RIDE_REQUEST_FAILED",message:Z.message}),process.exit(1)}return}let s=e[0];s||(console.error("error: Usage: amb ride-request <json_params>"),console.error("hint: see references/ride.md for the full json_params schema"),process.exit(1));let i;try{i=JSON.parse(s)}catch{b({error:"INVALID_JSON",message:"Failed to parse json_params argument."}),process.exit(1);return}let a=i.wallet_address,o=i.rider?.phone;if(!a){b({error:"MISSING_FIELD",message:"wallet_address is required in json_params."}),process.exit(1);return}if(J(a),he(a),o&&!Bb(a,o)){b({error:"PHONE_NOT_VERIFIED",message:`Phone ${o} is not verified.`,action:"Run `amb phone-verify-start` + `amb phone-verify-confirm` first."}),process.exit(1);return}le(t.appServerUrl),_e(t.gatewayServerUrl);try{let c=vt(a),u=new pt,l,d,m=i.search_id,f=Un(i.region),g=Fn(i.region);try{let T=u.resolveSearchForBooking(m,c,{payment_mode:"wallet_usdc",region:g,market_code:f.marketCode});l=T.journey,d=T.backend_id??void 0}catch{}let _=l,E=await zl(t.dataDir,{region:g,...f,paymentMode:"wallet_usdc",accountId:c,journeyId:l?.journey_id,searchId:l?m:void 0},()=>to({...i,search_id:d??m},t),T=>{if(l)try{u.link(l.journey_id,c,{link_type:"request",link_id:T.request_id});return}catch{return _=void 0,{context:{journeyId:void 0,searchId:void 0}}}});await nr(E.request_id),_?w({...E,journey_id:_.journey_id}):w(E)}catch(c){let u=c.message??"";u.toLowerCase().includes("deposit")||u.toLowerCase().includes("collateral")?b({error:"INSUFFICIENT_DEPOSIT",message:u,action:"Run `amb deposit-status` to identify the network, then `amb deposit-add <wallet> <network> <token> <amount>`."}):b({error:"RIDE_REQUEST_FAILED",message:u,action:"Run `amb deposit-status` + `amb wallet-balance` to diagnose."}),process.exit(1)}};function vx(e){let t=[],r;for(let n=0;n<e.length;n++){let s=e[n],i="--reason-type=";if(s==="--reason-type"||s.startsWith(i)){let a=s.startsWith(i)?s.slice(i.length):e[++n];(a==null||!/^\d+$/.test(a))&&(b({error:"INVALID_ARGUMENT",message:`--reason-type must be an integer id (got: ${a??"<missing>"}). Get valid ids from the cancel_pending reasons list.`}),process.exit(1)),r=parseInt(a,10)}else t.push(s)}return{positional:t,reasonType:r}}async function xx(e,t,r,n){let s=await e.getCancelReasons(t),i;if(n==="member")try{i=await e.getCancelPenalty(t)}catch{}w({cancel_pending:!0,ride_status:r,reasons:s,...i?.cancellation_fee!=null?{cancellation_fee:i.cancellation_fee,cancellation_fee_currency:i.cancellation_fee_currency,fee_varies_by_reason:!0}:{},message:n==="member"?"Ride is NOT cancelled yet. Show these reasons to the rider, let them pick one, then re-run with --reason-type <id>. Do not pick a reason on the rider's behalf. The fee shown is the default \u2014 it can differ by reason (re-check with `amb ride-cancel-penalty <request_id> --reason-type <id>`).":"Ride is NOT cancelled yet. Show these reasons to the rider, let them pick one, then re-run with --reason-type <id>. Do not pick a reason on the rider's behalf. The cancellation fee is reported after cancelling (isFreeCancel)."})}async function Tx(e,t,r,n){return await xx(e,t,r,n),{kind:"done"}}async function WM(e,t,r,n,s,i,a){let o;try{o=await e.cancelRide(t,r,n)}catch(l){if(!(l instanceof Be))throw l;if(l.status===409&&l.code==="ride_cancel_not_allowed"){let d=await e.getRideStatus(t),m=Eo({status:d.status,mode:s,supportsReasons:i,hasReasonType:n!=null});return m.kind==="needs_reason"?Tx(e,t,d.status,s):m.kind==="not_cancelable"?{kind:"not_cancelable",why:m.why,status:d.status}:{kind:"hold",status:d.status}}if(l.status===400&&l.code==="invalid_parameter"&&n!=null&&i){let d=await e.getRideStatus(t),m=Eo({status:d.status,mode:s,supportsReasons:i,hasReasonType:!1});return m.kind==="not_cancelable"?{kind:"not_cancelable",why:m.why,status:d.status}:Tx(e,t,d.status,s)}return{kind:"failed",message:l.message}}let c=o,u=s==="member"?c?.ride_status??"USER_CANCELED":c?.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED";return w(o),{kind:"done",status:u,previousStatus:a}}async function Rx(e,t,r){let{status:n,rideId:s}=r,i=r.previousStatus??t.status,a=!!s&&s!==t.ride_id,o=Wr({rideId:t.request_id,kind:"ride_status",status:n});await To(e,t,{eventId:o,status:n,previousStatus:i,rideId:s,rideCreatedObserved:a,durationMs:Math.max(0,Date.now()-(t.status_updated_at??t.created_at)*1e3)}),Dn(t.request_id,n)}var JM=async e=>{let{positional:t,reasonType:r}=vx(e),n=t[0];n||(console.error("error: Usage: amb ride-cancel <request_id> [wallet_address] [reason] [--reason-type <id>]"),process.exit(1));let s=D();O(s.dataDir),await nr(n);let i=Ae(n);if(i?.status?.startsWith("EXPIRED")&&(w({already_expired:!0,status:i.status,message:"Ride has already expired. No active ride to cancel."}),process.exit(0)),i){let l=i.wallet_address?"crypto":"member",d=l==="crypto"?t[2]:t[1],m=l==="member",f;try{let{backend:g}=await ft(s,i),_=await g.getRideStatus(n),E=Eo({status:_.status,mode:l,supportsReasons:m,hasReasonType:r!=null});E.kind==="not_cancelable"?f={kind:"not_cancelable",why:E.why,status:_.status}:E.kind==="needs_reason"?(await xx(g,n,_.status,l),f={kind:"done"}):f=await WM(g,n,d,r,l,m,_.status)}catch(g){f={kind:"failed",message:g.message}}if(f.kind==="done"){f.status&&await Rx(s.dataDir,i,{status:f.status,previousStatus:f.previousStatus});return}if(f.kind==="not_cancelable"){b({error:"RIDE_NOT_CANCELABLE",message:f.why,status:f.status}),process.exit(1);return}if(f.kind==="hold"){b({error:"RIDE_CANCEL_FAILED",message:"the payment is being held \u2014 retry in a moment",status:f.status}),process.exit(1);return}b({error:"RIDE_CANCEL_FAILED",message:f.message}),process.exit(1);return}let a=t[1],o=t[2],c=a;if(!c){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}. Provide wallet_address as 2nd argument.`}),process.exit(1);return}J(c),he(c),le(s.appServerUrl),_e(s.gatewayServerUrl);let u=ie(c);if(!u){b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let l=await Ha(u,n,o,r);Dn(n,l.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED"),w(l)}catch(l){b({error:"RIDE_CANCEL_FAILED",message:l.message}),process.exit(1)}},KM=async e=>{let t=e[0],r=e[1];t||(console.error("error: Usage: amb ride-status <request_id> [wallet_address]"),process.exit(1));let n=D();O(n.dataDir),await nr(t);let s=Ae(t);if(s){try{let{backend:o}=await ft(n,s),c=await o.getRideStatus(t);w(c),await Rx(n.dataDir,s,{status:c.status,previousStatus:s.status,rideId:c.rideId})}catch(o){b({error:"RIDE_STATUS_FAILED",message:o.message}),process.exit(1)}return}let i=r;if(!i){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}. Provide wallet_address as 2nd argument.`}),process.exit(1);return}J(i),he(i),le(n.appServerUrl),_e(n.gatewayServerUrl);let a=ie(i);if(!a){b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let o=await Cs(a,t);Dn(t,o.status),w(o)}catch(o){b({error:"RIDE_STATUS_FAILED",message:o.message}),process.exit(1)}},YM=async e=>{let{positional:t,reasonType:r}=vx(e),n=t[0];if(!n){console.error("error: Usage: amb ride-cancel-penalty <request_id> [--reason-type <id>]"),process.exit(1);return}let s=D();O(s.dataDir);let i=Ae(n);if(!i){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}try{let{backend:a}=await ft(s,i),o=await a.getCancelPenalty(n,r);w(o)}catch(a){a instanceof Er?b({error:"NOT_SUPPORTED",message:"Cancellation fee pre-check is TADA/Throo member-mode only; in crypto mode the fee is reported on cancel (isFreeCancel)."}):b({error:"RIDE_CANCEL_PENALTY_FAILED",message:a.message??""}),process.exit(1)}},zM=async e=>{let t="en",r=[];for(let a=0;a<e.length;a++){let o=e[a];o==="--lang"&&e[a+1]!=null?t=e[++a]:r.push(o)}let n=r[0];if(!n){console.error("error: Usage: amb ride-share <request_id> [--lang TAG]"),process.exit(1);return}let s=D();O(s.dataDir);let i=Ae(n);if(!i){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}try{let{backend:a}=await ft(s,i),o=await a.getShareLink(n,t);w(o)}catch(a){if(a instanceof Mn){b({error:a.code,message:a.message}),process.exit(1);return}b({error:"SHARE_LINK_FAILED",message:a.message}),process.exit(1)}},XM=async e=>{let[t,r]=e,n=r?parseInt(r,10):20;t||(console.error("error: Usage: amb ride-history <wallet_address> [limit]"),console.error("hint: limit: max history entries (default 20)"),process.exit(1));let s=D();O(s.dataDir),J(t),he(t),hr(s.gatewayServerUrl);let i=ie(t);if(!i){b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let a=await bv(i,n);w(a)}catch(a){b({error:"RIDE_HISTORY_FAILED",message:a.message}),process.exit(1)}};function QM(e,t){let r=Ae(t);return r?.region?Ze(St(r.region),e.cliGatewayHosts,e.cliGatewayHost):e.cliGatewayHost}function ZM(e){if(!e.ready){b({error:"RECEIPT_NOT_READY",message:"Receipt settlement is still pending. Please try again shortly."}),process.exitCode=75;return}console.log(Kv(e))}var e0=async e=>{let t=e.filter(c=>c.startsWith("--format"));if(t.length>1||t[0]&&t[0]!=="--format=markdown"||Kn()==="json"){b({error:"INVALID_RECEIPT_OPTIONS",message:"ride-receipt emits Markdown; '--format=markdown' is optional and --json is not supported."}),process.exit(1);return}let r=e.filter(c=>!c.startsWith("--format"));if(r.length!==1){b({error:"INVALID_RECEIPT_USAGE",message:"Usage: amb ride-receipt <request_id>. For raw detail, use ride-history-detail."}),process.exit(1);return}let n=r[0],s=D();O(s.dataDir);let i=Ae(n);if(!i){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}let a=Dv(),o=i.wallet_address?"wallet":"tada";if(a&&a!==o){b({error:"RECEIPT_ACCOUNT_CONFLICT",message:`This ride belongs to the ${o} account; remove --account=${a}.`}),process.exit(1);return}try{let{backend:c}=await ft(s,i);ZM(await c.getReceipt(n))}catch(c){b({error:"RIDE_RECEIPT_FAILED",message:c.message}),process.exit(1)}},t0=async e=>{if(ze().mode==="tada"){let[a]=e;if(!a){console.error("error: Usage: amb ride-history-detail <request_id>"),process.exit(1);return}let o=D();O(o.dataDir);let c;try{c=await $t(o)}catch(u){b({error:"MEMBER_SESSION_EXPIRED",message:u.message}),process.exit(1);return}try{let u=await Us(QM(o,a),c,a);w(u)}catch(u){b({error:"RIDE_HISTORY_DETAIL_FAILED",message:u.message}),process.exit(1)}return}let[r,n]=e;(!r||!n)&&(console.error("error: Usage: amb ride-history-detail <wallet_address> <request_id>"),process.exit(1));let s=D();O(s.dataDir),J(r),he(r),hr(s.gatewayServerUrl);let i=ie(r);if(!i){b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let a=await so(i,n);if(Kn()==="plain"){let o=a.receiptInfo?.paidNetwork??null,c={...a},u=Pn(o,a.receiptInfo?.paidTxHash??null);if(u&&(c.receiptInfo={...a.receiptInfo,explorerUrl:u}),a.refundReceiptInfo){let d=Pn(a.refundReceiptInfo.refundNetwork??o,a.refundReceiptInfo.refundTxHash);c.refundReceiptInfo=d?{...a.refundReceiptInfo,explorerUrl:d}:a.refundReceiptInfo}let l=a.tipInfo?.tipRequest?.txHash??null;if(l){let d=Pn(a.tipInfo?.tipRequest?.network??null,l);d&&a.tipInfo&&(c.tipInfo={...a.tipInfo,tipRequest:{...a.tipInfo.tipRequest,explorerUrl:d}})}w(c)}else w(a)}catch(a){b({error:"RIDE_HISTORY_DETAIL_FAILED",message:a.message}),process.exit(1)}},Ax={"ride-search":HM,"ride-request":$M,"ride-cancel":JM,"ride-status":KM,"ride-cancel-penalty":YM,"ride-share":zM,"ride-history":XM,"ride-history-detail":t0,"ride-receipt":e0};p();p();function r0(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function wx(e){let{request_id:t,wallet_address:r,config:n}=e,s=r0(r),{accepts:i,nonce:a}=await Yb(s,t),o=i[0],c=String(Math.floor(Date.now()/1e3)+o.maxTimeoutSeconds),u=parseInt(o.network.split(":")[1],10),l={domain:{name:o.extra.name,version:o.extra.version,chainId:u,verifyingContract:o.asset},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},primaryType:"TransferWithAuthorization",message:{from:r,to:o.payTo,value:o.amount,validAfter:"0",validBefore:c,nonce:a}},{typed_data:d,isSmartAccount:m}=await po({rawTypedData:l,walletAddress:r,target:{rpcUrl:n.paymentRpcUrl,chainId:u}});return Ya(t,{accepts:i,nonce:a,walletAddress:r,validBefore:c,expiresAt:Date.now()+o.maxTimeoutSeconds*1e3,isSmartAccount:m}),{typed_data:d}}p();function n0(e){let t=Ce(e);if(!t)throw new Error("JWT_NOT_FOUND: No cached JWT for this wallet. Call siwe_get_message + siwe_login first.");return t}async function Sx(e){let{request_id:t,signature:r}=e,n=On(t);if(!n)throw new Error("PAYMENT_CACHE_MISS: request_id not found or expired. Call ride_pay_prepare again.");let{accepts:s,nonce:i,walletAddress:a,validBefore:o,isSmartAccount:c}=n,u=n0(a),l=s[0],d={x402Version:2,accepted:l,payload:{authorization:{from:a,to:l.payTo,value:l.amount,validAfter:"0",validBefore:o,nonce:i},signature:mo(r,c===!0)}},m=Buffer.from(JSON.stringify(d)).toString("base64"),f=await zb(u,t,m);return{success:f.success,tx_hash:f.transaction}}function Ix(e,t){let r={},n;try{let a=Ae(e);if(n=a?.wallet_address??void 0,a?.wallet_address){let o=jn(a);o&&(r=o)}}catch{}let s=n??t,i=s?vt(s):void 0;return{...r,accountId:i,paymentMode:"wallet_usdc",requestId:e}}var s0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb ride-pay-prepare <request_id> <wallet_address>"),process.exit(1));let n=D();O(n.dataDir),J(r),he(r),le(n.appServerUrl),_e(n.gatewayServerUrl);try{let s=await wT(n.dataDir,Ix(t,r),()=>wx({request_id:t,wallet_address:r,config:n}));w(s)}catch(s){b({error:s.message}),process.exit(1)}},i0=async e=>{let[t,r,...n]=e;(!t||!r||n.length>0)&&(console.error("error: Usage: amb ride-pay-confirm <request_id> <signature>"),console.error("hint: signature: hex from `amb wallet-sign` with sign_method=eth_signTypedData_v4"),n.length>0&&console.error(`error: unexpected extra argument(s): ${n.join(" ")}`),process.exit(1)),/^0x[0-9a-fA-F]{100,}$/.test(r)||(console.error("error: signature looks too short to be a valid hex signature (got length "+r.length+")"),console.error("hint: pass the wallet_signature returned by `amb wallet-sign`, not the wallet address"),process.exit(1));let s=D();O(s.dataDir),le(s.appServerUrl),_e(s.gatewayServerUrl);try{let i=On(t)?.walletAddress,a=await ST(s.dataDir,Ix(t,i),()=>Sx({request_id:t,signature:r}));w(a)}catch(i){let a=i.message??"";a.toLowerCase().includes("insufficient")||a.toLowerCase().includes("balance")?b({error:"INSUFFICIENT_BALANCE",message:a,action:"Run `amb wallet-balance` and top up your wallet."}):b({error:"RIDE_PAY_CONFIRM_FAILED",message:a,action:"Check `amb wallet-balance` for wallet balance."}),process.exit(1)}},Px={"ride-pay-prepare":s0,"ride-pay-confirm":i0};p();async function Dx(e,t){try{let r=Ae(t),n=r?jn(r):void 0;n&&await AT(e,n)}catch{}}function a0(e){let t=[],r,n;for(let s=0;s<e.length;s++)e[s]==="--currency"&&e[s+1]!=null?r=e[++s]:e[s]==="--card"&&e[s+1]!=null?n=e[++s]:t.push(e[s]);return{positionals:t,currency:r,card:n}}var o0=async e=>{let t=e[0];if(!t){console.error("error: Usage: amb tip-config <region>"),console.error("hint: region: SG (Singapore), NY (New York). Member mode resolves the active account; crypto uses the registered wallet."),process.exit(1);return}let r=D();O(r.dataDir);let n;try{n=await Yr(r)}catch(s){b({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1);return}try{w(await n.backend.getTipConfig(t))}catch(s){b({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1)}},c0=async e=>{let{positionals:t,currency:r,card:n}=a0(e),[s,i]=t,a=i?parseFloat(i):NaN;if(!s||Number.isNaN(a)){console.error("error: Usage: amb tip <ride_id> <amount> [--currency C] [--card uuid]"),console.error("hint: amount within the tip-config min/max. Member: card auto-selected if --card omitted; crypto: pays from the wallet."),process.exit(1);return}let o=D();O(o.dataDir);let c=Ae(s);if(!c){b({error:"RIDE_NOT_FOUND",message:`No local record for ride_id: ${s}.`}),process.exit(1);return}let u;try{u=await ft(o,c)}catch(g){b({error:"TIP_FAILED",message:g.message}),process.exit(1);return}let{backend:l,mode:d}=u,m=r,f;if(d==="tada"){let g;try{g=await l.getTipConfig(c.region)}catch(T){b({error:"TIP_CONFIG_FAILED",message:T.message}),process.exit(1);return}if(!g.enabled){b({error:"TIP_NOT_AVAILABLE",message:"Tipping is not available for this ride/region."}),process.exit(1);return}m=r??g.currency;let _=Ze(St(c.region),o.cliGatewayHosts,o.cliGatewayHost),E=await Jr(l,n,_);if(E==null)return;f=E}try{let g=await l.payTip(s,{amount:a,currency:m,paymentItemUuid:f});g.tipStatus?.toUpperCase()==="PAID"&&await Dx(o.dataDir,s),w(g)}catch(g){if(g instanceof Be)g.code==="tip_not_available"?b({error:"TIP_NOT_AVAILABLE",message:"Tipping is not available yet. The fare may still be settling (try again in a moment), or the tip window has passed / the region is disabled."}):g.code==="tip_already_paid"?b({error:"TIP_ALREADY_PAID",message:"This ride has already been tipped."}):g.status===402?b({error:"TIP_PAYMENT_FAILED",message:"Payment failed. Check the card and try again."}):g.status===400?b({error:"TIP_AMOUNT_INVALID",message:"Tip amount is outside the allowed range. Run `amb tip-config <region>`."}):g.status===401||g.code==="unauthorized"?b({error:"SESSION_EXPIRED",message:"Your TADA/Throo session expired. Run `amb login` again."}):b({error:"TIP_FAILED",message:g.message});else{let _=g.message??"";_.toLowerCase().includes("insufficient")||_.toLowerCase().includes("balance")?b({error:"INSUFFICIENT_BALANCE",message:_,action:"Run `amb wallet-balance` and top up your wallet."}):b({error:"TIP_FAILED",message:_})}process.exit(1)}},l0=async e=>{let[t,r,n]=e,s=r?parseFloat(r):NaN;(!t||isNaN(s)||!n)&&(console.error("error: Usage: amb tip-prepare <request_id> <price> <wallet_address>"),process.exit(1));let i=D();O(i.dataDir),J(n),he(n),_e(i.gatewayServerUrl),hr(i.gatewayServerUrl);try{let a=await fo({request_id:t,price:s,wallet_address:n,config:i});w(a)}catch(a){b({error:"TIP_PREPARE_FAILED",message:a.message}),process.exit(1)}},u0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb tip-confirm <request_id> <signature>"),console.error("hint: signature: hex from `amb wallet-sign` with sign_method=eth_signTypedData_v4"),process.exit(1));let n=D();O(n.dataDir),hr(n.gatewayServerUrl);try{let s=await go({request_id:t,signature:r});s.success&&await Dx(n.dataDir,t),w(s)}catch(s){let i=s.message??"";i.includes("PAYMENT_CACHE_MISS")?b({error:"PAYMENT_CACHE_MISS",message:i,action:"Session expired. Run `amb tip-prepare` again."}):i.toLowerCase().includes("insufficient")||i.toLowerCase().includes("balance")?b({error:"INSUFFICIENT_BALANCE",message:i,action:"Run `amb wallet-balance` and top up your wallet."}):b({error:"TIP_CONFIRM_FAILED",message:i}),process.exit(1)}},Ox={"tip-config":o0,tip:c0,"tip-prepare":l0,"tip-confirm":u0};p();p();var Nx=new Set(["maps.app.goo.gl","goo.gl"]),d0=new Set(["www.google.com","google.com","maps.google.com"]),Cx=5;function Tr(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function p0(e){let t=e;for(let r=0;r<Cx;r++){let n=new URL(t);if(!Nx.has(n.host))return t;let s;try{s=await fetch(t,{redirect:"manual",method:"HEAD"})}catch(i){Tr("URL_RESOLVE_FAILED",i.message)}if(s.status>=300&&s.status<400){let i=s.headers.get("location");i||Tr("URL_RESOLVE_FAILED","redirect status without Location header"),t=new URL(i,t).toString();continue}Tr("URL_RESOLVE_FAILED",`unexpected status ${s.status} on short link`)}Tr("URL_RESOLVE_FAILED",`redirect chain exceeded ${Cx}`)}function m0(e){let t=e.match(/\/maps\/place\/([^/]+)/);if(!t)return;let r=decodeURIComponent(t[1].replace(/\+/g," ")),n=r.indexOf(",");return(n>=0?r.slice(0,n):r).trim()}function f0(e){let t=e.match(/!3d(-?\d+(?:\.\d+)?)!4d(-?\d+(?:\.\d+)?)/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function g0(e){let t=e.match(/\/@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function h0(e){let t=e.match(/!1s(0x[0-9a-fA-F]+:0x[0-9a-fA-F]+)/);return t?t[1]:void 0}async function Su(e){let t;try{t=new URL(e)}catch{Tr("INVALID_URL","not a parseable URL")}if(Nx.has(t.host)){let a=await p0(e);return Su(a)}d0.has(t.host)||Tr("INVALID_URL",`host ${t.host} not in allowlist`);let r=t.pathname,n=f0(r)??g0(r);n||Tr("COORDS_NOT_FOUND_IN_URL");let s=m0(r)??Tr("INVALID_URL","no /place/<name>/ segment"),i=h0(r);return{name:s,latitude:n.lat,longitude:n.lng,...i&&{ftid:i}}}p();var Iu="";function Lx(e){Iu=e.replace(/\/$/,"")}function qn(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function kx(e,t){Iu||qn("RESOLVE_FAILED","initSavedPlacesApi not called");let r=await fetch(`${Iu}/v1/places/resolve-google`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)try{return await r.json()}catch(n){qn("RESOLVE_FAILED",`malformed JSON response: ${n.message}`)}r.status===404&&qn("PLACE_NOT_FOUND"),r.status===422&&qn("REGION_UNSUPPORTED"),r.status===401&&qn("JWT_EXPIRED"),qn("RESOLVE_FAILED",`status ${r.status}`)}p();function y0(e){if(!e)return null;let t=e.match(/^0x[0-9a-fA-F]+:0x([0-9a-fA-F]+)$/);if(!t)return null;try{return BigInt("0x"+t[1])}catch{return null}}function _0(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=Buffer.from(r,"base64");if(n.length<8)throw new Error("place_id too short");let s=0n;for(let i=0;i<8;i++)s|=BigInt(n[n.length-8+i])<<BigInt(8*i);return s}async function Mx(e){let t=y0(e);if(t===null)return null;let s=`https://www.google.com/maps/preview/place?hl=en&gl=us&pb=${`!1m4!1s${`0x0%3A0x${t.toString(16)}`}!3m2!2m1!1i1`}`;try{let i=await fetch(s,{headers:{"User-Agent":"Mozilla/5.0"}});if(!i.ok)return null;let o=(await i.text()).match(/ChI[A-Za-z0-9_-]{15,}/g)??[];for(let c of o)try{if(_0(c)===t)return c}catch{}return null}catch{return null}}p();function Ux(e,t,r){return yr("/v1/places",e,{query:{query:t.query,region:t.region,city:t.city,originLat:t.originLat,originLng:t.originLng,sessionToken:t.sessionToken},lang:r})}function Fx(e,t,r,n){return yr(`/v1/places/${encodeURIComponent(t)}`,e,{query:{region:r.region,city:r.city},lang:n})}function jx(e,t,r){return yr("/v1/places/nearby",e,{query:{latitude:t.latitude,longitude:t.longitude,limit:t.limit},lang:r})}function qx(e,t,r){return yr("/v1/places/airports",e,{query:{city:t.city},lang:r})}function Bx(e,t,r){return yr("/v1/places/reverse-geocode",e,{query:{latitude:t.latitude,longitude:t.longitude,region:t.region},lang:r})}function Vs(e){let t=[],r,n,s;for(let i=0;i<e.length;i++){let a=e[i];a==="--city"&&e[i+1]!=null?r=e[++i]:a==="--session-token"&&e[i+1]!=null?n=e[++i]:a==="--lang"&&e[i+1]!=null?s=e[++i]:t.push(a)}return{positional:t,city:r,sessionToken:n,lang:s}}function Gs(e){switch(e.code){case"unsupported_region":return"Region not supported (currently NY, SG). Re-run with a supported region.";case"place_not_found":return"Place not found. Check the place id or coordinates and try again.";case"invalid_parameter":return"Invalid parameter. Check the query, region, or coordinates.";case"place_api_error":return"Place search is temporarily unavailable. Please try again.";default:return e.message}}function Pu(e){b({error:"NOT_SUPPORTED",message:`tada ${e} is only available for TADA/Throo members. Run 'amb login' first.`}),process.exit(1)}var E0=async e=>{if(ze().mode==="tada"){let{positional:d,city:m,sessionToken:f,lang:g}=Vs(e),[_,E,T,x]=d;(!_||!E)&&(console.error("error: Usage: amb place-search <query> <region> [originLat originLng] [--city CODE] [--session-token UUID] [--lang TAG]"),console.error("hint: region: NY, SG. multi-word query is quoted."),process.exit(1)),T!==void 0!=(x!==void 0)&&(b({error:"INVALID_COORDINATES",message:"originLat and originLng must be provided together."}),process.exit(1));let R=T!==void 0?parseFloat(T):void 0,I=x!==void 0?parseFloat(x):void 0;(R!==void 0&&isNaN(R)||I!==void 0&&isNaN(I))&&(b({error:"INVALID_COORDINATES",message:"originLat and originLng must be valid numbers."}),process.exit(1));let N=D();O(N.dataDir),kn(Ye(N.cliGatewayHosts,N.cliGatewayHost));let k;try{k=await $t(N)}catch(B){b({error:"MEMBER_AUTH_FAILED",message:B.message}),process.exit(1);return}try{let B=await Ux(k,{query:_,region:E,city:m,originLat:R,originLng:I,sessionToken:f},g);w({...B,next_action:"PICK_A_PLACE_THEN_BUILD_RIDE_LOCATIONS",must:"Copy place_id / sub_places[].id / lat_lng / name / address verbatim from this response. Never fabricate them. A Google candidate with lat_lng:null must be resolved via place-detail before booking."})}catch(B){b({error:"PLACE_SEARCH_FAILED",message:Gs(B)}),process.exit(1)}return}let t=e[0],r=e[1],n=e[2],s=e[3],i=e[4];(!t||!r||!n)&&(console.error("error: Usage: amb place-search <wallet_address> <city> <query> [latitude] [longitude]"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let a=Os(r);a||(b({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${r}". Use codes like SIN, BKK, DEN or full names like Singapore, Bangkok, Denver.`}),process.exit(1));let o=s!==void 0?parseFloat(s):void 0,c=i!==void 0?parseFloat(i):void 0;s!==void 0!=(i!==void 0)&&(b({error:"INVALID_COORDINATES",message:"latitude and longitude must both be provided together."}),process.exit(1)),(s!==void 0&&isNaN(o)||i!==void 0&&isNaN(c))&&(b({error:"INVALID_COORDINATES",message:"latitude and longitude must be valid numbers."}),process.exit(1));let u=D();O(u.dataDir),J(t),he(t),le(u.appServerUrl),_e(u.gatewayServerUrl);let l=ie(t);l||(b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let d=await Xb(l,n,a,o,c);d.length===0?w({results:[],next_action:"REPORT_NO_MATCHES_TO_USER"}):w({results:d,next_action:"ASK_USER_TO_PICK_ONE_RESULT",must:"placeId passed to any subsequent command (amb place-detail, amb map-session-create, amb ride-request) MUST be a value taken verbatim from results[].placeId of this response. NEVER fabricate or substitute a place ID from any external system or from your own model knowledge. If a chosen result has subPlaces, amb map-session-create + amb map-session-verify is mandatory and the user must pick a subPlace on the map \u2014 do NOT enumerate subPlaces as text."})}catch(d){b({error:"PLACE_SEARCH_FAILED",message:d.message}),process.exit(1)}},T0=async e=>{if(ze().mode==="tada"){let{positional:o,city:c,lang:u}=Vs(e),[l,d,m]=o,f=c??m;(!l||!d)&&(console.error("error: Usage: amb place-detail <place_id> <region> [city] [--lang TAG]"),console.error("hint: region: NY, SG"),process.exit(1));let g=D();O(g.dataDir),kn(Ye(g.cliGatewayHosts,g.cliGatewayHost));let _;try{_=await $t(g)}catch(E){b({error:"MEMBER_AUTH_FAILED",message:E.message}),process.exit(1);return}try{let E=await Fx(_,l,{region:d,city:f},u);w(E)}catch(E){b({error:"PLACE_DETAIL_FAILED",message:Gs(E)}),process.exit(1)}return}let t=e[0],r=e[1],n=e[2];(!t||!r||!n)&&(console.error("error: Usage: amb place-detail <wallet_address> <city> <place_id>"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let s=Os(r);s||(b({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${r}". Use codes like SIN, BKK, DEN or full names like Singapore, Bangkok, Denver.`}),process.exit(1));let i=D();O(i.dataDir),J(t),he(t),le(i.appServerUrl),_e(i.gatewayServerUrl);let a=ie(t);a||(b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let o=await Qb(a,n,s);w(o)}catch(o){b({error:"PLACE_DETAIL_FAILED",message:o.message}),process.exit(1)}},b0=async e=>{let t=e[0],r=e[1],n,s=!1;for(let g=2;g<e.length;g++)e[g]==="--label"&&e[g+1]!=null?(n=e[g+1],g++):e[g]==="--force"&&(s=!0);(!t||!r)&&(console.error("error: Usage: amb place-save <wallet_address> <google_maps_url> [--label LABEL]"),process.exit(1));let i=D();O(i.dataDir),J(t),he(t),Lx(i.gatewayServerUrl);let a=ie(t);a||(console.error(JSON.stringify({error:"JWT_NOT_FOUND",message:"No valid JWT. Run siwe-request-message.js + siwe-submit.js first."})),process.exit(1));let o;try{o=await Su(r)}catch(g){let _=g.code??"INVALID_URL";console.error(JSON.stringify({error:_,message:g.message})),process.exit(1)}let c=await Mx(o.ftid),u;try{u=await kx(a,{name:o.name,latitude:o.latitude,longitude:o.longitude,...o.ftid&&{ftid:o.ftid},...c&&{resolvedPlaceId:c}})}catch(g){let _=g.code??"RESOLVE_FAILED";console.error(JSON.stringify({error:_,message:g.message})),process.exit(1)}u.match==="approximate"&&!s&&(console.error(JSON.stringify({error:"APPROXIMATE_MATCH_NEEDS_FORCE",message:"This URL did not resolve to an exact place. Confirm the place below with the user, then re-run with --force to save it.",candidate:{name:u.name,formatted_address:u.formattedAddress},match:u.match})),process.exit(1));let l=Cn({placeId:u.googlePlaceId,latitude:u.location.latitude,longitude:u.location.longitude}),d,m=!1,f={wallet_address:t,label:n??null,name:u.name,formatted_address:u.formattedAddress,latitude:u.location.latitude,longitude:u.location.longitude,google_place_id:u.googlePlaceId,city:u.city,region:u.region,ftid:o.ftid??null,kg_id:null,source_url:r};l?fu(t,l)?(d=gu(t,l,{...n!==void 0&&{label:n},source_url:r,google_place_id:u.googlePlaceId,ftid:o.ftid??null,kg_id:null,formatted_address:u.formattedAddress,name:u.name,city:u.city,region:u.region}),m=!0):d=pu(f):d=pu(f),console.log(JSON.stringify({...d,was_promoted:m},null,2))},v0=async e=>{let t=e[0],r=[],n=!1,s=!1,i;for(let l=1;l<e.length;l++){let d=e[l];if(d==="--match"&&e[l+1]!=null)r.push(e[l+1]),l++;else if(d==="--favorites-only")n=!0;else if(d==="--history-only")s=!0;else if(d==="--limit"&&e[l+1]!=null){let m=e[l+1],f=parseInt(m,10);(!/^\d+$/.test(m)||f<=0)&&(console.log(JSON.stringify({error:"INVALID_LIMIT",value:m})),process.exit(1)),i=f,l++}else d==="--limit"&&(console.log(JSON.stringify({error:"INVALID_LIMIT",message:"--limit requires a positive integer value"})),process.exit(1))}t||(console.error("error: Usage: amb place-list <wallet_address> [--match QUERY ...] [--favorites-only|--history-only] [--limit N]"),process.exit(1)),n&&s&&(console.log(JSON.stringify({error:"CONFLICTING_FILTERS"})),process.exit(1));let a=i??50,o=D();O(o.dataDir),J(t);let c={favoritesOnly:n,historyOnly:s,limit:a},u;r.length===0?u={matches:mu(t,c),matched_tier:null,normalized_queries:[]}:u=ov(t,r,c),console.log(JSON.stringify({matches:u.matches,matched_tier:u.matched_tier,queries:u.normalized_queries,next_action:"USE_FOR_RIDE_OR_FALLBACK_TO_PLACE_SEARCH"},null,2))},x0=async e=>{let t=e[0],r=e[1];(!t||!r)&&(console.error("error: Usage: amb place-remove <wallet_address> <id_or_label>"),process.exit(1));let n=D();O(n.dataDir),J(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i=s!=null?cv(t,s):lv(t,r);if(!i){console.log(JSON.stringify({removed:0,error:"NOT_FOUND"}));return}console.log(JSON.stringify({removed:1,id:i.id,label:i.label}))},R0=async e=>{let t=e[0],r=e[1],n;for(let u=2;u<e.length;u++)e[u]==="--label"&&e[u+1]!=null&&(n=e[u+1],u++);(!t||!r)&&(console.error("error: Usage: amb place-favorite <wallet_address> <id_or_dedup_key> [--label LABEL]"),process.exit(1));let s=D();O(s.dataDir),J(t);let i=/^\d+$/.test(r)?parseInt(r,10):null,a;i!=null?a=Ns(t,i):a=fu(t,r),a||(console.log(JSON.stringify({error:"NOT_FOUND"})),process.exit(1));let o=a.is_favorite===1,c=i!=null?dv(t,i,n):gu(t,r,{...n!==void 0&&{label:n}});console.log(JSON.stringify({...c,was_favorite_before:o},null,2))},A0=async e=>{let t=e[0],r=e[1];(!t||!r)&&(console.error("error: Usage: amb place-unfavorite <wallet_address> <id_or_label>"),process.exit(1));let n=D();O(n.dataDir),J(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i;if(s!=null?i=Ns(t,s):i=pv(t,r),i||(console.log(JSON.stringify({error:"NOT_FOUND"})),process.exit(1)),i.is_favorite===0){console.log(JSON.stringify({info:"ALREADY_NOT_FAVORITE",row:i},null,2));return}let a=s!=null?mv(t,s):fv(t,r);console.log(JSON.stringify({...a,was_favorite_before:!0},null,2))},w0=async e=>{ze().mode!=="tada"&&Pu("place-nearby");let{positional:t,lang:r}=Vs(e),[n,s,i]=t;(!n||!s)&&(console.error("error: Usage: amb place-nearby <lat> <lng> [limit] [--lang TAG]"),process.exit(1));let a=parseFloat(n),o=parseFloat(s),c=i!==void 0?parseInt(i,10):void 0;(isNaN(a)||isNaN(o)||i!==void 0&&isNaN(c))&&(b({error:"INVALID_COORDINATES",message:"lat/lng (and limit) must be valid numbers."}),process.exit(1));let u=D();O(u.dataDir),kn(Ye(u.cliGatewayHosts,u.cliGatewayHost));let l;try{l=await $t(u)}catch(d){b({error:"MEMBER_AUTH_FAILED",message:d.message}),process.exit(1);return}try{w(await jx(l,{latitude:a,longitude:o,limit:c},r))}catch(d){b({error:"PLACE_NEARBY_FAILED",message:Gs(d)}),process.exit(1)}},S0=async e=>{ze().mode!=="tada"&&Pu("place-airports");let{positional:t,lang:r}=Vs(e),[n]=t;n||(console.error("error: Usage: amb place-airports <city> [--lang TAG]"),console.error("hint: city = TADA city code, e.g. NYC"),process.exit(1));let s=D();O(s.dataDir),kn(Ye(s.cliGatewayHosts,s.cliGatewayHost));let i;try{i=await $t(s)}catch(a){b({error:"MEMBER_AUTH_FAILED",message:a.message}),process.exit(1);return}try{w(await qx(i,{city:n},r))}catch(a){b({error:"PLACE_AIRPORTS_FAILED",message:Gs(a)}),process.exit(1)}},I0=async e=>{ze().mode!=="tada"&&Pu("place-reverse-geocode");let{positional:t,lang:r}=Vs(e),[n,s,i]=t;(!n||!s||!i)&&(console.error("error: Usage: amb place-reverse-geocode <lat> <lng> <region> [--lang TAG]"),console.error("hint: region: NY, SG"),process.exit(1));let a=parseFloat(n),o=parseFloat(s);(isNaN(a)||isNaN(o))&&(b({error:"INVALID_COORDINATES",message:"lat/lng must be valid numbers."}),process.exit(1));let c=D();O(c.dataDir),kn(Ye(c.cliGatewayHosts,c.cliGatewayHost));let u;try{u=await $t(c)}catch(l){b({error:"MEMBER_AUTH_FAILED",message:l.message}),process.exit(1);return}try{w(await Bx(u,{latitude:a,longitude:o,region:i},r))}catch(l){b({error:"PLACE_REVERSE_GEOCODE_FAILED",message:Gs(l)}),process.exit(1)}},Vx={"place-search":E0,"place-detail":T0,"place-save":b0,"place-list":v0,"place-remove":x0,"place-favorite":R0,"place-unfavorite":A0,"place-nearby":w0,"place-airports":S0,"place-reverse-geocode":I0};p();import{readFileSync as P0}from"fs";p();async function Du(e,t,r){let n=r?.pollIntervalMs??1e3,s=r?.timeoutMs??5*6e4,i=r?.authUrl??"",a=Date.now()+s,o=`${e.gatewayServerUrl}/v1/map-session/${t}/result`;for(;;){let c;try{c=await(await fetch(o)).json()}catch(l){process.stderr.write(`map-session-check poll_error: ${l.message}
564
+ `)}let u=c?.status;if(u==="completed"&&!c?.result)return{status:"failed",reason:"completed_missing_result"};if(u==="completed"&&c?.result)return{status:"ready",result:c.result};if(u==="jwt_expired"||u==="cancelled"||u==="expired")return{status:"failed",reason:u};if(Date.now()>=a)return{status:"pending",auth_url:i};await new Promise(l=>setTimeout(l,n))}}function Hx(e){let t=[],r,n,s,i=!1;for(let a=0;a<e.length;a++)e[a]==="--subplaces"&&a+1<e.length?r=e[++a]:e[a]==="--subplaces-file"&&a+1<e.length?n=e[++a]:e[a]==="--purpose"&&a+1<e.length?s=e[++a]:e[a]==="--no-wait"?i=!0:t.push(e[a]);return{positional:t,subplacesJson:r,subplacesFile:n,purpose:s,noWait:i}}function Ou(e){try{let t=JSON.parse(e);if(Array.isArray(t))return t;if(Array.isArray(t.subPlaces))return t.subPlaces}catch{}}function $x(e,t={}){let r=t.purpose?{...e,purpose:t.purpose}:e;if(Kn()==="json"){w(r),e.status==="failed"&&process.exit(1);return}if(e.status==="ready"){let n=e.result.subPlaceId?` (subPlace=${e.result.subPlaceId})`:"";process.stdout.write(`\u2713 Selected: ${e.result.name}, ${e.result.address} (lat=${e.result.lat}, lng=${e.result.lng})${n}
448
565
  `);return}if(e.status==="pending"){process.stderr.write(`\u23F3 Still waiting. Resume with: amb map-session-verify <session_id>
449
566
  auth_url: ${e.auth_url}
450
567
  `);return}process.stderr.write(`\u2717 Map session failed: ${e.reason}
451
- `),process.exit(1)}var Tl=async e=>{let{positional:t,subplacesJson:r,subplacesFile:n,purpose:s,noWait:i}=Sl(e),o=t[0],a=t[1],c=t[2],l=t[3],d=t.slice(4).join(" ")||void 0;(!o||!a)&&(console.error("error: Usage: map-session <wallet_address> <city> [lat] [lng] [name] [--subplaces JSON | --subplaces-file PATH] [--purpose origin|destination] [--no-wait]"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let u=Lt(a);u||(g({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${a}"`}),process.exit(1));let m=Pt[u],p=c?parseFloat(c):void 0,f=l?parseFloat(l):void 0,_=R();b(_.dataDir),k(o),$(o);let h=P(o);h||(g({error:"JWT_NOT_FOUND"}),process.exit(1)),H(_.gatewayServerUrl);let I;if(r)I=ks(r);else if(n)try{let E=wf(n,"utf-8");I=ks(E)}catch{}else if(!process.stdin.isTTY){let E=[];for await(let N of process.stdin)E.push(Buffer.from(N));let A=Buffer.concat(E).toString("utf-8").trim();A&&(I=ks(A))}try{let E=await fetch(`${_.gatewayServerUrl}/v1/map-session`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({initialLat:p,initialLng:f,initialName:d,city:u,region:m,subPlaces:I})});if(!E.ok){let re=await E.text();g({error:"MAP_SESSION_CREATE_FAILED",status:E.status,message:re}),process.exit(1)}let A=await E.json();if(A.mapUrl&&!A.mapUrl.startsWith("http")&&(A.mapUrl=`${_.webappUrl}${A.mapUrl}`),s&&(A.purpose=s),i){w(A);return}let{sessionId:N,mapUrl:C=""}=A;N||(g({error:"MAP_SESSION_INVALID_RESPONSE",message:"response missing sessionId"}),process.exit(1)),process.stderr.write(`Open this URL to pick a location:
452
- ${C}
568
+ `),process.exit(1)}var Gx=async e=>{let{positional:t,subplacesJson:r,subplacesFile:n,purpose:s,noWait:i}=Hx(e),a=t[0],o=t[1],c=t[2],u=t[3],l=t.slice(4).join(" ")||void 0;(!a||!o)&&(console.error("error: Usage: map-session <wallet_address> <city> [lat] [lng] [name] [--subplaces JSON | --subplaces-file PATH] [--purpose origin|destination] [--no-wait]"),console.error("hint: city: SIN (Singapore), NYC (New York)"),process.exit(1));let d=Os(o);d||(b({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${o}"`}),process.exit(1));let m=Ds[d],f=c?parseFloat(c):void 0,g=u?parseFloat(u):void 0,_=D();O(_.dataDir),J(a),he(a);let E=ie(a);E||(b({error:"JWT_NOT_FOUND"}),process.exit(1)),_e(_.gatewayServerUrl);let T;if(r)T=Ou(r);else if(n)try{let x=P0(n,"utf-8");T=Ou(x)}catch{}else if(!process.stdin.isTTY){let x=[];for await(let I of process.stdin)x.push(Buffer.from(I));let R=Buffer.concat(x).toString("utf-8").trim();R&&(T=Ou(R))}try{let x=await fetch(`${_.gatewayServerUrl}/v1/map-session`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({initialLat:f,initialLng:g,initialName:l,city:d,region:m,subPlaces:T})});if(!x.ok){let B=await x.text();b({error:"MAP_SESSION_CREATE_FAILED",status:x.status,message:B}),process.exit(1)}let R=await x.json();if(R.mapUrl&&!R.mapUrl.startsWith("http")&&(R.mapUrl=`${_.webappUrl}${R.mapUrl}`),s&&(R.purpose=s),i){w(R);return}let{sessionId:I,mapUrl:N=""}=R;I||(b({error:"MAP_SESSION_INVALID_RESPONSE",message:"response missing sessionId"}),process.exit(1)),process.stderr.write(`Open this URL to pick a location:
569
+ ${N}
453
570
 
454
571
  Waiting (up to 5 minutes)\u2026
455
- `);let U=await Ns(_,N,{authUrl:C});Al(U,{purpose:s})}catch(E){g({error:"MAP_SESSION_CREATE_FAILED",message:E.message}),process.exit(1)}},Ef=async e=>{let{positional:t,purpose:r}=Sl(e),n=t[0];n||(console.error("error: Usage: map-session-verify <session_id> [--purpose origin|destination]"),process.exit(1));let s=R(),i=await Ns(s,n,{});Al(i,{purpose:r})},Il={"map-session-create":e=>Tl(e.includes("--no-wait")?e:[...e,"--no-wait"]),"map-session":Tl,"map-session-verify":Ef};var Rf=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb phone-verify-start <wallet_address> <phone>"),console.error("hint: phone: E.164 format (e.g. +12125550100)"),process.exit(1));let n=R();b(n.dataDir),k(t),$(t);let s=P(t);O(n.appServerUrl),H(n.gatewayServerUrl);try{let i=await Wa(s,r);i.status==="ALREADY_VERIFIED"&&Rr(t,r),w(i)}catch(i){g({error:i.message}),process.exit(1)}},bf=async e=>{let[t,r,n]=e;(!t||!r||!n)&&(console.error("error: Usage: amb phone-verify-confirm <wallet_address> <phone> <code>"),console.error("hint: phone: E.164 format (e.g. +12125550100). code: 6-digit OTP from SMS"),process.exit(1));let s=R();b(s.dataDir),k(t),$(t);let i=P(t);O(s.appServerUrl),H(s.gatewayServerUrl);try{let o=await Va(i,r,n);o.status==="ok"&&Rr(t,r),w({status:o.status})}catch(o){g({error:o.message}),process.exit(1)}},Tf=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb phone-verify-check <wallet_address> <phone>"),console.error("hint: phone: E.164 format (e.g. +12125550100)"),process.exit(1));let n=R();b(n.dataDir),k(t),$(t);let s=P(t);O(n.appServerUrl),H(n.gatewayServerUrl);try{let i=await Ga(s,r);i.verified&&Rr(t,r),w(i)}catch(i){g({error:i.message}),process.exit(1)}},xl={"phone-verify-start":Rf,"phone-verify-confirm":bf,"phone-verify-check":Tf};import Cs from"fs";import Sf from"path";var Af=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb siwe-request-message <wallet_address> <chain_id>"),console.error("hint: chain_id: 84532 (BASE_SEPOLIA), 11155111 (ETH_SEPOLIA)"),process.exit(1));let n=R();b(n.dataDir),k(t),O(n.appServerUrl);try{let{message:s,expiresAt:i}=await Nr(t,parseInt(r,10));Cs.mkdirSync(n.dataDir,{recursive:!0});let o=`siwe-${t}-exp${i}.json`,a=Sf.join(n.dataDir,o);Cs.writeFileSync(a,JSON.stringify({message:s,walletAddress:t,expiresAt:i},null,2),{mode:384}),w({message:s,siwe_file:a,expires_at:new Date(i*1e3).toISOString()})}catch(s){g({error:s.message}),process.exit(1)}},If=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb siwe-submit <siwe_file> <signature>"),console.error("hint: siwe_file is the file path returned by `amb siwe-request-message`"),console.error(" signature is the wallet_signature from `amb wallet-sign`"),process.exit(1));let n=R();b(n.dataDir),O(n.appServerUrl);try{let{message:s,expiresAt:i}=JSON.parse(Cs.readFileSync(t,"utf8"));Date.now()/1e3>i&&(g({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1));let o=await kr(s,r);w({access_token:o.accessToken,expires_in:o.expiresIn})}catch(s){g({error:s.message}),process.exit(1)}},vl={"siwe-request-message":Af,"siwe-submit":If};import*as Ds from"fs";import*as kl from"path";import{io as vf}from"socket.io-client";import xf from"net";function Nl(e,t,r={}){let n=r.connectTimeoutMs??1e3,s=r.responseTimeoutMs??cn;return new Promise(i=>{let o=!1,a=m=>{if(!o){o=!0;try{c.destroy()}catch{}clearTimeout(l),clearTimeout(d),i(m)}},c=xf.connect(e),l=setTimeout(()=>a({ok:!1,reason:"monitor_unreachable"}),n),d=setTimeout(()=>{},0);clearTimeout(d);let u="";c.on("connect",()=>{clearTimeout(l),d=setTimeout(()=>a({ok:!1,reason:"response_timeout"}),s);try{c.write(JSON.stringify({content:t})+`
456
- `)}catch(m){a({ok:!1,reason:`write_failed: ${m.message}`})}}),c.on("data",m=>{u+=m.toString();let p=u.indexOf(`
457
- `);if(!(p<0))try{let f=JSON.parse(u.slice(0,p));a(f&&typeof f=="object"&&"ok"in f?f:{ok:!1,reason:"bad_response"})}catch{a({ok:!1,reason:"bad_response"})}}),c.on("error",()=>a({ok:!1,reason:"monitor_unreachable"})),c.on("end",()=>a({ok:!1,reason:"no_response"}))})}var Nf={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function kf(e,t,r,n){let i=new URL(e.gatewayServerUrl).origin,o=vf(`${i}/chat`,{path:"/tada-ton/chat-socket",transports:["websocket"],auth:{token:r}});return new Promise(a=>{let c=!1,l,d;function u(p){c||(c=!0,clearTimeout(l),clearTimeout(d),o.disconnect(),a(p))}function m(p){u({ok:!1,reason:p})}o.on("connect_error",p=>{m(`socket connection failed: ${p.message}`)}),new Promise((p,f)=>{l=setTimeout(()=>f(new Error("join room timeout")),1e4),o.emit("JOIN_ROOM",{rideRequestId:t}),o.once("MESSAGE_SENT",_=>{if(clearTimeout(l),_.event!=="joined"){f(new Error(`unexpected join event: ${_.event}`));return}let h=_.roomId;d=setTimeout(()=>f(new Error("send message timeout")),1e4),o.emit("SEND_MESSAGE",{roomId:h,content:n,type:"TEXT"}),o.once("MESSAGE_SENT",()=>{clearTimeout(d),p()})})}).then(()=>{u({ok:!0})},p=>{m(p.message)})})}var Cf=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb chat-send-message <request_id> <content>"),process.exit(1));let n=R();b(n.dataDir);let s=V(t);if(s||(g({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let l;try{({backend:l}=await te(n,s))}catch(d){g({error:"AUTH_FAILED",message:d.message,request_id:t}),process.exit(1)}try{let d=await l.sendChat(t,{message:r});w(d)}catch(d){let u=d instanceof Y?d.code:"CHAT_SEND_FAILED";g({error:u,message:d.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;k(i),$(i);let o=P(i);o||(g({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1)),xe(t);let a=await Nl(ln(F(),t),r);if(a.ok){w({success:!0,via:"monitor"});return}let c=await kf(n,t,o,r);if(c.ok){w({success:!0,via:"fallback"});return}g({error:"CHAT_SEND_FAILED",primary:a.reason,fallback:c.reason}),process.exit(1)},Df=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb chat-send-image <request_id> <image_path>"),process.exit(1));let n=kl.extname(r).toLowerCase(),s=Nf[n];s||(g({error:"UNSUPPORTED_FORMAT",message:`Unsupported image format: "${n}". Supported: jpeg, jpg, png, gif, webp`}),process.exit(1));let i=R();b(i.dataDir);let o=V(t);if(o||(g({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}`}),process.exit(1)),!o.wallet_address){let d;try{d=Ds.readFileSync(r)}catch(m){g({error:"FILE_READ_FAILED",message:m.message}),process.exit(1)}let u;try{({backend:u}=await te(i,o))}catch(m){g({error:"AUTH_FAILED",message:m.message,request_id:t}),process.exit(1)}try{let m=await u.sendChat(t,{image:{buffer:d,mimetype:s}});w(m)}catch(m){let p=m instanceof Y?m.code:"CHAT_SEND_FAILED";g({error:p,message:m.message,request_id:t}),process.exit(1)}return}let a=o.wallet_address;k(a),$(a),H(i.gatewayServerUrl);let c=P(a),l;try{l=Ds.readFileSync(r)}catch(d){g({error:"FILE_READ_FAILED",message:d.message}),process.exit(1)}try{let d=await Jr(c,t,l,s);w(d)}catch(d){g({error:"CHAT_SEND_IMAGE_FAILED",message:d.message}),process.exit(1)}},Pf=async e=>{let[t,r]=e;t||(console.error("error: Usage: amb chat-get-messages <request_id> [cursor]"),process.exit(1));let n=R();b(n.dataDir);let s=V(t);if(s||(g({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let a;try{({backend:a}=await te(n,s))}catch(c){g({error:"AUTH_FAILED",message:c.message,request_id:t}),process.exit(1)}try{w(await a.getMessages(t,r?Number(r):void 0))}catch(c){let l=c instanceof Y?c.code:"CHAT_GET_FAILED";g({error:l,message:c.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;k(i),$(i),H(n.gatewayServerUrl);let o=P(i);o||(g({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let a=await Vr(t,o,r);w(a)}catch(a){g({error:"CHAT_GET_FAILED",message:a.message}),process.exit(1)}},Cl={"chat-send-message":Cf,"chat-send-image":Df,"chat-get-messages":Pf};import*as v from"fs";import*as M from"path";import*as hn from"os";import*as Pl from"crypto";import{spawnSync as Lf}from"child_process";import Of from"better-sqlite3";function Mf(e){if(!v.existsSync(e))return{};let t={};for(let r of v.readFileSync(e,"utf8").split(`
458
- `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");s<=0||(t[n.slice(0,s).trim()]=n.slice(s+1).trim())}return t}var Uf;function Dl(e){try{return process.kill(e,0),!0}catch{return!1}}function Ps(e){let t=M.join(e,"run"),r=`${e}.amb-migration-quiesced`;if(v.existsSync(r)){let i=Number.parseInt(v.readFileSync(r,"utf8").trim(),10);if(Number.isSafeInteger(i)&&i>1&&Dl(i))throw new Error("MIGRATION_CONFLICT: legacy quiescence is held");v.unlinkSync(r)}let n=v.openSync(r,"wx",384);v.writeFileSync(n,`${process.pid}
459
- `),v.closeSync(n);let s;try{if(v.existsSync(t))for(let a of v.readdirSync(t)){if(!/^(?:mon|sup|relay)-.+\.pid$/.test(a))continue;let c=Number.parseInt(v.readFileSync(M.join(t,a),"utf8").trim(),10);if(Number.isSafeInteger(c)&&c>1&&c!==process.pid&&Dl(c))throw new Error(`MIGRATION_CONFLICT: legacy writer pid ${c} is still active`)}let o=[M.join(e,"state","data","tada-ride-agent.db"),M.join(e,"state","data","ambient-ride.db"),M.join(e,"data","tada-ride-agent.db"),M.join(e,"data","ambient-ride.db")].find(a=>v.existsSync(a));o&&(s=new Of(o,{fileMustExist:!0,timeout:0}),s.pragma("wal_checkpoint(TRUNCATE)"),s.exec("BEGIN EXCLUSIVE"))}catch(i){try{s?.close()}catch{}try{v.unlinkSync(r)}catch{}throw i}return{release(){try{s?.inTransaction&&s.exec("ROLLBACK"),s?.close()}catch{}finally{s=void 0}try{v.unlinkSync(r)}catch{}}}}function Bf(e,t){return{legacyRoot:t,ambientRoot:e,stagingRoot:`${e}.migrating`,backupRoot:`${t}.bak`,lockPath:`${e}-migration.lock`}}function Ff(e){let t={},r=[];for(let n of e){if(!v.existsSync(n))continue;let s=JSON.parse(v.readFileSync(n,"utf8")),i=s.env;if(i&&typeof i=="object"&&!Array.isArray(i)){for(let[a,c]of Object.entries(i))if(typeof c=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(a)){if(t[a]!==void 0&&t[a]!==c)throw new Error(`MIGRATION_CONFLICT: managed settings disagree for ${a}`);t[a]=c}}let o=s.skills?.entries?.["tada-ride"]?.env;if(o&&typeof o=="object"&&!Array.isArray(o)){for(let[a,c]of Object.entries(o))if(typeof c=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(a)){if(t[a]!==void 0&&t[a]!==c)throw new Error(`MIGRATION_CONFLICT: managed settings disagree for ${a}`);t[a]=c}}r.push({path:n,json:s})}return{legacy:t,documents:r}}function $f(e,t,r){let n=[];for(let o of e.documents){let a=o.json.env,c=o.json.skills?.entries?.["tada-ride"]?.env;for(let d of[a,c]){if(!d||typeof d!="object"||Array.isArray(d))continue;let u=d,m=Object.fromEntries(Object.entries(u).filter(([f,_])=>typeof _=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(f))),p=He(m,t);for(let f of Object.keys(m))delete u[f];Object.assign(u,p.env)}let l=v.statSync(o.path);n.push({path:o.path,content:`${JSON.stringify(o.json,null,2)}
460
- `,original:v.readFileSync(o.path),mode:l.mode&511})}let s=r,i=[];try{for(let o of n)s(o.path,o.content,o.mode),i.push(o)}catch(o){for(let a of i.reverse())s(a.path,a.original,a.mode);throw o}}function Hf(e,t,r){let n=`${e}.amb-migration-${process.pid}.tmp`,s;try{s=v.openSync(n,"wx",r),v.writeFileSync(s,t),v.fsyncSync(s),v.closeSync(s),s=void 0,v.renameSync(n,e);let i=v.openSync(M.dirname(e),"r");try{v.fsyncSync(i)}finally{v.closeSync(i)}}catch(i){s!==void 0&&v.closeSync(s);try{v.unlinkSync(n)}catch{}throw i}}function qf(e={}){let t=e.ambientRoot??F(),r=e.legacyRoot??M.join(M.dirname(t),".tada"),n=e.skillDir??M.resolve(M.dirname(new URL(import.meta.url).pathname),".."),s=Kt(n),i=v.existsSync(s)?(e.quiesceLegacy??Ps)(s):void 0,o=M.join(t,"state","data");if(Tt(o)){let C=(e.quiesceLegacy??Ps)(t);try{Fi(o)}finally{C.release()}}let a=Bf(t,r),c=z().networks.paymentNetwork,l=e.managedSettingsPaths??[M.join(hn.homedir(),".claude","settings.json"),M.join(hn.homedir(),".openclaw","openclaw.json")],d=Ff(l),u=e.environmentSnapshot??{...process.env},m;try{or(s,M.join(r,"state")),m=(e.migrate??Mn)({paths:a,oldDataDir:M.join(r,"state","data"),oldKeysDir:M.join(r,"state","keys"),paymentNetwork:c,installManagedCli:e.installManagedCli??(()=>{}),smoke:e.smoke??(()=>{}),quiesceLegacy:()=>(e.quiesceLegacy??Ps)(r),managedLegacyLink:e.managedLegacyLink??M.join(hn.homedir(),".local","bin","tada"),expectedLegacyLinkTarget:e.expectedLegacyLinkTarget??M.join(r,"cli","tada"),transformEnv:(C,U)=>He([{name:"legacy-state",env:C},{name:"managed-settings",env:d.legacy},{name:"process-env",env:u}],U)})}finally{i?.release()}$f(d,c,e.replaceManagedFile??Hf);let p=M.join(t,"state","data"),f=M.join(t,"state","keys"),_=M.join(p,".installed"),h=M.join(p,".env");if(v.existsSync(_)){let C=JSON.parse(v.readFileSync(_,"utf8"));return{status:"already_installed",migration:m,output:{status:"already_installed",installed_at:C.installed_at,skill_dir:n,state_dir:t,data_dir:p,keys_dir:f,migration:m}}}v.mkdirSync(p,{recursive:!0,mode:448}),v.mkdirSync(f,{recursive:!0,mode:448});let I={...He(u,c).env,...He(d.legacy,c).env,...Mf(h)},E=I.AMB_RIDE_PASSPHRASE??Pl.randomBytes(32).toString("hex"),A=I.AMB_RIDE_PASSPHRASE?"preserved from existing .env":"newly generated",N={...I,AMB_RIDE_PASSPHRASE:E};return v.writeFileSync(h,["# Ambient Ride - auto-generated by amb install",`# Generated at: ${new Date().toISOString()}`,`# Source: ${A}`,...Object.entries(N).sort(([C],[U])=>C.localeCompare(U)).map(([C,U])=>`${C}=${U}`),""].join(`
461
- `),{mode:384}),v.writeFileSync(_,JSON.stringify({installed_at:new Date().toISOString(),skill_dir:n,layout:"self-contained"},null,2),{mode:384}),{status:"installed",migration:m,output:{status:"installed",skill_dir:n,state_dir:t,data_dir:p,keys_dir:f,env_file:h,passphrase_source:A,migration:m,next_steps:["No platform config edits needed \u2014 the skill is self-contained.","Run `amb whoami` to see onboarding state."]}}}var jf=async e=>{process.env.SUDO_UID&&(w({status:"skipped_sudo",message:"Skipped agent state init because this ran under sudo. If `amb install` has already been run as your own user, there is nothing to do; otherwise run it as your own user (on a root-only machine, `sudo env -u SUDO_UID amb install`)."}),process.exit(0));try{let r=qf(Uf??{installManagedCli(){let n=process.argv[1];if(!n||M.basename(n)!=="amb")throw new Error("MIGRATION_INTERRUPTED: Ambient CLI entrypoint is not verified");v.accessSync(n,v.constants.R_OK)},smoke(n){let s=Lf(process.execPath,[process.argv[1],"--json","whoami"],{encoding:"utf8",env:{...process.env,AMB_RIDE_STATE_DIR:n}});if(s.error||s.status!==0)throw new Error("MIGRATION_INTERRUPTED: Ambient runtime smoke failed")}});w(r.output),process.exit(0)}catch(t){let r=String(t),n=r.includes("BACKUP_EXISTS")?"MIGRATION_BACKUP_EXISTS":r.includes("VALIDATION")?"MIGRATION_VALIDATION_FAILED":r.includes("CONFLICT")?"MIGRATION_CONFLICT":"MIGRATION_INTERRUPTED";process.stderr.write(`${JSON.stringify({error:n,message:n})}
462
- `),process.exit(1)}},Gf=async e=>{let[t]=e;t||(console.error("error: Usage: amb setup-check <wallet_address>"),process.exit(1));let r=R();try{b(r.dataDir)}catch{w({wallet:{registered:!1,address:null,type:null,is_active:!1},jwt:null,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0)}let n=ye(t),s=n?{registered:!0,address:n.wallet_address,type:n.wallet_type}:{registered:!1,address:null,type:null};n||(w({wallet:s,jwt:null,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let i=to(n.wallet_address),o=i?{valid:!0,expires_at:i.expires_at}:{valid:!1,expires_at:null};i||(w({wallet:s,jwt:o,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let a=Zi(n.wallet_address),c={verified:a.length>0,numbers:a};a.length===0&&(w({wallet:s,jwt:o,phone:c,deposit:null,ready_for_ride:!1}),process.exit(0));let l=null,d=!1;try{l=(await Promise.allSettled(r.depositNetworks.map(async p=>{let[f,_,h]=await Promise.all([Ar(p,n.wallet_address),Sr(p,n.wallet_address),vt(p)]);return{network:p.name,isActive:f,deposited:_.toString(),minRequired:h.toString()}}))).filter(p=>p.status==="fulfilled").map(p=>p.value),d=l.some(p=>p.isActive)}catch{l=null,d=!1}w({wallet:s,jwt:o,phone:c,deposit:l,ready_for_ride:d})},Ll={install:jf,"setup-check":Gf};import zf from"fs";import wn from"fs";import Vf from"path";import Wf from"path";function Ls(e,t){return Wf.join(e,"events",`${t}.jsonl`)}function Os(e,t){let r=fc({rideId:t.rideId,kind:t.kind,status:t.status,content:t.content});if(so(t.rideId,r))return null;let n=oo(t.rideId)+1,s={v:gc,seq:n,eventId:r,rideId:t.rideId,kind:t.kind,terminal:t.terminal,ts:t.ts,payload:t.payload},i=Ls(e,t.rideId);return wn.mkdirSync(Vf.dirname(i),{recursive:!0}),wn.appendFileSync(i,JSON.stringify(s)+`
463
- `),io(t.rideId,r,n),s}function Ol(e,t,r){let n=Ls(e,t);if(!wn.existsSync(n))return[];let s=[];for(let i of wn.readFileSync(n,"utf8").split(`
464
- `))if(i)try{let o=JSON.parse(i);o.seq>r&&s.push(o)}catch{process.stderr.write(`[event-log] skipping unparseable line in ${t}.jsonl
465
- `)}return s}var Jf={WAITPAY:"waiting for payment",PAYCONFIRMED:"payment confirmed, matching a driver",PENDING:"searching for a driver",MATCHED:"a driver candidate was found",CONFIRMED:"the match was confirmed",ASSIGNED:"a driver is assigned and on the way",PICKUP:"the driver is on the way to the pickup point",PICKUP_ARRIVED:"the driver has arrived at the pickup point",INUSE:"the ride is in progress",FINISHED:"the ride completed successfully",NOT_MATCHED:"no driver was found",CANCELED:"the ride was cancelled",ACCIDENT_CANCELED:"the ride was cancelled due to an accident",USER_CANCELED:"cancelled by the rider",USER_CANCELED_BEFORE_CALL:"cancelled by the rider before matching",USER_CANCELED_NO_FREE:"cancelled by the rider (cancellation fee charged)",DRIVER_CANCELED:"cancelled by the driver",DRIVER_CANCELED_RECALLABLE:"cancelled by the driver (can re-request)",COMPANY_CANCELED:"cancelled by the operator",COMPANY_CANCELED_RECALLABLE:"cancelled by the operator (can re-request)",EXPIRED:"the request expired (no driver found)",EXPIRED_RECALLABLE:"the request expired (can re-request)",EXPIRED_BEFORE_PAY:"the payment window expired",ERROR_PAYMENT:"a payment error occurred",ERROR:"an unexpected error occurred"};function Ml(e,t){let r=t?.trim();return r&&r.length>0?r:Jf[e]??e}var Kf={KRW:"\u20A9",USD:"$",SGD:"S$",VND:"\u20AB"};function En(e,t){let r=e.toLocaleString("en-US"),n=Kf[t];return n?`${n}${r}`:`${r} ${t}`}function Yf(e){if(!e)return"";let t=[];e.carPlate&&t.push(`plate ${e.carPlate}`);let r=[e.carColor,e.carModel].filter(Boolean).join(" ").trim();return r&&t.push(r),e.name&&t.push(`driver ${e.name}`),t.length?`, ${t.join(", ")}`:""}function Xf(e){let t=typeof e=="string"?e.toUpperCase():"";return t==="NY"?"Throo":t===""?"TADA/Throo":"TADA"}function Ul(e){let t=Xf(e.payload.region);if(e.kind==="driver_chat"){let a=e.payload.content??"";return`${t} ride: driver sent "${a}". Tell the user briefly; their next short reply may be for the driver. No unrelated questions.`}let r=e.payload.statusMessage,n=String(e.payload.status??""),s=Ml(n,r);if(e.terminal){let a=e.payload.tip,c=`${t} ride ${e.rideId} ${s}. Tell the user the final outcome briefly.`;if(n==="FINISHED"&&(c+=" Ask whether they would like to see their receipt. Fetch it only if they explicitly ask."),a){let l=a.maxAmount?`from ${En(a.minAmount,a.currency)} up to ${En(a.maxAmount,a.currency)}`:`from ${En(a.minAmount,a.currency)}`;c+=` Tips ${l} are welcome. You may offer the tip together with that receipt question.`}return c}let i=e.payload.etaMin,o=Yf(e.payload.driver);return`${t} ride ${e.rideId} is ${s}${o}${i?`, pickup ~${i}min`:""}. Tell the user briefly. No unrelated questions.`}function Qf(e){try{return parseInt(zf.readFileSync(e,"utf8").trim(),10)||0}catch{return 0}}var Zf=e=>new Promise(t=>setTimeout(t,e));async function e_(e){let t=e.write??(n=>process.stdout.write(n+`
466
- `)),r=e.pollMs??2e3;for(;;){let n=Qf(e.cursorFile),s=Ol(e.root,e.rideId,n);for(let i of s){let o=e.prompt?{...i,prompt:Ul(i)}:i;if(t(JSON.stringify(o)),i.terminal)return 0}if(!e.follow)return 0;await Zf(r)}}var t_=async e=>{let t=o=>{let a=e.indexOf(o);return a>=0?e[a+1]:void 0},r=t("--ride"),n=t("--cursor-file");(!r||!n)&&(console.error(JSON.stringify({error:"USAGE",message:"amb events --ride <id> --cursor-file <f> [--follow] [--prompt]"})),process.exit(1));let s=R();b(s.dataDir),await xe(r);let i=await e_({root:F(),rideId:r,cursorFile:n,follow:e.includes("--follow"),prompt:e.includes("--prompt")});process.exit(i)},Bl={events:t_};import Bs from"fs";import Fs from"path";import{spawn as o_}from"child_process";var Fl=[2e3,5e3,15e3,3e4];function $l(e){if(e.exitCode===0)return{action:"stop",code:0};if(e.exitCode===1)return{action:"stop",code:1};let t=Math.min(e.restartCount,Fl.length-1);return{action:"restart",delayMs:Fl[t]}}import r_ from"net";import Ms from"fs";import n_ from"path";function Hl(e){let t=e.trace??(()=>{});try{Ms.mkdirSync(n_.dirname(e.sockPath),{recursive:!0})}catch{}try{Ms.unlinkSync(e.sockPath)}catch{}let r=r_.createServer(n=>{let s="";n.on("data",i=>{s+=i.toString();let o=s.indexOf(`
467
- `);if(o<0)return;let a=s.slice(0,o);s="",(async()=>{let c;try{let l=JSON.parse(a);typeof l?.content!="string"?c={ok:!1,reason:"bad_request"}:(t("chat_control_req",{len:l.content.length}),c=await e.send(l.content))}catch(l){c={ok:!1,reason:`bad_request: ${l.message}`}}try{n.write(JSON.stringify(c)+`
468
- `)}catch{}n.end()})()}),n.on("error",()=>{})});return r.on("error",n=>t("chat_control_server_error",{error:String(n)})),r.listen(e.sockPath,()=>t("chat_control_listen",{sockPath:e.sockPath})),{close(){try{r.close()}catch{}try{Ms.unlinkSync(e.sockPath)}catch{}}}}var s_=5e3,ql=3e4,jl=3,Gl=Symbol("timed_out");function i_(e){let t,r=new Promise(n=>{t=setTimeout(()=>n(Gl),s_)});return Promise.race([e,r]).finally(()=>clearTimeout(t))}function Wl(e){let t=e.trace??(()=>{}),r=e.now??Date.now,n=null,s=null,i=null,o=0,a=null,c=(l,d)=>{l!==null&&l!==s||(o+=1,a=r(),s=null,i=null,t("share_fetch_failed",{attempt:o,reason:d}),o>=jl&&t("share_fetch_gave_up"))};return async l=>{if(e.mode!=="tada"||l.rideShareUrl||!l.driverInfo)return l;if(Ie(l.status))return n?{...l,rideShareUrl:n}:l;if(n)return{...l,rideShareUrl:n};if(s&&i!==null&&r()-i>=ql)return c(s,"abandoned"),t("share_fetch_abandoned",{status:l.status}),l;if(!s){if(o>=jl||a!==null&&r()-a<ql)return l;let m=e.backend.getShareLink(e.rideId).then(p=>p.url);m.then(p=>{n=p,s=null,i=null},()=>{}),s=m,i=r()}let d=s,u;try{u=await i_(d)}catch(m){return c(d,String(m.message??m)),l}return u===Gl?(t("share_fetch_slow",{status:l.status}),l):(n=u,s=null,i=null,{...l,rideShareUrl:n})}}async function a_(e){let t=e.trace??(()=>{}),r=await e.fetchStatus();if(t("poll_result",{status:r.status,hasDriverInfo:!!r.driverInfo,changed:r.status!==e.lastStatusRef.status,raw:r}),r.status===e.lastStatusRef.status)return{terminal:!1};e.lastStatusRef.status=r.status;let n=Ie(r.status),s={status:r.status};if(e.region&&(s.region=e.region),r.driverInfo&&(s.driver=r.driverInfo),r.driverInfo&&r.rideShareUrl&&(s.rideShareUrl=r.rideShareUrl),r.rideId&&(s.upstreamRideId=r.rideId),r.statusMessage&&r.statusMessage.trim()&&(s.statusMessage=r.statusMessage),n&&r.status==="FINISHED"&&e.tipLookup)try{let i=await e.tipLookup();i&&(s.tip=i)}catch{}return Os(e.root,{rideId:e.rideId,kind:"ride_status",status:r.status,terminal:n,ts:new Date().toISOString(),payload:s}),Ve(e.rideId,r.status),t("event_appended",{status:r.status,terminal:n}),{terminal:n}}function c_(e,t,r,n){let s;return e.on("ready",()=>{if(!s)try{s=Hl({sockPath:ln(r,t),send:i=>e.send(i),trace:n}),n("chat_control_attached",{rideId:t})}catch(i){n("chat_control_attach_failed",{error:String(i)})}}),{close(){try{s?.close()}catch{}}}}function l_(e){return Fs.join(F(),"run",`monitor-trace-${e}.log`)}function Jl(e){let t=l_(e);return(r,n)=>{try{Bs.mkdirSync(Fs.dirname(t),{recursive:!0}),Bs.appendFileSync(t,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:r,rideId:e,...n??{}})+`
469
- `)}catch{}}}var Us=5e3,Vl=e=>new Promise(t=>setTimeout(t,e));function d_(e,t){let r=(async()=>{try{let n=await e.getTipConfig(t);return n.enabled?{minAmount:n.minAmount,currency:n.currency,...n.maxAmount!==void 0?{maxAmount:n.maxAmount}:{}}:null}catch{return null}})();return async()=>{let n=new Promise(s=>setTimeout(()=>s(null),5e3));return await Promise.race([r,n])}}var u_=async e=>{let t=e[0];t||(console.error(JSON.stringify({error:"USAGE",message:"amb monitor <request_id>"})),process.exit(1));let r=Jl(t),n=R();b(n.dataDir);let s=V(t);if(!s){r("exit",{reason:"ride_not_found"}),console.error(JSON.stringify({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}`})),process.exit(1);return}let i;try{i=await te(n,s)}catch(E){r("backend_resolve_failed",{msg:E.message}),console.error(JSON.stringify({error:"BACKEND_UNAVAILABLE",message:E.message})),process.exit(1);return}let{backend:o,mode:a}=i;r("startup",{rideId:t,mode:a,gatewayServerUrl:n.gatewayServerUrl,dataDir:n.dataDir,pollIntervalMs:Us});let c=d_(o,s.region),l=Wl({backend:o,mode:a,rideId:t,trace:r}),d="mon-"+t;if(!fs(F(),d)){r("already_running",{lockName:d}),process.exit(0);return}r("lock_acquired",{lockName:d});let u=null,m,p={status:s.status??""},f=0,_=!1,h=E=>{if(!_){_=!0;try{u?.dispose()}catch{}m?.close(),on(F(),d),r("lock_released",{reason:E})}},I=(E,A)=>{throw h(A),r("exit",{code:E,reason:A}),process.exit(E),new Error("unreachable")};process.on("SIGTERM",()=>{r("signal",{signal:"SIGTERM"}),I(2,"SIGTERM")}),process.on("SIGINT",()=>{r("signal",{signal:"SIGINT"}),I(2,"SIGINT")}),process.on("uncaughtException",E=>{r("crash",{source:"uncaughtException",error:String(E),stack:E?.stack}),h("uncaughtException"),r("exit",{code:1,reason:"uncaughtException"}),process.exit(1)}),process.on("unhandledRejection",E=>{let A=E instanceof Error?E:new Error(String(E));r("crash",{source:"unhandledRejection",error:String(A),stack:A.stack}),h("unhandledRejection"),r("exit",{code:1,reason:"unhandledRejection"}),process.exit(1)});try{for(;;){f+=1,r("poll_begin",{iteration:f,lastStatus:p.status}),a==="wallet"&&(P(s.wallet_address)||(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED"})+`
470
- `),r("jwt_missing",{iteration:f}),I(1,"jwt_missing")));let E;try{E=await p_({backend:o,rideId:t,lastStatusRef:p,trace:r,tipLookup:c,region:s.region,shareEnricher:l})}catch(A){let N=A.message;N.includes("401")&&(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED",message:N})+`
471
- `),r("jwt_expired",{iteration:f,message:N}),I(1,"jwt_expired")),process.stderr.write(`poll_error: ${N}
472
- `),r("poll_error",{iteration:f,message:N}),await Vl(Us);continue}E.driverInfo&&!u&&(r("chat_client_start",{rideId:t}),u=o.subscribeChat(t),u.on("message",A=>{let N=A.data,C=N?.content??"",U=N?.senderType,re=U==="DRIVER"?"driver":U==="SYSTEM"?"system":"unknown";r("chat_msg_raw",{raw:N,senderType:U,sender:re}),Os(F(),{rideId:t,kind:"driver_chat",terminal:!1,ts:new Date().toISOString(),content:C,payload:{content:C,sender:re,region:s.region}})}),u.on("error",A=>{r("chat_error",{message:A.message})}),u.connect(),m=c_(u,t,F(),r)),Ie(E.status)&&(r("terminal",{status:E.status}),I(0,"terminal")),await Vl(Us)}}catch(E){if(_)throw E;let A=E;r("crash",{source:"poll_loop",error:String(A),stack:A?.stack}),h("crash"),r("exit",{code:1,reason:"crash"}),process.exit(1)}};async function p_(e){let t;if(await a_({root:F(),rideId:e.rideId,region:e.region,fetchStatus:async()=>{let r=await e.backend.getRideStatus(e.rideId),n=e.shareEnricher?await e.shareEnricher(r):r;return t=n,n},lastStatusRef:e.lastStatusRef,trace:e.trace,tipLookup:e.tipLookup??void 0}),!t)throw new Error("fetchStatus did not run");return t}function m_(){let e=process.argv[1]??"",t=e?Fs.resolve(e):"";if(!t||!Bs.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}function g_(e){let t=Jl(e);return(r,n)=>t(r,{role:"supervisor",...n??{}})}var f_=async e=>{let t=e[0];if(!t){console.error(JSON.stringify({error:"USAGE",message:"amb monitor-supervisor <request_id>"})),process.exit(1);return}let r=g_(t);r("sup_start",{rideId:t,pid:process.pid});let n="sup-"+t;if(!fs(F(),n)){r("sup_already_running",{lockName:n}),process.exit(0);return}r("sup_lock_acquired",{lockName:n});let s;try{s=m_(),r("sup_entry_resolved",{ambEntry:s})}catch(p){r("sup_entry_unresolved",{error:String(p)}),on(F(),n),r("sup_stop",{code:2,reason:"entry_unresolved"}),process.exit(2);return}let i,o=!1,a=!1,c=p=>{a||(a=!0,on(F(),n),r("sup_lock_released",{reason:p}))},l=()=>{if(i&&i.exitCode===null&&i.signalCode===null)try{i.kill("SIGTERM")}catch{}},d=async p=>{if(o)return;o=!0,r("sup_signal",{signal:p});let f=!!(i&&i.exitCode===null&&i.signalCode===null);l(),f&&await new Promise(_=>{let h=!1,I=()=>{h||(h=!0,_())};i.once("exit",I),setTimeout(I,25e3).unref()}),c(p),r("sup_stop",{code:2,reason:p}),process.exit(2)};process.on("SIGTERM",()=>{d("SIGTERM")}),process.on("SIGINT",()=>{d("SIGINT")});let u=(p,f)=>{if(o)return;o=!0;let _=f instanceof Error?f:new Error(String(f));r("sup_crash",{source:p,error:String(_),stack:_.stack}),l(),c("crash"),r("sup_stop",{code:1,reason:p}),process.exit(1)};process.on("uncaughtException",p=>u("uncaughtException",p)),process.on("unhandledRejection",p=>u("unhandledRejection",p));let m=0;await new Promise(()=>{let p=()=>{i=o_(process.execPath,[s,"monitor",t],{detached:!1,stdio:"ignore"}),r("sup_spawn",{childPid:i.pid,attempt:m}),i.on("error",f=>{o||(r("sup_child_error",{error:f.message}),c("child_spawn_error"),r("sup_stop",{code:2,reason:"child_spawn_error"}),process.exit(2))}),i.on("exit",(f,_)=>{if(o)return;r("sup_child_exit",{exitCode:f,signal:_,restartCount:m});let h=$l({exitCode:f,signal:_,restartCount:m});if(r("sup_decision",{...h}),h.action==="stop"){c("terminal"),r("sup_stop",{code:h.code}),process.exit(h.code);return}m++,r("sup_restart",{delayMs:h.delayMs,restartCount:m}),setTimeout(p,h.delayMs)})};p()})},Kl={monitor:u_,"monitor-supervisor":f_};function __(e){let t=P(e,"member")!==null,r=wr(e)!==null;return t||r?"active":"needs_login"}var y_="Your TADA/Throo session isn't active \u2014 run 'amb login' to sign in again.",h_=async e=>{let t=K(),r=bt();if(t.mode===null){w({mode:null,reason:"onboarding",identity:null,member_available:r,hint:"No credentials registered. Run 'amb install' to set up, then 'amb login' (TADA/Throo member) or 'amb wallet-setup' (crypto)."});return}if(t.mode==="tada"&&t.member){let i=__(t.member.id),o=i==="active",a={mode:"tada",reason:t.reason,identity:{kind:"tada",member_id:t.member.id,phone:t.member.phone,display_name:t.member.display_name,region:t.member.region},member_available:r,authenticated:o,auth_state:i,...o?{}:{hint:y_}};w(a);return}if(t.mode==="wallet"&&t.walletAddress){let i={mode:"wallet",reason:t.reason,identity:{kind:"wallet",wallet_address:t.walletAddress},member_available:r};w(i);return}let n=t.mode==="tada"?"Run 'amb login' first.":"Run 'amb wallet-setup' first.",s={mode:t.mode,reason:t.reason,identity:null,member_available:r,hint:`--account=${t.mode} was forced but no ${t.mode==="tada"?"TADA/Throo member":"wallet"} credentials are registered. ${n}`};w(s)},Yl={whoami:h_};import w_ from"os";import Xl from"path";import E_ from"fs";import zl from"qrcode";async function $s(e){return zl.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"L"})}async function Ql(e){let t=E_.mkdtempSync(Xl.join(w_.tmpdir(),"tada-login-")),r=Xl.join(t,"qr.png");return await zl.toFile(r,e,{type:"png",margin:4,width:320}),r}import b_ from"readline/promises";async function T_(){let e=b_.createInterface({input:process.stdin,output:process.stdout});try{return(await e.question("Enter the 4-digit code shown in the TADA/Throo app: ")).trim()}finally{e.close()}}async function S_(){if(!bt()){w({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let e=R();b(e.dataDir);let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret};Ue(ee(e.cliGatewayHosts,e.cliGatewayHost));try{let r=await Es(t),n=Date.parse(r.expiresAt),s=Number.isFinite(n)?Math.floor(n/1e3):Math.floor(Date.now()/1e3)+600;Vi(),Gi(r.sessionToken,s);let i={status:"auth_required",approval_url:r.approvalUrl,expires_at:r.expiresAt};try{let o=await $s(r.approvalUrl);process.stderr.write(`Scan this QR to approve the login in the TADA/Throo app:
473
- ${o}
474
- `),i.qr_image_path=await Ql(r.approvalUrl)}catch{}w(i)}catch{w({status:"error",message:"Failed to start login session."})}}var A_=async e=>{if(e.includes("--no-wait"))return S_();let r=R();if(!Oi(r)){console.log("Member login is not available in this build (missing RIDER_CLI_APP credentials).");return}b(r.dataDir);let n={clientId:r.riderCliApp.clientId,clientSecret:r.riderCliApp.clientSecret};Ue(ee(r.cliGatewayHosts,r.cliGatewayHost));let s=await Es(n),i="";try{i=`
475
- ${await $s(s.approvalUrl)}`}catch{}console.log(`Approve this login in the TADA/Throo app:${i} ${s.approvalUrl}
476
- Then enter the 4-digit code the app shows.`);let o=e.indexOf("--code"),a=o>=0?e[o+1]:void 0,c=!1;for(let l=1;l<=5;l++){let d=a??await T_();try{let u=await Rs(n,s.sessionToken,d);console.log(`Logged in as TADA/Throo member ${u.memberId}.`);return}catch(u){if(u instanceof Y&&u.code==="invalid_user_code"){if(c=!0,console.log(`Code did not match (${l}/5)${l===4?" \u2014 last attempt!":""}.`),a!==void 0)return;continue}if(u instanceof Y&&u.code==="invalid_grant"){console.log(c?"Too many incorrect codes \u2014 the login session was destroyed. Please run `amb login` again.":"This login session is no longer valid (it may have expired, been denied, or already been used). Please run `amb login` again.");return}console.log("Login failed. Please run `amb login` again.");return}}console.log("Too many incorrect codes \u2014 the login session was destroyed. Please run `amb login` again.")},I_=async()=>{let e=R();b(e.dataDir),console.log(Dc()?"Logged out of TADA/Throo member account.":"No active TADA/Throo member session.")},x_=async e=>{let t=e.indexOf("--code"),r=t>=0?e[t+1]:void 0;if(r||(console.error("error: Usage: amb login-verify --code <4-digit-code>"),process.exit(1)),!bt()){w({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let n=R();b(n.dataDir);let s={clientId:n.riderCliApp.clientId,clientSecret:n.riderCliApp.clientSecret};Ue(ee(n.cliGatewayHosts,n.cliGatewayHost));let i=Wi(),o=Math.floor(Date.now()/1e3);if(!i||i.expires_at<=o){i&&hr(i.session_token),w({status:"session_expired",message:"No active login session. Run `amb login --no-wait` to start over."});return}try{let a=await Rs(s,i.session_token,r);hr(i.session_token),w({status:"logged_in",member_id:a.memberId})}catch(a){if(a instanceof Y&&a.code==="invalid_user_code"){w({status:"invalid_code",message:"The 4-digit code did not match. Re-read the code in the TADA/Throo app and run `amb login-verify --code <code>` again."});return}if(a instanceof Y&&(a.code==="invalid_grant"||a.code==="agent_session_not_found"||a.code==="agent_session_already_decided"||a.code==="agent_session_expired")){hr(i.session_token),w({status:"session_expired",message:"The login session is no longer valid (expired, denied, or too many wrong codes). Run `amb login --no-wait` to start over."});return}w({status:"error",message:"Login failed. Run `amb login --no-wait` to start over."})}},Zl={login:A_,logout:I_,"login-verify":x_};import yt from"fs";import ht from"path";var v_="proprietary (see LICENSE)";function Rn(){let{cliVersion:e,gitSha:t}=z().artifact;return{version:e,git_sha:t,license:v_}}function ed(e){return`version: ${e.version}
572
+ `);let k=await Du(_,I,{authUrl:N});$x(k,{purpose:s})}catch(x){b({error:"MAP_SESSION_CREATE_FAILED",message:x.message}),process.exit(1)}},D0=async e=>{let{positional:t,purpose:r}=Hx(e),n=t[0];n||(console.error("error: Usage: map-session-verify <session_id> [--purpose origin|destination]"),process.exit(1));let s=D(),i=await Du(s,n,{});$x(i,{purpose:r})},Wx={"map-session-create":e=>Gx(e.includes("--no-wait")?e:[...e,"--no-wait"]),"map-session":Gx,"map-session-verify":D0};p();var O0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb phone-verify-start <wallet_address> <phone>"),console.error("hint: phone: E.164 format (e.g. +12125550100)"),process.exit(1));let n=D();O(n.dataDir),J(t),he(t);let s=ie(t);le(n.appServerUrl),_e(n.gatewayServerUrl);try{let i=await $b(s,r);i.status==="ALREADY_VERIFIED"&&Va(t,r),w(i)}catch(i){b({error:i.message}),process.exit(1)}},C0=async e=>{let[t,r,n]=e;(!t||!r||!n)&&(console.error("error: Usage: amb phone-verify-confirm <wallet_address> <phone> <code>"),console.error("hint: phone: E.164 format (e.g. +12125550100). code: 6-digit OTP from SMS"),process.exit(1));let s=D();O(s.dataDir),J(t),he(t);let i=ie(t);le(s.appServerUrl),_e(s.gatewayServerUrl);try{let a=await Wb(i,r,n);a.status==="ok"&&Va(t,r),w({status:a.status})}catch(a){b({error:a.message}),process.exit(1)}},N0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb phone-verify-check <wallet_address> <phone>"),console.error("hint: phone: E.164 format (e.g. +12125550100)"),process.exit(1));let n=D();O(n.dataDir),J(t),he(t);let s=ie(t);le(n.appServerUrl),_e(n.gatewayServerUrl);try{let i=await Hb(s,r);i.verified&&Va(t,r),w(i)}catch(i){b({error:i.message}),process.exit(1)}},Jx={"phone-verify-start":O0,"phone-verify-confirm":C0,"phone-verify-check":N0};p();import Cu from"fs";import L0 from"path";var k0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb siwe-request-message <wallet_address> <chain_id>"),console.error("hint: chain_id: 84532 (BASE_SEPOLIA), 11155111 (ETH_SEPOLIA)"),process.exit(1));let n=D();O(n.dataDir),J(t),le(n.appServerUrl);try{let{message:s,expiresAt:i}=await wa(t,parseInt(r,10));Cu.mkdirSync(n.dataDir,{recursive:!0});let a=`siwe-${t}-exp${i}.json`,o=L0.join(n.dataDir,a);Cu.writeFileSync(o,JSON.stringify({message:s,walletAddress:t,expiresAt:i},null,2),{mode:384}),w({message:s,siwe_file:o,expires_at:new Date(i*1e3).toISOString()})}catch(s){b({error:s.message}),process.exit(1)}},M0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb siwe-submit <siwe_file> <signature>"),console.error("hint: siwe_file is the file path returned by `amb siwe-request-message`"),console.error(" signature is the wallet_signature from `amb wallet-sign`"),process.exit(1));let n=D();O(n.dataDir),le(n.appServerUrl);try{let{message:s,expiresAt:i,walletAddress:a}=JSON.parse(Cu.readFileSync(t,"utf8"));Date.now()/1e3>i&&(b({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1));let o=await Sa(s,r);a&&await Gt(n.dataDir,"activation_authenticated",{id:vt(a)}),w({access_token:o.accessToken,expires_in:o.expiresIn})}catch(s){b({error:s.message}),process.exit(1)}},Kx={"siwe-request-message":k0,"siwe-submit":M0};p();import*as Nu from"fs";import*as zx from"path";import{io as F0}from"socket.io-client";p();import U0 from"net";function Yx(e,t,r={}){let n=r.connectTimeoutMs??1e3,s=r.responseTimeoutMs??co;return new Promise(i=>{let a=!1,o=m=>{if(!a){a=!0;try{c.destroy()}catch{}clearTimeout(u),clearTimeout(l),i(m)}},c=U0.connect(e),u=setTimeout(()=>o({ok:!1,reason:"monitor_unreachable"}),n),l=setTimeout(()=>{},0);clearTimeout(l);let d="";c.on("connect",()=>{clearTimeout(u),l=setTimeout(()=>o({ok:!1,reason:"response_timeout"}),s);try{c.write(JSON.stringify({content:t})+`
573
+ `)}catch(m){o({ok:!1,reason:`write_failed: ${m.message}`})}}),c.on("data",m=>{d+=m.toString();let f=d.indexOf(`
574
+ `);if(!(f<0))try{let g=JSON.parse(d.slice(0,f));o(g&&typeof g=="object"&&"ok"in g?g:{ok:!1,reason:"bad_response"})}catch{o({ok:!1,reason:"bad_response"})}}),c.on("error",()=>o({ok:!1,reason:"monitor_unreachable"})),c.on("end",()=>o({ok:!1,reason:"no_response"}))})}var j0={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function q0(e,t,r,n){let i=new URL(e.gatewayServerUrl).origin,a=F0(`${i}/chat`,{path:"/tada-ton/chat-socket",transports:["websocket"],auth:{token:r}});return new Promise(o=>{let c=!1,u,l;function d(f){c||(c=!0,clearTimeout(u),clearTimeout(l),a.disconnect(),o(f))}function m(f){d({ok:!1,reason:f})}a.on("connect_error",f=>{m(`socket connection failed: ${f.message}`)}),new Promise((f,g)=>{u=setTimeout(()=>g(new Error("join room timeout")),1e4),a.emit("JOIN_ROOM",{rideRequestId:t}),a.once("MESSAGE_SENT",_=>{if(clearTimeout(u),_.event!=="joined"){g(new Error(`unexpected join event: ${_.event}`));return}let E=_.roomId;l=setTimeout(()=>g(new Error("send message timeout")),1e4),a.emit("SEND_MESSAGE",{roomId:E,content:n,type:"TEXT"}),a.once("MESSAGE_SENT",()=>{clearTimeout(l),f()})})}).then(()=>{d({ok:!0})},f=>{m(f.message)})})}var B0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb chat-send-message <request_id> <content>"),process.exit(1));let n=D();O(n.dataDir);let s=Ae(t);if(s||(b({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let u;try{({backend:u}=await ft(n,s))}catch(l){b({error:"AUTH_FAILED",message:l.message,request_id:t}),process.exit(1)}try{let l=await u.sendChat(t,{message:r});w(l)}catch(l){let d=l instanceof Be?l.code:"CHAT_SEND_FAILED";b({error:d,message:l.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;J(i),he(i);let a=ie(i);a||(b({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1)),nr(t);let o=await Yx(lo(ge(),t),r);if(o.ok){w({success:!0,via:"monitor"});return}let c=await q0(n,t,a,r);if(c.ok){w({success:!0,via:"fallback"});return}b({error:"CHAT_SEND_FAILED",primary:o.reason,fallback:c.reason}),process.exit(1)},V0=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb chat-send-image <request_id> <image_path>"),process.exit(1));let n=zx.extname(r).toLowerCase(),s=j0[n];s||(b({error:"UNSUPPORTED_FORMAT",message:`Unsupported image format: "${n}". Supported: jpeg, jpg, png, gif, webp`}),process.exit(1));let i=D();O(i.dataDir);let a=Ae(t);if(a||(b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}`}),process.exit(1)),!a.wallet_address){let l;try{l=Nu.readFileSync(r)}catch(m){b({error:"FILE_READ_FAILED",message:m.message}),process.exit(1)}let d;try{({backend:d}=await ft(i,a))}catch(m){b({error:"AUTH_FAILED",message:m.message,request_id:t}),process.exit(1)}try{let m=await d.sendChat(t,{image:{buffer:l,mimetype:s}});w(m)}catch(m){let f=m instanceof Be?m.code:"CHAT_SEND_FAILED";b({error:f,message:m.message,request_id:t}),process.exit(1)}return}let o=a.wallet_address;J(o),he(o),_e(i.gatewayServerUrl);let c=ie(o),u;try{u=Nu.readFileSync(r)}catch(l){b({error:"FILE_READ_FAILED",message:l.message}),process.exit(1)}try{let l=await Wa(c,t,u,s);w(l)}catch(l){b({error:"CHAT_SEND_IMAGE_FAILED",message:l.message}),process.exit(1)}},G0=async e=>{let[t,r]=e;t||(console.error("error: Usage: amb chat-get-messages <request_id> [cursor]"),process.exit(1));let n=D();O(n.dataDir);let s=Ae(t);if(s||(b({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let o;try{({backend:o}=await ft(n,s))}catch(c){b({error:"AUTH_FAILED",message:c.message,request_id:t}),process.exit(1)}try{w(await o.getMessages(t,r?Number(r):void 0))}catch(c){let u=c instanceof Be?c.code:"CHAT_GET_FAILED";b({error:u,message:c.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;J(i),he(i),_e(n.gatewayServerUrl);let a=ie(i);a||(b({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let o=await $a(t,a,r);w(o)}catch(o){b({error:"CHAT_GET_FAILED",message:o.message}),process.exit(1)}},Xx={"chat-send-message":B0,"chat-send-image":V0,"chat-get-messages":G0};p();import*as H from"fs";import*as pe from"path";import*as wo from"os";import*as AR from"crypto";import{spawnSync as fU}from"child_process";import gU from"better-sqlite3";p();import Bu from"crypto";import F from"fs";import j from"path";p();function Qx(e,t){let r=t(e.legacyRoot),n=t(e.ambientRoot),s=t(e.backupRoot);return t(e.stagingRoot)?"conflict":!r&&!n&&!s?"fresh":r&&!n&&!s?"legacy_candidate":!r&&n&&!s?"ambient_fresh":!r&&n&&s?"already_migrated":r&&n&&!s?"resume_before_backup":"conflict"}var H0={fresh:["initialize_ambient"],legacy_candidate:["migrate_legacy"],ambient_fresh:["use_ambient"],already_migrated:["validate_migrated"],resume_before_backup:["resume_backup"]};function Zx(e,t){if(t==="conflict")throw new Error("MIGRATION_CONFLICT: filesystem state is not safe to migrate");return{state:t,paths:{...e},actions:[...H0[t]]}}p();var tR={TADA_AGENT_PASSPHRASE:"AMB_RIDE_PASSPHRASE",TADA_AGENT_STATE_DIR:"AMB_RIDE_STATE_DIR",TADA_AGENT_LOG_LEVEL:"AMB_RIDE_LOG_LEVEL",TADA_OPENCLAW_CLI:"AMB_RIDE_OPENCLAW_CLI"},eR=new Set(Object.values(tR)),$0=/^(?:TADA_AGENT_|TADA_OPENCLAW_)/,W0=/^TADA_AGENT_DEPOSIT_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,J0=/^TADA_AGENT_BRIDGE_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,K0=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function br(e,t){throw new Error(`${e}: ${t}`)}function Hs(e){if(typeof e.env!="string")return{...e.env};let t={};for(let[r,n]of e.env.split(/\r?\n/).entries()){let s=n.trim();if(s===""||s.startsWith("#"))continue;let i=s.indexOf("=");i<=0&&br("INVALID_ENV_LINE",`source=${e.name} line=${r+1}`);let a=s.slice(0,i).trim(),o=s.slice(i+1).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)||br("INVALID_ENV_KEY",`source=${e.name} line=${r+1}`),Object.hasOwn(t,a)&&br("DUPLICATE_ENV_KEY",`source=${e.name} key=${a}`),t[a]=o}return t}function Y0(e){let t=Array.isArray(e)?e:[{name:"input",env:e}],r=[],n=new Map;for(let s of t){let i=Hs(s);for(let[a,o]of Object.entries(i)){if(o===void 0)continue;let c=n.get(a);if(c&&c.value!==o&&br("ENV_SOURCE_CONFLICT",`key=${a} sources=${c.source},${s.name}`),!c){let u={key:a,value:o,source:s.name};n.set(a,u),r.push(u)}}}return r}function z0(e,t){let r=W0.exec(e);if(r)return r[1];let n=J0.exec(e);if(n)return n[1];if(e==="TADA_AGENT_PAYMENT_RPC_URL")return t}function zr(e,t){if(!K0.test(t))throw new Error(`INVALID_PAYMENT_NETWORK: network=${t}`);let r=Y0(e),n={},s=new Map,i=new Map,a=[],o=[],c=(u,l)=>{let d=s.get(l);d&&d.value!==u.value&&br("ENV_TARGET_CONFLICT",`target=${l} keys=${d.key},${u.key} sources=${d.source},${u.source}`),d||(s.set(l,u),n[l]=u.value),o.push({from:u.key,to:l})};for(let u of r){let l=tR[u.key];if(l){c(u,l);continue}let d=z0(u.key,t);if(d){let m=i.get(d)??[];m.push(u),i.set(d,m);continue}if(eR.has(u.key)||/^AMB_RIDE_RPC_URL_/.test(u.key)){!eR.has(u.key)&&!/^AMB_RIDE_RPC_URL_[A-Z0-9]+(?:_[A-Z0-9]+)*$/.test(u.key)&&br("UNKNOWN_AMBIENT_ENV_KEY",`key=${u.key} source=${u.source}`),c(u,u.key);continue}u.key.startsWith("AMB_RIDE_")&&br("UNKNOWN_AMBIENT_ENV_KEY",`key=${u.key} source=${u.source}`),$0.test(u.key)&&a.push(u.key)}for(let[u,l]of i){new Set(l.map(f=>f.value)).size>1&&br("RPC_CONFIG_CONFLICT",`network=${u} keys=${l.map(f=>f.key).join(",")} sources=${l.map(f=>f.source).join(",")}`);let m=`AMB_RIDE_RPC_URL_${u}`;for(let f of l)c(f,m)}return{env:n,droppedLegacyConfig:[...new Set(a)].sort(),mappedLegacyConfig:o}}p();import Xr from"fs";import sr from"path";import X0 from"better-sqlite3";var iR=["identity","wallets","privy_wallet_meta","pending_sessions","jwt_cache","ride_requests","tada_members","places","bridge_jobs","member_login_sessions"];function Me(e,t){throw new Error(t?`${e}: ${t}`:e)}function rR(e){try{return new X0(e,{readonly:!0,fileMustExist:!0})}catch(t){return Me("SQLITE_OPEN_FAILED",String(t))}}function Lu(e,t){return!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(t)}function nR(e){return Object.fromEntries(iR.map(t=>{if(!Lu(e,t))return[t,"absent"];let r=e.prepare(`SELECT COUNT(*) AS count FROM ${t}`).get();return[t,r.count]}))}function Q0(e){let t=[];if(Lu(e,"privy_wallet_meta")){let r=e.prepare("SELECT wallet_address AS id, k_i_pub AS publicKey, k_i_key_path AS storedPath FROM privy_wallet_meta").all();t.push(...r.map(n=>({table:"privy_wallet_meta",...n})))}if(Lu(e,"pending_sessions")){let r=e.prepare("SELECT session_token AS id, k_i_pub AS publicKey, k_i_key_path AS storedPath FROM pending_sessions").all();t.push(...r.map(n=>({table:"pending_sessions",...n})))}return t}function sR(e){let t;try{t=e.pragma("integrity_check")}catch(r){Me("SQLITE_INTEGRITY_FAILED",String(r))}(t.length!==1||t[0]?.integrity_check!=="ok")&&Me("SQLITE_INTEGRITY_FAILED",t.map(r=>r.integrity_check).join("; "))}function Z0(e,t){for(let r of iR)e[r]!==t[r]&&Me("ROW_COUNT_MISMATCH",`${r}: source=${e[r]} staged=${t[r]}`)}function ku(e){let t=sr.resolve(e.dataDir),r=sr.resolve(e.keysDir),n=sr.resolve(e.dbPath);for(let[o,c]of[["DATA_DIR",t],["KEYS_DIR",r]]){let u;try{u=Xr.lstatSync(c)}catch{Me(`MISSING_${o}`)}(!u.isDirectory()||u.isSymbolicLink())&&Me(`INVALID_${o}`)}sr.dirname(n)!==t&&Me("DB_OUTSIDE_DATA_DIR"),Xr.existsSync(n)||Me("MISSING_DATABASE");let s=Xr.lstatSync(n);(!s.isFile()||s.isSymbolicLink())&&Me("INVALID_DATABASE_FILE");let i;if(e.sourceDbPath){let o=sr.resolve(e.sourceDbPath);o===n&&Me("SOURCE_EQUALS_STAGED");let c=rR(o);try{sR(c),i=nR(c)}finally{c.close()}}try{Nd(n)}catch(o){let c=String(o);c.includes("KEY_PATH_COLLISION")&&Me("KEY_PATH_COLLISION",c),/malformed|not a database|database disk image/i.test(c)&&Me("SQLITE_INTEGRITY_FAILED",c),Me("KEY_PATH_NORMALIZATION_FAILED",c)}let a=rR(n);try{sR(a);let o=nR(a);i&&Z0(i,o);let c=Q0(a),u=0;for(let l of c){let d=tt(r,l.storedPath),m=sr.relative(r,d);(m.startsWith("..")||sr.isAbsolute(m))&&Me("KEY_OUTSIDE_KEYS_DIR",`${l.table}:${l.id}`);let f;try{f=Xr.lstatSync(d)}catch{Me("MISSING_KEY_FILE",`${l.table}:${l.id}`)}(!f.isFile()||f.isSymbolicLink())&&Me("INVALID_KEY_FILE",`${l.table}:${l.id}`);let g=Xr.realpathSync(d),_=Xr.realpathSync(r),E=sr.relative(_,g);(E.startsWith("..")||sr.isAbsolute(E))&&Me("KEY_OUTSIDE_KEYS_DIR",`${l.table}:${l.id}`);let T;try{T=qt(Xr.readFileSync(d),Buffer.from(e.passphrase,"utf8")),hi(T.toString("utf8"))!==l.publicKey&&Me("KEY_PUBLIC_MISMATCH",`${l.table}:${l.id}`)}catch(x){if(String(x).includes("KEY_PUBLIC_MISMATCH"))throw x;Me("KEY_DECRYPT_FAILED",`${l.table}:${l.id}`)}finally{T&&gt(T)}u++}return{sqliteIntegrity:"ok",criticalRowCounts:o,referencedKeys:c.length,openedKeys:u}}finally{a.close()}}var xo=".amb-migration-provenance.json",Fu=".amb-migration-attempt",oR=".amb-migration-report.json",Mu=".env.legacy",Bn=384;function vo(e){return`${e.stagingRoot}.owner`}function me(e,t){return new Error(t?`${e}: ${t}`:e)}function eU(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[r,j.resolve(n)]));if(new Set(Object.values(t)).size!==Object.keys(t).length)throw me("MIGRATION_CONFLICT","migration paths must be distinct");if(j.dirname(t.stagingRoot)!==j.dirname(t.ambientRoot))throw me("MIGRATION_CONFLICT","staging must be an Ambient sibling");if(j.dirname(t.backupRoot)!==j.dirname(t.legacyRoot))throw me("MIGRATION_CONFLICT","backup must be a legacy sibling");for(let r of[t.legacyRoot,t.ambientRoot,t.stagingRoot,t.backupRoot]){let n=j.relative(r,t.lockPath);if(n===""||!n.startsWith("..")&&!j.isAbsolute(n))throw me("MIGRATION_CONFLICT","lock must be outside state trees")}}function Uu(e,t,r){let n=e.lstat(t);if(!n.isDirectory()||n.isSymbolicLink())throw me(r)}function tU(e,t,r){let n=e.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw me(r)}function cR(e){return`${JSON.stringify(e,null,2)}
575
+ `}function lR(e,t){let r=Bu.createHash("sha256"),n=0;for(let s of[t,`${t}-wal`,`${t}-journal`]){if(!e.exists(s))continue;let i=e.readFile(s);r.update(j.basename(s)),r.update(i),n+=i.length}return{size:n,sha256:r.digest("hex")}}function Ao(e){return j.join(e.oldDataDir,"tada-ride-agent.db")}function Wt(e){return j.join(e.stagingRoot,"state","data")}function bo(e){return j.join(e.stagingRoot,"state","keys")}function ju(e){return j.join(e.ambientRoot,"state","data")}function rU(e){return j.join(e.ambientRoot,"state","keys")}function Vu(e,t,r){try{return JSON.parse(e.readFile(t).toString("utf8"))}catch{throw me(r)}}function Vn(e,t,r){e.fsyncDirectory(j.dirname(t)),e.rename(t,r),e.fsyncDirectory(j.dirname(r))}function uR(e,t,r,n){if(e.exists(t))return;let s=`${t}.${n}.tmp`;e.writeFileExclusive(s,cR(r),Bn),e.fsyncFile(s),Vn(e,s,t),e.fsyncFile(t)}function nU(e,t){let r=j.join(Wt(e.paths),".env"),n=e.transformEnv??zr,s=t.exists(r)?Hs({name:"legacy-state",env:t.readFile(r).toString("utf8")}):{},i=n(s,e.paymentNetwork);if(t.exists(r)){let o=j.join(Wt(e.paths),Mu);if(t.exists(o))throw me("MIGRATION_COLLISION");Vn(t,r,o)}let a=Object.entries(i.env).sort(([o],[c])=>o.localeCompare(c)).map(([o,c])=>`${o}=${c}`);return t.writeFileExclusive(r,`${a.join(`
576
+ `)}${a.length?`
577
+ `:""}`,Bn),t.fsyncFile(r),t.exists(j.join(Wt(e.paths),Mu))&&t.unlink(j.join(Wt(e.paths),Mu)),t.fsyncDirectory(j.dirname(r)),i}function sU(e,t,r,n,s){let i=lR(e,t);return{schemaVersion:1,attemptId:s,sourcePath:e.realpath(t),sourceDbSize:i.size,sourceDbSha256:i.sha256,criticalRowCounts:r.criticalRowCounts,mappedLegacyConfig:n.mappedLegacyConfig,droppedLegacyConfig:n.droppedLegacyConfig}}function dR(e,t,r){let n=j.join(t.ambientRoot,xo);if(!e.exists(n))throw me("MIGRATION_INTERRUPTED","missing provenance");let s=Vu(e,n,"MIGRATION_INTERRUPTED"),i=lR(e,r);if(s.schemaVersion!==1||s.sourcePath!==e.realpath(r)||s.sourceDbSize!==i.size||s.sourceDbSha256!==i.sha256)throw me("MIGRATION_INTERRUPTED","source provenance mismatch");return s}function pR(e,t,r){let n=j.join(t.ambientRoot,Fu);if(e.exists(n)){if(e.readFile(n).toString("utf8").trim()!==r)throw me("MIGRATION_INTERRUPTED","attempt provenance mismatch");e.unlink(n),e.fsyncDirectory(t.ambientRoot)}}function iU(e,t){if(!t.exists(e.managedLegacyLink)||!t.lstat(e.managedLegacyLink).isSymbolicLink())return;let n,s;try{n=t.realpath(e.managedLegacyLink),s=t.realpath(e.expectedLegacyLinkTarget)}catch{return}n===s&&(t.unlink(e.managedLegacyLink),t.fsyncDirectory(j.dirname(e.managedLegacyLink)))}function Ro(e,t){let r=j.join(t,"state","data"),n=j.join(r,"ambient-ride.db"),s=j.join(r,".env");for(let i of[n,`${n}-wal`,`${n}-shm`,s])e.exists(i)&&e.fsyncFile(i);for(let i of[r,j.join(t,"state","keys"),j.join(t,"state"),t])e.fsyncDirectory(i)}function qu(e,t){let r=e.validate??ku;try{return r({dataDir:j.join(t,"state","data"),keysDir:j.join(t,"state","keys"),dbPath:j.join(t,"state","data","ambient-ride.db"),sourceDbPath:Ao(e),passphrase:mR(e,t)})}catch{throw me("MIGRATION_VALIDATION_FAILED")}}function mR(e,t){let r=j.join(t,"state","data",".env"),s=Hs({name:"ambient-state",env:e.fs?.readFile(r).toString("utf8")??F.readFileSync(r,"utf8")}).AMB_RIDE_PASSPHRASE;if(!s)throw me("MIGRATION_VALIDATION_FAILED","missing passphrase");return s}function fR(e,t,r,n){return{schemaVersion:1,status:e,sourcePath:t.paths.legacyRoot,sourceDataPath:t.oldDataDir,sourceKeysPath:t.oldKeysDir,backupPath:t.paths.backupRoot,mappedLegacyConfig:r.mappedLegacyConfig,droppedLegacyConfig:r.droppedLegacyConfig,validation:n}}function aU(e,t){let r=Hs({name:"ambient-state",env:e.readFile(j.join(ju(t),".env")).toString("utf8")});return{env:Object.fromEntries(Object.entries(r).filter(n=>n[1]!==void 0)),droppedLegacyConfig:[],mappedLegacyConfig:[]}}function gR(e,t){let r=/^(?:TADA_AGENT_|TADA_OPENCLAW_)[A-Z0-9_]+$/,n=/^AMB_RIDE_[A-Z0-9_]+$/;return e.every(s=>typeof s=="object"&&s!==null&&typeof s.from=="string"&&typeof s.to=="string"&&(r.test(s.from)||n.test(s.from))&&n.test(s.to))&&t.every(s=>typeof s=="string"&&r.test(s))}function hR(e,t){let r=Vu(e,j.join(t.ambientRoot,xo),"MIGRATION_INTERRUPTED");if(!Array.isArray(r.mappedLegacyConfig)||!Array.isArray(r.droppedLegacyConfig)||!gR(r.mappedLegacyConfig,r.droppedLegacyConfig))throw me("MIGRATION_INTERRUPTED","invalid provenance");return{...aU(e,t),mappedLegacyConfig:r.mappedLegacyConfig,droppedLegacyConfig:r.droppedLegacyConfig}}function yR(e,t,r,n,s,i){if(e.installManagedCli(),e.smoke(e.paths.ambientRoot),dR(t,e.paths,Ao(e)),t.exists(e.paths.backupRoot))throw me("MIGRATION_BACKUP_EXISTS");iU(e,t),Vn(t,e.paths.legacyRoot,e.paths.backupRoot);let a=fR(r,e,s,i);return uR(t,j.join(e.paths.ambientRoot,oR),a,n),a}function oU(e,t,r){Uu(t,e.paths.legacyRoot,"INVALID_LEGACY_ROOT"),Uu(t,e.oldDataDir,"INVALID_LEGACY_DATA_DIR"),Uu(t,e.oldKeysDir,"INVALID_LEGACY_KEYS_DIR");let n=Ao(e);tU(t,n,"INVALID_LEGACY_DATABASE");let s=e.quiesceLegacy(),i=!1;try{t.writeFileExclusive(vo(e.paths),`${r}
578
+ `,Bn),t.fsyncFile(vo(e.paths)),t.fsyncDirectory(j.dirname(e.paths.stagingRoot)),i=!0,t.copyTreeExclusive(e.paths.legacyRoot,e.paths.stagingRoot,["cli"]),t.writeFileExclusive(j.join(e.paths.stagingRoot,Fu),`${r}
579
+ `,Bn),t.fsyncFile(j.join(e.paths.stagingRoot,Fu));let a=j.join(e.paths.stagingRoot,j.relative(e.paths.legacyRoot,e.oldDataDir)),o=j.join(e.paths.stagingRoot,j.relative(e.paths.legacyRoot,e.oldKeysDir));if(j.resolve(a)!==j.resolve(Wt(e.paths))){let g=j.join(e.paths.stagingRoot,"state");t.exists(g)||t.mkdirExclusive(g,448),t.exists(Wt(e.paths))&&t.removeOwnedPath(Wt(e.paths)),t.copyTreeExclusive(e.oldDataDir,Wt(e.paths))}if(j.resolve(o)!==j.resolve(bo(e.paths))){let g=j.join(e.paths.stagingRoot,"state");t.exists(g)||t.mkdirExclusive(g,448),t.exists(bo(e.paths))&&t.removeOwnedPath(bo(e.paths)),t.copyTreeExclusive(e.oldKeysDir,bo(e.paths))}let c=nU(e,t),u=j.join(Wt(e.paths),"tada-ride-agent.db"),l=j.join(Wt(e.paths),"ambient-ride.db");if(t.exists(l))throw me("MIGRATION_COLLISION");Vn(t,u,l);for(let g of["-wal","-shm","-journal"]){let _=`${u}${g}`,E=`${l}${g}`;if(t.exists(_)){if(t.exists(E))throw me("MIGRATION_COLLISION");Vn(t,_,E)}}let d=qu(e,e.paths.stagingRoot);Ro(t,e.paths.stagingRoot);let m=sU(t,n,d,c,r);t.writeFileExclusive(j.join(e.paths.stagingRoot,xo),cR(m),Bn),t.fsyncFile(j.join(e.paths.stagingRoot,xo)),t.fsyncDirectory(e.paths.stagingRoot),Vn(t,e.paths.stagingRoot,e.paths.ambientRoot),i=!1,t.unlink(vo(e.paths)),t.fsyncDirectory(j.dirname(e.paths.stagingRoot)),pR(t,e.paths,r);let f=qu(e,e.paths.ambientRoot);return Ro(t,e.paths.ambientRoot),yR(e,t,"migrated",r,c,f)}catch(a){if(i)try{t.removeOwnedStaging(e.paths.stagingRoot,r)}catch{throw me("MIGRATION_INTERRUPTED","staging cleanup failed")}throw a}finally{s.release()}}function cU(e,t,r){let n=e.quiesceLegacy();try{let s=Ao(e),i=dR(t,e.paths,s);pR(t,e.paths,i.attemptId);let a=qu(e,e.paths.ambientRoot);return Ro(t,e.paths.ambientRoot),yR(e,t,"resumed",r,hR(t,e.paths),a)}finally{n.release()}}function lU(e,t){let r=vo(t);if(!e.exists(r))return;let n=e.readFile(r).toString("utf8").trim();if(!n||n.includes(`
580
+ `))throw me("MIGRATION_CONFLICT","invalid staging owner");e.removeOwnedStaging(t.stagingRoot,n)}function uU(e,t,r){let n=j.join(e.paths.ambientRoot,oR),s;try{s=(e.validate??ku)({dataDir:ju(e.paths),keysDir:rU(e.paths),dbPath:j.join(ju(e.paths),"ambient-ride.db"),passphrase:mR(e,e.paths.ambientRoot)})}catch{throw me("MIGRATION_VALIDATION_FAILED")}Ro(t,e.paths.ambientRoot);let i=hR(t,e.paths);if(t.exists(n)){let o=Vu(t,n,"MIGRATION_INTERRUPTED");if(o.schemaVersion!==1||!["migrated","resumed","already_migrated"].includes(o.status)||!Array.isArray(o.mappedLegacyConfig)||!Array.isArray(o.droppedLegacyConfig)||!gR(o.mappedLegacyConfig,o.droppedLegacyConfig))throw me("MIGRATION_INTERRUPTED","invalid report");return{schemaVersion:1,status:o.status,sourcePath:o.sourcePath,sourceDataPath:o.sourceDataPath,sourceKeysPath:o.sourceKeysPath,backupPath:o.backupPath,mappedLegacyConfig:o.mappedLegacyConfig,droppedLegacyConfig:o.droppedLegacyConfig,validation:s}}let a=fR("already_migrated",e,i,s);return uR(t,n,a,r),a}function _R(e){let t=e.fs??pU,r=e.attemptId??Bu.randomUUID();eU(e.paths);let n;try{n=t.acquireLock(e.paths.lockPath)}catch{throw me("MIGRATION_CONFLICT","migration lock is held")}try{try{lU(t,e.paths);let s=Qx(e.paths,a=>t.exists(a));switch(Zx(e.paths,s).state){case"fresh":return{schemaVersion:1,status:"fresh",mappedLegacyConfig:[],droppedLegacyConfig:[]};case"ambient_fresh":return{schemaVersion:1,status:"ambient_fresh",mappedLegacyConfig:[],droppedLegacyConfig:[]};case"legacy_candidate":return oU(e,t,r);case"resume_before_backup":return cU(e,t,r);case"already_migrated":return uU(e,t,r)}}catch(s){throw/\b(?:MIGRATION_|INVALID_|UNSAFE_|STAGING_)[A-Z_]+/.test(String(s))?s:me("MIGRATION_INTERRUPTED")}}finally{n.release()}}function ER(e,t,r=[]){let n=F.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw me("UNSAFE_STATE_ENTRY");F.mkdirSync(t,{mode:n.mode&511,recursive:!1});try{for(let i of F.readdirSync(e)){if(r.includes(i))continue;let a=j.join(e,i),o=j.join(t,i),c=F.lstatSync(a);if(c.isSymbolicLink()||!c.isDirectory()&&!c.isFile())throw me("UNSAFE_STATE_ENTRY");if(c.isDirectory())ER(a,o);else{F.copyFileSync(a,o,F.constants.COPYFILE_EXCL),F.chmodSync(o,c.mode&511),F.chownSync(o,c.uid,c.gid);let u=F.openSync(o,"r");try{F.fsyncSync(u)}finally{F.closeSync(u)}}}F.chmodSync(t,n.mode&511),F.chownSync(t,n.uid,n.gid);let s=F.openSync(t,"r");try{F.fsyncSync(s)}finally{F.closeSync(s)}}catch(s){throw F.rmSync(t,{recursive:!0}),s}}function dU(e,t){let r=`${e}.owner`;if(!F.existsSync(r)||F.readFileSync(r,"utf8").trim()!==t)throw me("STAGING_NOT_OWNED");F.existsSync(e)&&F.rmSync(e,{recursive:!0}),F.unlinkSync(r);let n=F.openSync(j.dirname(e),"r");try{F.fsyncSync(n)}finally{F.closeSync(n)}}function aR(e){let t=F.openSync(e,"r");try{F.fsyncSync(t)}finally{F.closeSync(t)}}var pU={exists:F.existsSync,lstat:F.lstatSync,mkdirExclusive(e,t){F.mkdirSync(e,{mode:t,recursive:!1})},copyTreeExclusive:ER,removeOwnedPath(e){F.rmSync(e,{recursive:!0})},rename(e,t){if(F.existsSync(t))throw me("MIGRATION_COLLISION");F.renameSync(e,t)},removeOwnedStaging:dU,writeFileExclusive(e,t,r){F.writeFileSync(e,t,{flag:"wx",mode:r})},readFile:F.readFileSync,readlink:F.readlinkSync,realpath:F.realpathSync,unlink:F.unlinkSync,fsyncFile:aR,fsyncDirectory:aR,acquireLock(e){let t=`${e}.reclaim`,r=(o,c)=>o.dev===c.dev&&o.ino===c.ino,n=()=>{let o=new Error(`EEXIST: migration lock is held, open '${e}'`);return o.code="EEXIST",o},s=(o=!1)=>{if(!o&&F.existsSync(t))throw n();let c;try{return c=F.openSync(e,"wx",Bn),F.writeFileSync(c,`${process.pid}
581
+ ${Bu.randomUUID()}
582
+ `,"utf8"),F.fsyncSync(c),{descriptor:c,identity:F.fstatSync(c)}}catch(u){if(c!==void 0){try{let l=F.lstatSync(e),d=F.fstatSync(c);r(l,d)&&F.unlinkSync(e)}catch{}F.closeSync(c)}throw u}},i;try{i=s()}catch(o){if(o.code!=="EEXIST"||F.existsSync(t))throw o;let c,u;try{c=F.openSync(e,"r"),u=F.fstatSync(c);let d=Number(F.readFileSync(c,"utf8").trim().split(/\s+/u)[0]);throw!Number.isSafeInteger(d)||d<=0||process.kill(d,0),o}catch(d){if(!(d instanceof Error)||!("code"in d)||d.code!=="ESRCH")throw d}finally{c!==void 0&&F.closeSync(c)}try{F.linkSync(e,t)}catch{throw o}let l=F.lstatSync(t);try{let d=F.lstatSync(e);if(u===void 0||!r(u,l)||!r(d,l))throw o;F.unlinkSync(e),i=s(!0)}finally{try{let d=F.lstatSync(t);r(d,l)&&F.unlinkSync(t)}catch{}}}let a=!1;return{release(){if(!a){a=!0,F.closeSync(i.descriptor);try{let o=F.lstatSync(e);r(o,i.identity)&&F.unlinkSync(e)}catch(o){if(o.code!=="ENOENT")throw o}}}}}};p();function TR(e,t){let r=t.replace(/\s*[\r\n]+\s*/g," ");process.stderr.write(JSON.stringify({error:e,message:r})+`
583
+ `)}p();var mU="22.22.0";function bR(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(e);if(!t)return!1;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=t[4];return r!==22?r>22:n!==22?n>22:s>0||s===0&&i===void 0}function vR(e){return`Node.js ${mU} or newer is required; found ${e}. Upgrade Node.js and run the installer again.`}function hU(e){if(!H.existsSync(e))return{};let t={};for(let r of H.readFileSync(e,"utf8").split(`
584
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");s<=0||(t[n.slice(0,s).trim()]=n.slice(s+1).trim())}return t}var xR;function RR(e){try{return process.kill(e,0),!0}catch{return!1}}function Gu(e){let t=pe.join(e,"run"),r=`${e}.amb-migration-quiesced`;if(H.existsSync(r)){let i=Number.parseInt(H.readFileSync(r,"utf8").trim(),10);if(Number.isSafeInteger(i)&&i>1&&RR(i))throw new Error("MIGRATION_CONFLICT: legacy quiescence is held");H.unlinkSync(r)}let n=H.openSync(r,"wx",384);H.writeFileSync(n,`${process.pid}
585
+ `),H.closeSync(n);let s;try{if(H.existsSync(t))for(let o of H.readdirSync(t)){if(!/^(?:mon|sup|relay)-.+\.pid$/.test(o))continue;let c=Number.parseInt(H.readFileSync(pe.join(t,o),"utf8").trim(),10);if(Number.isSafeInteger(c)&&c>1&&c!==process.pid&&RR(c))throw new Error(`MIGRATION_CONFLICT: legacy writer pid ${c} is still active`)}let a=[pe.join(e,"state","data","tada-ride-agent.db"),pe.join(e,"state","data","ambient-ride.db"),pe.join(e,"data","tada-ride-agent.db"),pe.join(e,"data","ambient-ride.db")].find(o=>H.existsSync(o));a&&(s=new gU(a,{fileMustExist:!0,timeout:0}),s.pragma("wal_checkpoint(TRUNCATE)"),s.exec("BEGIN EXCLUSIVE"))}catch(i){try{s?.close()}catch{}try{H.unlinkSync(r)}catch{}throw i}return{release(){try{s?.inTransaction&&s.exec("ROLLBACK"),s?.close()}catch{}finally{s=void 0}try{H.unlinkSync(r)}catch{}}}}function yU(e,t){return{legacyRoot:t,ambientRoot:e,stagingRoot:`${e}.migrating`,backupRoot:`${t}.bak`,lockPath:`${e}-migration.lock`}}function _U(e){let t={},r=[];for(let n of e){if(!H.existsSync(n))continue;let s=JSON.parse(H.readFileSync(n,"utf8")),i=s.env;if(i&&typeof i=="object"&&!Array.isArray(i)){for(let[o,c]of Object.entries(i))if(typeof c=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(o)){if(t[o]!==void 0&&t[o]!==c)throw new Error(`MIGRATION_CONFLICT: managed settings disagree for ${o}`);t[o]=c}}let a=s.skills?.entries?.["tada-ride"]?.env;if(a&&typeof a=="object"&&!Array.isArray(a)){for(let[o,c]of Object.entries(a))if(typeof c=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(o)){if(t[o]!==void 0&&t[o]!==c)throw new Error(`MIGRATION_CONFLICT: managed settings disagree for ${o}`);t[o]=c}}r.push({path:n,json:s})}return{legacy:t,documents:r}}function EU(e,t,r){let n=[];for(let a of e.documents){let o=a.json.env,c=a.json.skills?.entries?.["tada-ride"]?.env;for(let l of[o,c]){if(!l||typeof l!="object"||Array.isArray(l))continue;let d=l,m=Object.fromEntries(Object.entries(d).filter(([g,_])=>typeof _=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(g))),f=zr(m,t);for(let g of Object.keys(m))delete d[g];Object.assign(d,f.env)}let u=H.statSync(a.path);n.push({path:a.path,content:`${JSON.stringify(a.json,null,2)}
586
+ `,original:H.readFileSync(a.path),mode:u.mode&511})}let s=r,i=[];try{for(let a of n)s(a.path,a.content,a.mode),i.push(a)}catch(a){for(let o of i.reverse())s(o.path,o.original,o.mode);throw a}}function TU(e,t,r){let n=`${e}.amb-migration-${process.pid}.tmp`,s;try{s=H.openSync(n,"wx",r),H.writeFileSync(s,t),H.fsyncSync(s),H.closeSync(s),s=void 0,H.renameSync(n,e);let i=H.openSync(pe.dirname(e),"r");try{H.fsyncSync(i)}finally{H.closeSync(i)}}catch(i){s!==void 0&&H.closeSync(s);try{H.unlinkSync(n)}catch{}throw i}}function bU(e={}){let t=e.ambientRoot??ge(),r=e.legacyRoot??pe.join(pe.dirname(t),".tada"),n=e.skillDir??pe.resolve(pe.dirname(new URL(import.meta.url).pathname),".."),s=Qs(n),i=H.existsSync(s)?(e.quiesceLegacy??Gu)(s):void 0,a=pe.join(t,"state","data");if(Xn(a)){let N=(e.quiesceLegacy??Gu)(t);try{Ed(a)}finally{N.release()}}let o=yU(t,r),c=De().networks.paymentNetwork,u=e.managedSettingsPaths??[pe.join(wo.homedir(),".claude","settings.json"),pe.join(wo.homedir(),".openclaw","openclaw.json")],l=_U(u),d=e.environmentSnapshot??{...process.env},m;try{Zs(s,pe.join(r,"state")),m=(e.migrate??_R)({paths:o,oldDataDir:pe.join(r,"state","data"),oldKeysDir:pe.join(r,"state","keys"),paymentNetwork:c,installManagedCli:e.installManagedCli??(()=>{}),smoke:e.smoke??(()=>{}),quiesceLegacy:()=>(e.quiesceLegacy??Gu)(r),managedLegacyLink:e.managedLegacyLink??pe.join(wo.homedir(),".local","bin","tada"),expectedLegacyLinkTarget:e.expectedLegacyLinkTarget??pe.join(r,"cli","tada"),transformEnv:(N,k)=>zr([{name:"legacy-state",env:N},{name:"managed-settings",env:l.legacy},{name:"process-env",env:d}],k)})}finally{i?.release()}EU(l,c,e.replaceManagedFile??TU);let f=pe.join(t,"state","data"),g=pe.join(t,"state","keys"),_=pe.join(f,".installed"),E=pe.join(f,".env");if(H.existsSync(_)){let N=JSON.parse(H.readFileSync(_,"utf8"));return{status:"already_installed",migration:m,output:{status:"already_installed",installed_at:N.installed_at,skill_dir:n,state_dir:t,data_dir:f,keys_dir:g,migration:m}}}H.mkdirSync(f,{recursive:!0,mode:448}),H.mkdirSync(g,{recursive:!0,mode:448});let T={...zr(d,c).env,...zr(l.legacy,c).env,...hU(E)},x=T.AMB_RIDE_PASSPHRASE??AR.randomBytes(32).toString("hex"),R=T.AMB_RIDE_PASSPHRASE?"preserved from existing .env":"newly generated",I={...T,AMB_RIDE_PASSPHRASE:x};return H.writeFileSync(E,["# Ambient Ride - auto-generated by amb install",`# Generated at: ${new Date().toISOString()}`,`# Source: ${R}`,...Object.entries(I).sort(([N],[k])=>N.localeCompare(k)).map(([N,k])=>`${N}=${k}`),""].join(`
587
+ `),{mode:384}),H.writeFileSync(_,JSON.stringify({installed_at:new Date().toISOString(),skill_dir:n,layout:"self-contained"},null,2),{mode:384}),{status:"installed",migration:m,output:{status:"installed",skill_dir:n,state_dir:t,data_dir:f,keys_dir:g,env_file:E,passphrase_source:R,migration:m,next_steps:["No platform config edits needed \u2014 the skill is self-contained.","Run `amb whoami` to see onboarding state."]}}}var vU=async e=>{let t=xR?.nodeVersion??process.versions.node;bR(t)||(TR("AMB_INSTALL_FAILED",vR(t)),process.exit(1)),process.env.SUDO_UID&&(w({status:"skipped_sudo",message:"Skipped agent state init because this ran under sudo. If `amb install` has already been run as your own user, there is nothing to do; otherwise run it as your own user (on a root-only machine, `sudo env -u SUDO_UID amb install`)."}),process.exit(0));try{let n=bU(xR??{installManagedCli(){let s=process.argv[1];if(!s||pe.basename(s)!=="amb")throw new Error("MIGRATION_INTERRUPTED: Ambient CLI entrypoint is not verified");H.accessSync(s,H.constants.R_OK)},smoke(s){let i=fU(process.execPath,[process.argv[1],"--json","whoami"],{encoding:"utf8",env:{...process.env,AMB_RIDE_STATE_DIR:s}});if(i.error||i.status!==0)throw new Error("MIGRATION_INTERRUPTED: Ambient runtime smoke failed")}});n.status==="installed"&&typeof n.output.data_dir=="string"&&await Gt(n.output.data_dir,"activation_installed"),w(n.output),process.exit(0)}catch(r){let n=String(r),s=n.includes("BACKUP_EXISTS")?"MIGRATION_BACKUP_EXISTS":n.includes("VALIDATION")?"MIGRATION_VALIDATION_FAILED":n.includes("CONFLICT")?"MIGRATION_CONFLICT":"MIGRATION_INTERRUPTED";process.stderr.write(`${JSON.stringify({error:s,message:s})}
588
+ `),process.exit(1)}},xU=async e=>{let[t]=e;t||(console.error("error: Usage: amb setup-check <wallet_address>"),process.exit(1));let r=D();try{O(r.dataDir)}catch{w({wallet:{registered:!1,address:null,type:null,is_active:!1},jwt:null,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0)}let n=jt(t),s=n?{registered:!0,address:n.wallet_address,type:n.wallet_type}:{registered:!1,address:null,type:null};n||(w({wallet:s,jwt:null,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let i=Jd(n.wallet_address),a=i?{valid:!0,expires_at:i.expires_at}:{valid:!1,expires_at:null};i||(w({wallet:s,jwt:a,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let o=qb(n.wallet_address),c={verified:o.length>0,numbers:o};o.length===0&&(w({wallet:s,jwt:a,phone:c,deposit:null,ready_for_ride:!1}),process.exit(0));let u=null,l=!1;try{u=(await Promise.allSettled(r.depositNetworks.map(async f=>{let[g,_,E]=await Promise.all([Ti(f,n.wallet_address),Ei(f,n.wallet_address),es(f)]);return{network:f.name,isActive:g,deposited:_.toString(),minRequired:E.toString()}}))).filter(f=>f.status==="fulfilled").map(f=>f.value),l=u.some(f=>f.isActive)}catch{u=null,l=!1}w({wallet:s,jwt:a,phone:c,deposit:u,ready_for_ride:l})},wR={install:vU,"setup-check":xU};p();import DU from"fs";p();import So from"fs";import AU from"path";p();function SR(e,t){return!!S().prepare("SELECT 1 FROM processed_events WHERE ride_id=? AND event_id=?").get(e,t)}function IR(e,t,r){S().prepare("INSERT OR IGNORE INTO processed_events(ride_id,event_id,seq) VALUES(?,?,?)").run(e,t,r)}function PR(e){return S().prepare("SELECT MAX(seq) AS m FROM processed_events WHERE ride_id=?").get(e).m??0}p();import RU from"path";function Hu(e,t){return RU.join(e,"events",`${t}.jsonl`)}function $u(e,t){let r=Wr({rideId:t.rideId,kind:t.kind,status:t.status,content:t.content});if(SR(t.rideId,r))return null;let n=PR(t.rideId)+1,s={v:Av,seq:n,eventId:r,rideId:t.rideId,kind:t.kind,terminal:t.terminal,ts:t.ts,payload:t.payload},i=Hu(e,t.rideId);return So.mkdirSync(AU.dirname(i),{recursive:!0}),So.appendFileSync(i,JSON.stringify(s)+`
589
+ `),IR(t.rideId,r,n),s}function DR(e,t,r){let n=Hu(e,t);if(!So.existsSync(n))return[];let s=[];for(let i of So.readFileSync(n,"utf8").split(`
590
+ `))if(i)try{let a=JSON.parse(i);a.seq>r&&s.push(a)}catch{process.stderr.write(`[event-log] skipping unparseable line in ${t}.jsonl
591
+ `)}return s}p();p();var wU={WAITPAY:"waiting for payment",PAYCONFIRMED:"payment confirmed, matching a driver",PENDING:"searching for a driver",MATCHED:"a driver candidate was found",CONFIRMED:"the match was confirmed",ASSIGNED:"a driver is assigned and on the way",PICKUP:"the driver is on the way to the pickup point",PICKUP_ARRIVED:"the driver has arrived at the pickup point",INUSE:"the ride is in progress",FINISHED:"the ride completed successfully",NOT_MATCHED:"no driver was found",CANCELED:"the ride was cancelled",ACCIDENT_CANCELED:"the ride was cancelled due to an accident",USER_CANCELED:"cancelled by the rider",USER_CANCELED_BEFORE_CALL:"cancelled by the rider before matching",USER_CANCELED_NO_FREE:"cancelled by the rider (cancellation fee charged)",DRIVER_CANCELED:"cancelled by the driver",DRIVER_CANCELED_RECALLABLE:"cancelled by the driver (can re-request)",COMPANY_CANCELED:"cancelled by the operator",COMPANY_CANCELED_RECALLABLE:"cancelled by the operator (can re-request)",EXPIRED:"the request expired (no driver found)",EXPIRED_RECALLABLE:"the request expired (can re-request)",EXPIRED_BEFORE_PAY:"the payment window expired",ERROR_PAYMENT:"a payment error occurred",ERROR:"an unexpected error occurred"};function OR(e,t){let r=t?.trim();return r&&r.length>0?r:wU[e]??e}var SU={KRW:"\u20A9",USD:"$",SGD:"S$",VND:"\u20AB"};function Io(e,t){let r=e.toLocaleString("en-US"),n=SU[t];return n?`${n}${r}`:`${r} ${t}`}function IU(e){if(!e)return"";let t=[];e.carPlate&&t.push(`plate ${e.carPlate}`);let r=[e.carColor,e.carModel].filter(Boolean).join(" ").trim();return r&&t.push(r),e.name&&t.push(`driver ${e.name}`),t.length?`, ${t.join(", ")}`:""}function PU(e){let t=typeof e=="string"?e.toUpperCase():"";return t==="NY"?"Throo":t===""?"TADA/Throo":"TADA"}function CR(e){let t=PU(e.payload.region);if(e.kind==="driver_chat"){let u=e.payload.content??"";return`${t} ride: driver sent "${u}". Tell the user briefly; their next short reply may be for the driver. No unrelated questions.`}let r=e.payload.statusMessage,n=String(e.payload.status??""),s=OR(n,r);if(e.terminal){let u=e.payload.tip,l=`${t} ride ${e.rideId} ${s}. Tell the user the final outcome briefly.`;if(n==="FINISHED"&&(l+=" Ask whether they would like to see their receipt. Fetch it only if they explicitly ask."),u){let d=u.maxAmount?`from ${Io(u.minAmount,u.currency)} up to ${Io(u.maxAmount,u.currency)}`:`from ${Io(u.minAmount,u.currency)}`;l+=` Tips ${d} are welcome. You may offer the tip together with that receipt question.`}return l}let i=e.payload.etaMin,a=IU(e.payload.driver),o=e.payload.rideShareUrl,c=o?` Live tracking: ${o} \u2014 include it as a markdown link.`:"";return`${t} ride ${e.rideId} is ${s}${a}${i?`, pickup ~${i}min`:""}. Tell the user briefly.${c} No unrelated questions.`}function OU(e){try{return parseInt(DU.readFileSync(e,"utf8").trim(),10)||0}catch{return 0}}var CU=e=>new Promise(t=>setTimeout(t,e));async function NU(e){let t=e.write??(n=>process.stdout.write(n+`
592
+ `)),r=e.pollMs??2e3;for(;;){let n=OU(e.cursorFile),s=DR(e.root,e.rideId,n);for(let i of s){let a=e.prompt?{...i,prompt:CR(i)}:i;if(t(JSON.stringify(a)),i.terminal)return 0}if(!e.follow)return 0;await CU(r)}}var LU=async e=>{let t=a=>{let o=e.indexOf(a);return o>=0?e[o+1]:void 0},r=t("--ride"),n=t("--cursor-file");(!r||!n)&&(console.error(JSON.stringify({error:"USAGE",message:"amb events --ride <id> --cursor-file <f> [--follow] [--prompt]"})),process.exit(1));let s=D();O(s.dataDir),await nr(r);let i=await NU({root:ge(),rideId:r,cursorFile:n,follow:e.includes("--follow"),prompt:e.includes("--prompt")});process.exit(i)},NR={events:LU};p();import Ku from"fs";import Yu from"path";import{spawn as jU}from"child_process";p();var LR=[2e3,5e3,15e3,3e4];function kR(e){if(e.exitCode===0)return{action:"stop",code:0};if(e.exitCode===1)return{action:"stop",code:1};let t=Math.min(e.restartCount,LR.length-1);return{action:"restart",delayMs:LR[t]}}p();import kU from"net";import Wu from"fs";import MU from"path";function MR(e){let t=e.trace??(()=>{});try{Wu.mkdirSync(MU.dirname(e.sockPath),{recursive:!0})}catch{}try{Wu.unlinkSync(e.sockPath)}catch{}let r=kU.createServer(n=>{let s="";n.on("data",i=>{s+=i.toString();let a=s.indexOf(`
593
+ `);if(a<0)return;let o=s.slice(0,a);s="",(async()=>{let c;try{let u=JSON.parse(o);typeof u?.content!="string"?c={ok:!1,reason:"bad_request"}:(t("chat_control_req",{len:u.content.length}),c=await e.send(u.content))}catch(u){c={ok:!1,reason:`bad_request: ${u.message}`}}try{n.write(JSON.stringify(c)+`
594
+ `)}catch{}n.end()})()}),n.on("error",()=>{})});return r.on("error",n=>t("chat_control_server_error",{error:String(n)})),r.listen(e.sockPath,()=>t("chat_control_listen",{sockPath:e.sockPath})),{close(){try{r.close()}catch{}try{Wu.unlinkSync(e.sockPath)}catch{}}}}p();var UU=5e3,UR=3e4,FR=3,jR=Symbol("timed_out");function FU(e){let t,r=new Promise(n=>{t=setTimeout(()=>n(jR),UU)});return Promise.race([e,r]).finally(()=>clearTimeout(t))}function qR(e){let t=e.trace??(()=>{}),r=e.now??Date.now,n=null,s=null,i=null,a=0,o=null,c=(u,l)=>{u!==null&&u!==s||(a+=1,o=r(),s=null,i=null,t("share_fetch_failed",{attempt:a,reason:l}),a>=FR&&t("share_fetch_gave_up"))};return async u=>{if(e.mode!=="tada"||u.rideShareUrl||!u.driverInfo)return u;if(Lt(u.status))return n?{...u,rideShareUrl:n}:u;if(n)return{...u,rideShareUrl:n};if(s&&i!==null&&r()-i>=UR)return c(s,"abandoned"),t("share_fetch_abandoned",{status:u.status}),u;if(!s){if(a>=FR||o!==null&&r()-o<UR)return u;let m=e.backend.getShareLink(e.rideId).then(f=>f.url);m.then(f=>{n=f,s=null,i=null},()=>{}),s=m,i=r()}let l=s,d;try{d=await FU(l)}catch(m){return c(l,String(m.message??m)),u}return d===jR?(t("share_fetch_slow",{status:u.status}),u):(n=d,s=null,i=null,{...u,rideShareUrl:n})}}async function qU(e){let t=e.trace??(()=>{}),r=await e.fetchStatus();t("poll_result",{status:r.status,hasDriverInfo:!!r.driverInfo,changed:r.status!==e.lastStatusRef.status,raw:r});let n=!!e.lastRideIdRef&&!!r.rideId&&r.rideId!==e.lastRideIdRef.rideId;if(r.rideId&&e.lastRideIdRef&&(e.lastRideIdRef.rideId=r.rideId),r.status===e.lastStatusRef.status){if(n&&e.onStatusChange)try{await e.onStatusChange({eventId:Wr({rideId:e.rideId,kind:"ride_status",status:`RIDE_ID:${r.rideId}`}),status:r.status,previousStatus:e.lastStatusRef.status,rideId:r.rideId,rideCreatedObserved:!0})}catch{}return{terminal:!1}}let s=e.lastStatusRef.status,i=Lt(r.status),a={status:r.status};if(e.region&&(a.region=e.region),r.driverInfo&&(a.driver=r.driverInfo),r.driverInfo&&r.rideShareUrl&&(a.rideShareUrl=r.rideShareUrl),r.rideId&&(a.upstreamRideId=r.rideId),r.statusMessage&&r.statusMessage.trim()&&(a.statusMessage=r.statusMessage),i&&r.status==="FINISHED"&&e.tipLookup)try{let c=await e.tipLookup();c&&(a.tip=c)}catch{}let o=$u(e.root,{rideId:e.rideId,kind:"ride_status",status:r.status,terminal:i,ts:new Date().toISOString(),payload:a});if(e.onStatusChange)try{await e.onStatusChange({eventId:o?.eventId??Wr({rideId:e.rideId,kind:"ride_status",status:r.status}),status:r.status,previousStatus:s,rideId:r.rideId,rideCreatedObserved:n})}catch{}return Dn(e.rideId,r.status),e.lastStatusRef.status=r.status,t("event_appended",{status:r.status,terminal:i}),{terminal:i}}function BU(e,t,r,n){let s;return e.on("ready",()=>{if(!s)try{s=MR({sockPath:lo(r,t),send:i=>e.send(i),trace:n}),n("chat_control_attached",{rideId:t})}catch(i){n("chat_control_attach_failed",{error:String(i)})}}),{close(){try{s?.close()}catch{}}}}function VU(e){return Yu.join(ge(),"run",`monitor-trace-${e}.log`)}function VR(e){let t=VU(e);return(r,n)=>{try{Ku.mkdirSync(Yu.dirname(t),{recursive:!0}),Ku.appendFileSync(t,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:r,rideId:e,...n??{}})+`
595
+ `)}catch{}}}var Ju=5e3,GU=250,BR=e=>new Promise(t=>setTimeout(t,e));function HU(e,t){let r=(async()=>{try{let n=await e.getTipConfig(t);return n.enabled?{minAmount:n.minAmount,currency:n.currency,...n.maxAmount!==void 0?{maxAmount:n.maxAmount}:{}}:null}catch{return null}})();return async()=>{let n=new Promise(s=>setTimeout(()=>s(null),5e3));return await Promise.race([r,n])}}var $U=async e=>{let t=e[0];t||(console.error(JSON.stringify({error:"USAGE",message:"amb monitor <request_id>"})),process.exit(1));let r=VR(t),n=D();O(n.dataDir);let s=Ae(t);if(!s){r("exit",{reason:"ride_not_found"}),console.error(JSON.stringify({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}`})),process.exit(1);return}let i;try{i=await ft(n,s)}catch(B){r("backend_resolve_failed",{msg:B.message}),console.error(JSON.stringify({error:"BACKEND_UNAVAILABLE",message:B.message})),process.exit(1);return}let{backend:a,mode:o}=i;r("startup",{rideId:t,mode:o,gatewayServerUrl:n.gatewayServerUrl,dataDir:n.dataDir,pollIntervalMs:Ju});let c=HU(a,s.region),u=qR({backend:a,mode:o,rideId:t,trace:r}),l="mon-"+t;if(!yu(ge(),l)){r("already_running",{lockName:l}),process.exit(0);return}r("lock_acquired",{lockName:l});let d=null,m,f={status:s.status??""},g={at:s.status?.toUpperCase()==="PENDING"&&s.status_updated_at?s.status_updated_at*1e3:void 0},_={rideId:s.ride_id??void 0},E=new Set,T=0,x=!1,R=B=>{if(!x){x=!0;try{d?.dispose()}catch{}m?.close(),ao(ge(),l),r("lock_released",{reason:B})}},I=(B,Y)=>{throw R(Y),r("exit",{code:B,reason:Y}),process.exit(B),new Error("unreachable")},N=!1,k=async B=>{N&&I(2,`${B}_repeat`),N=!0,r("signal",{signal:B});let Y;try{await Promise.race([Promise.allSettled([...E]),new Promise(re=>{Y=setTimeout(re,GU)})])}finally{Y&&clearTimeout(Y)}I(2,B)};process.on("SIGTERM",()=>{k("SIGTERM")}),process.on("SIGINT",()=>{k("SIGINT")}),process.on("uncaughtException",B=>{r("crash",{source:"uncaughtException",error:String(B),stack:B?.stack}),R("uncaughtException"),r("exit",{code:1,reason:"uncaughtException"}),process.exit(1)}),process.on("unhandledRejection",B=>{let Y=B instanceof Error?B:new Error(String(B));r("crash",{source:"unhandledRejection",error:String(Y),stack:Y.stack}),R("unhandledRejection"),r("exit",{code:1,reason:"unhandledRejection"}),process.exit(1)});try{for(;;){T+=1,r("poll_begin",{iteration:T,lastStatus:f.status}),o==="wallet"&&(ie(s.wallet_address)||(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED"})+`
596
+ `),r("jwt_missing",{iteration:T}),I(1,"jwt_missing")));let B;try{B=await WU({backend:a,rideId:t,lastStatusRef:f,lastRideIdRef:_,trace:r,tipLookup:c,region:s.region,shareEnricher:u,onStatusChange:async Y=>{let re=Date.now();Y.status.toUpperCase()==="PENDING"&&g.at==null&&(g.at=re),g.at==null&&xT(Y.status)&&(g.at=s.created_at*1e3);let q=To(n.dataDir,s,{...Y,durationMs:Math.max(0,re-(g.at??s.created_at*1e3))});E.add(q);try{await q}finally{E.delete(q)}}})}catch(Y){let re=Y.message;re.includes("401")&&(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED",message:re})+`
597
+ `),r("jwt_expired",{iteration:T,message:re}),I(1,"jwt_expired")),process.stderr.write(`poll_error: ${re}
598
+ `),r("poll_error",{iteration:T,message:re}),await BR(Ju);continue}B.driverInfo&&!d&&(r("chat_client_start",{rideId:t}),d=a.subscribeChat(t),d.on("message",Y=>{let re=Y.data,q=re?.content??"",Z=re?.senderType,Ve=Z==="DRIVER"?"driver":Z==="SYSTEM"?"system":"unknown";r("chat_msg_raw",{raw:re,senderType:Z,sender:Ve}),$u(ge(),{rideId:t,kind:"driver_chat",terminal:!1,ts:new Date().toISOString(),content:q,payload:{content:q,sender:Ve,region:s.region}})}),d.on("error",Y=>{r("chat_error",{message:Y.message})}),d.connect(),m=BU(d,t,ge(),r)),Lt(B.status)&&(r("terminal",{status:B.status}),I(0,"terminal")),await BR(Ju)}}catch(B){if(x)throw B;let Y=B;r("crash",{source:"poll_loop",error:String(Y),stack:Y?.stack}),R("crash"),r("exit",{code:1,reason:"crash"}),process.exit(1)}};async function WU(e){let t;if(await qU({root:ge(),rideId:e.rideId,region:e.region,fetchStatus:async()=>{let r=await e.backend.getRideStatus(e.rideId),n=e.shareEnricher?await e.shareEnricher(r):r;return t=n,n},lastStatusRef:e.lastStatusRef,lastRideIdRef:e.lastRideIdRef,trace:e.trace,tipLookup:e.tipLookup??void 0,onStatusChange:e.onStatusChange}),!t)throw new Error("fetchStatus did not run");return t}function JU(){let e=process.argv[1]??"",t=e?Yu.resolve(e):"";if(!t||!Ku.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}function KU(e){let t=VR(e);return(r,n)=>t(r,{role:"supervisor",...n??{}})}var YU=async e=>{let t=e[0];if(!t){console.error(JSON.stringify({error:"USAGE",message:"amb monitor-supervisor <request_id>"})),process.exit(1);return}let r=KU(t);r("sup_start",{rideId:t,pid:process.pid});let n="sup-"+t;if(!yu(ge(),n)){r("sup_already_running",{lockName:n}),process.exit(0);return}r("sup_lock_acquired",{lockName:n});let s;try{s=JU(),r("sup_entry_resolved",{ambEntry:s})}catch(f){r("sup_entry_unresolved",{error:String(f)}),ao(ge(),n),r("sup_stop",{code:2,reason:"entry_unresolved"}),process.exit(2);return}let i,a=!1,o=!1,c=f=>{o||(o=!0,ao(ge(),n),r("sup_lock_released",{reason:f}))},u=()=>{if(i&&i.exitCode===null&&i.signalCode===null)try{i.kill("SIGTERM")}catch{}},l=async f=>{if(a)return;a=!0,r("sup_signal",{signal:f});let g=!!(i&&i.exitCode===null&&i.signalCode===null);u(),g&&await new Promise(_=>{let E=!1,T=()=>{E||(E=!0,_())};i.once("exit",T),setTimeout(T,25e3).unref()}),c(f),r("sup_stop",{code:2,reason:f}),process.exit(2)};process.on("SIGTERM",()=>{l("SIGTERM")}),process.on("SIGINT",()=>{l("SIGINT")});let d=(f,g)=>{if(a)return;a=!0;let _=g instanceof Error?g:new Error(String(g));r("sup_crash",{source:f,error:String(_),stack:_.stack}),u(),c("crash"),r("sup_stop",{code:1,reason:f}),process.exit(1)};process.on("uncaughtException",f=>d("uncaughtException",f)),process.on("unhandledRejection",f=>d("unhandledRejection",f));let m=0;await new Promise(()=>{let f=()=>{i=jU(process.execPath,[s,"monitor",t],{detached:!1,stdio:"ignore"}),r("sup_spawn",{childPid:i.pid,attempt:m}),i.on("error",g=>{a||(r("sup_child_error",{error:g.message}),c("child_spawn_error"),r("sup_stop",{code:2,reason:"child_spawn_error"}),process.exit(2))}),i.on("exit",(g,_)=>{if(a)return;r("sup_child_exit",{exitCode:g,signal:_,restartCount:m});let E=kR({exitCode:g,signal:_,restartCount:m});if(r("sup_decision",{...E}),E.action==="stop"){c("terminal"),r("sup_stop",{code:E.code}),process.exit(E.code);return}m++,r("sup_restart",{delayMs:E.delayMs,restartCount:m}),setTimeout(f,E.delayMs)})};f()})},GR={monitor:$U,"monitor-supervisor":YU};p();function zU(e){let t=ie(e,"member")!==null,r=_i(e)!==null;return t||r?"active":"needs_login"}var XU="Your TADA/Throo session isn't active \u2014 run 'amb login' to sign in again.",QU=async e=>{let t=ze(),r=zn();if(t.mode===null){let i={mode:null,reason:"onboarding",identity:null,member_available:r,has_wallet:t.hasWallet,hint:"No credentials registered. Run 'amb install', then 'amb wallet-setup' to provision your wallet; add a TADA/Throo membership with 'amb login' if you want card payment."};w(i);return}if(t.mode==="tada"&&t.member){let i=zU(t.member.id),a=i==="active",o={mode:"tada",reason:t.reason,identity:{kind:"tada",member_id:t.member.id,phone:t.member.phone,display_name:t.member.display_name,region:t.member.region},member_available:r,has_wallet:t.hasWallet,authenticated:a,auth_state:i,...a?{}:{hint:XU}};w(o);return}if(t.mode==="wallet"&&t.walletAddress){let i={mode:"wallet",reason:t.reason,identity:{kind:"wallet",wallet_address:t.walletAddress},member_available:r,has_wallet:t.hasWallet};w(i);return}let n=t.mode==="tada"?"Run 'amb login' first.":"Run 'amb wallet-setup' first.",s={mode:t.mode,reason:t.reason,identity:null,member_available:r,has_wallet:t.hasWallet,hint:`--account=${t.mode} was forced but no ${t.mode==="tada"?"TADA/Throo member":"wallet"} credentials are registered. ${n}`};w(s)},HR={whoami:QU};p();p();function $R(e,t){S().prepare("INSERT OR REPLACE INTO member_login_sessions (session_token, expires_at, created_at) VALUES (?, ?, ?)").run(e,t,Math.floor(Date.now()/1e3))}function WR(){return S().prepare("SELECT * FROM member_login_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function Po(e){S().prepare("DELETE FROM member_login_sessions WHERE session_token = ?").run(e)}function JR(){S().prepare("DELETE FROM member_login_sessions").run()}p();import ZU from"os";import KR from"path";import e1 from"fs";import YR from"qrcode";async function zu(e){return YR.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"L"})}async function zR(e){let t=e1.mkdtempSync(KR.join(ZU.tmpdir(),"tada-login-")),r=KR.join(t,"qr.png");return await YR.toFile(r,e,{type:"png",margin:4,width:320}),r}import r1 from"readline/promises";async function n1(){let e=r1.createInterface({input:process.stdin,output:process.stdout});try{return(await e.question("Enter the 4-digit code shown in the TADA/Throo app: ")).trim()}finally{e.close()}}async function s1(){if(!zn()){w({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let e=D();O(e.dataDir);let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret};_r(Ye(e.cliGatewayHosts,e.cliGatewayHost));try{let r=await vu(t),n=Date.parse(r.expiresAt),s=Number.isFinite(n)?Math.floor(n/1e3):Math.floor(Date.now()/1e3)+600;JR(),$R(r.sessionToken,s);let i={status:"auth_required",approval_url:r.approvalUrl,expires_at:r.expiresAt};try{let a=await zu(r.approvalUrl);process.stderr.write(`Scan this QR to approve the login in the TADA/Throo app:
599
+ ${a}
600
+ `),i.qr_image_path=await zR(r.approvalUrl)}catch{}w(i)}catch{w({status:"error",message:"Failed to start login session."})}}var i1=async e=>{if(e.includes("--no-wait"))return s1();let r=D();if(!gd(r)){console.log("Member login is not available in this build (missing RIDER_CLI_APP credentials).");return}O(r.dataDir);let n={clientId:r.riderCliApp.clientId,clientSecret:r.riderCliApp.clientSecret};_r(Ye(r.cliGatewayHosts,r.cliGatewayHost));let s=await vu(n),i="";try{i=`
601
+ ${await zu(s.approvalUrl)}`}catch{}console.log(`Approve this login in the TADA/Throo app:${i} ${s.approvalUrl}
602
+ Then enter the 4-digit code the app shows.`);let a=e.indexOf("--code"),o=a>=0?e[a+1]:void 0,c=!1;for(let u=1;u<=5;u++){let l=o??await n1();try{let d=await xu(n,s.sessionToken,l);await Gt(r.dataDir,"activation_authenticated",{id:ur(d.memberId)}),console.log(`Logged in as TADA/Throo member ${d.memberId}.`);return}catch(d){if(d instanceof Be&&d.code==="invalid_user_code"){if(c=!0,console.log(`Code did not match (${u}/5)${u===4?" \u2014 last attempt!":""}.`),o!==void 0)return;continue}if(d instanceof Be&&d.code==="invalid_grant"){console.log(c?"Too many incorrect codes \u2014 the login session was destroyed. Please run `amb login` again.":"This login session is no longer valid (it may have expired, been denied, or already been used). Please run `amb login` again.");return}console.log("Login failed. Please run `amb login` again.");return}}console.log("Too many incorrect codes \u2014 the login session was destroyed. Please run `amb login` again.")},a1=async()=>{let e=D();O(e.dataDir),console.log(Hv()?"Logged out of TADA/Throo member account.":"No active TADA/Throo member session.")},o1=async e=>{let t=e.indexOf("--code"),r=t>=0?e[t+1]:void 0;if(r||(console.error("error: Usage: amb login-verify --code <4-digit-code>"),process.exit(1)),!zn()){w({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let n=D();O(n.dataDir);let s={clientId:n.riderCliApp.clientId,clientSecret:n.riderCliApp.clientSecret};_r(Ye(n.cliGatewayHosts,n.cliGatewayHost));let i=WR(),a=Math.floor(Date.now()/1e3);if(!i||i.expires_at<=a){i&&Po(i.session_token),w({status:"session_expired",message:"No active login session. Run `amb login --no-wait` to start over."});return}try{let o=await xu(s,i.session_token,r);Po(i.session_token),await Gt(n.dataDir,"activation_authenticated",{id:ur(o.memberId)}),w({status:"logged_in",member_id:o.memberId})}catch(o){if(o instanceof Be&&o.code==="invalid_user_code"){w({status:"invalid_code",message:"The 4-digit code did not match. Re-read the code in the TADA/Throo app and run `amb login-verify --code <code>` again."});return}if(o instanceof Be&&(o.code==="invalid_grant"||o.code==="agent_session_not_found"||o.code==="agent_session_already_decided"||o.code==="agent_session_expired")){Po(i.session_token),w({status:"session_expired",message:"The login session is no longer valid (expired, denied, or too many wrong codes). Run `amb login --no-wait` to start over."});return}w({status:"error",message:"Login failed. Run `amb login --no-wait` to start over."})}},XR={login:i1,logout:a1,"login-verify":o1};p();import Gn from"fs";import Hn from"path";p();var c1="proprietary (see LICENSE)";function Do(){let{cliVersion:e,gitSha:t}=De().artifact;return{version:e,git_sha:t,license:c1}}function QR(e){return`version: ${e.version}
477
603
  git_sha: ${e.git_sha}
478
- license: ${e.license}`}import N_ from"fs";import Ee from"path";function td(e,t){return[{arcname:`events-${e}.jsonl`,rel:Ee.join("events",`${e}.jsonl`)},{arcname:`monitor-trace-${e}.log`,rel:Ee.join("run",`monitor-trace-${e}.log`)},{arcname:`relay-error-${e}.log`,rel:Ee.join("run",`relay-error-${e}.log`)},{arcname:`relay-trace-${e}.jsonl`,rel:Ee.join("run",`relay-trace-${e}.jsonl`)},{arcname:`mon-${e}.pid`,rel:Ee.join("run",`mon-${e}.pid`)},{arcname:`sup-${e}.pid`,rel:Ee.join("run",`sup-${e}.pid`)},{arcname:`relay-${e}.pid`,rel:Ee.join("run",`relay-${e}.pid`)},{arcname:`cursor-openclaw-${e}`,rel:Ee.join("cursors",`openclaw-${e}`)},{arcname:`cursor-stdout-${e}`,rel:Ee.join("cursors",`stdout-${e}`)}].map(({arcname:n,rel:s})=>{let i=Ee.join(t,s);return{arcname:n,absPath:i,present:N_.existsSync(i)}})}function rd(e){let t=e.artifacts.filter(a=>a.present).map(a=>a.arcname),r=e.artifacts.filter(a=>!a.present).map(a=>a.arcname),n={ride_id:e.rideId,created_at:e.createdAt,version:e.version,ride_row:e.rideRow,liveness:e.liveness,collected:t,missing:r},s=e.rideRow===null?["_No local DB record for this request_id \u2014 confirm it is the id from `amb ride request` output (the local request_id, not the upstream ride id)._"]:["```json",JSON.stringify(e.rideRow,null,2),"```"],i=a=>a.length?a.map(c=>`- ${c}`):["- (none)"];return{markdown:[`# amb debug \u2014 ${e.rideId}`,"",`- created_at: ${e.createdAt}`,`- version: ${e.version.version} / git_sha ${e.version.git_sha} / branch ${e.version.branch} / install ${e.version.install_mode}`,"","## ride_requests row","",...s,"","## liveness (locks held-alive at collection time)","",`- monitor (mon-): ${e.liveness.monitor}`,`- supervisor (sup-): ${e.liveness.supervisor}`,`- relay (relay-): ${e.liveness.relay}`,"> The relay lock is held only by the OpenClaw delivery flavor; the stdout flavor (Claude Code / Hermes / codex) runs without it, so `relay: false` there is normal, not a failure.","","## collected","",...i(t),"","## missing","",...i(r),""].join(`
479
- `),manifest:n}}import{spawn as k_}from"child_process";import C_ from"path";var Gt=class extends Error{constructor(){super("zip binary not found on PATH"),this.name="ZipUnavailableError"}},Wt=class extends Error{constructor(t){super(`zip exited ${t}`),this.name="ZipFailedError"}},D_=(e,t,r)=>new Promise((n,s)=>{let i=k_(e,t,{cwd:r,stdio:"ignore"});i.on("error",s),i.on("exit",o=>n(o??1))});async function nd(e){if(!C_.isAbsolute(e.outZipPath))throw new Error("outZipPath must be absolute");let t=e.run??D_,r;try{r=await t("zip",["-r","-q",e.outZipPath,"."],e.stagingDir)}catch(n){throw n.code==="ENOENT"?new Gt:n}if(r!==0)throw new Wt(r)}function sd(e){let t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}var P_=async e=>{let t=e[0];if(!t||t.startsWith("--")){g({error:"USAGE",message:"amb debug <request_id>"}),process.exit(1);return}if(/[/\\]/.test(t)||t.includes("..")||t.includes("\0")){g({error:"INVALID_RIDE_ID",message:'rideId must not contain path separators or ".."'}),process.exit(1);return}b(et());let r=F(),n=new Date,s=ht.join(r,"debug"),i=ht.join(s,`.staging-${sd(n)}-${process.pid}`);yt.mkdirSync(i,{recursive:!0});let o=ht.join(s,`tada-debug-${t.slice(0,8)}-${sd(n)}.zip`);try{let a=td(t,r);for(let u of a)if(u.present)try{yt.copyFileSync(u.absPath,ht.join(i,u.arcname))}catch{u.present=!1}let c=Rn(),l=z(),d=rd({rideId:t,createdAt:n.toISOString(),version:{version:c.version,git_sha:c.git_sha,branch:l.install.repoBranch,install_mode:l.install.mode},rideRow:V(t)??null,liveness:{monitor:mt(r,`mon-${t}`),supervisor:mt(r,`sup-${t}`),relay:mt(r,`relay-${t}`)},artifacts:a.map(u=>({arcname:u.arcname,present:u.present}))});yt.writeFileSync(ht.join(i,"summary.md"),d.markdown),yt.writeFileSync(ht.join(i,"manifest.json"),JSON.stringify(d.manifest,null,2)),await nd({stagingDir:i,outZipPath:o}),yt.rmSync(i,{recursive:!0,force:!0}),w({ok:!0,zipPath:o,rideId:t,collected:a.filter(u=>u.present).map(u=>u.arcname),missing:a.filter(u=>!u.present).map(u=>u.arcname)})}catch(a){if(yt.rmSync(i,{recursive:!0,force:!0}),a instanceof Gt){g({error:"ZIP_UNAVAILABLE",message:"zip binary not found on PATH"}),process.exit(1);return}if(a instanceof Wt){g({error:"ZIP_FAILED",message:a.message}),process.exit(1);return}g({error:"DEBUG_FAILED",message:a.message}),process.exit(1);return}},id={debug:P_};function od(){let e=z().install.repoBranch;return e==="dev"||e==="staging"}var ad={...$o,...ta,...qa,...al,...dl,...ul,...bl,...Il,...xl,...vl,...Cl,...Ll,...Bl,...Kl,...Yl,...Zl,...od()?id:{}},L_=new Set(["wallet-add-external"]);function cd(e){return ad[e]}function Hs(){return Object.keys(ad).filter(e=>!L_.has(e)).sort()}var{json:ld,argv:O_}=Ks(process.argv.slice(2));Js(ld?"json":"plain");var qs;try{let e=wc(O_);yc(e.account),qs=e.argv}catch(e){g({error:"USAGE",message:e.message}),process.exit(1)}var ve=qs[0];if(ve==="--version"||ve==="-v"){let e=Rn();console.log(ld?JSON.stringify(e):ed(e)),process.exit(0)}(!ve||ve==="--help"||ve==="-h")&&(g({error:"USAGE",message:"amb <command> [args]",commands:Hs()}),process.exit(ve?0:1));var dd=cd(ve);dd||(g({error:"UNKNOWN_COMMAND",message:`Unknown command: ${ve}`,commands:Hs()}),process.exit(1));var bn=Ec(ve);if(bn){let e=K();e.mode&&e.mode!==bn&&(g({error:"MODE_MISMATCH",message:Rc(bn,e.mode),required_mode:bn,active_mode:e.mode,active_reason:e.reason}),process.exit(1))}try{await dd(qs.slice(1))}catch(e){g({error:"CLI_ERROR",message:e.message??String(e)}),process.exit(1)}
604
+ license: ${e.license}`}p();import l1 from"fs";import Jt from"path";function ZR(e,t){return[{arcname:`events-${e}.jsonl`,rel:Jt.join("events",`${e}.jsonl`)},{arcname:`monitor-trace-${e}.log`,rel:Jt.join("run",`monitor-trace-${e}.log`)},{arcname:`relay-error-${e}.log`,rel:Jt.join("run",`relay-error-${e}.log`)},{arcname:`relay-trace-${e}.jsonl`,rel:Jt.join("run",`relay-trace-${e}.jsonl`)},{arcname:`mon-${e}.pid`,rel:Jt.join("run",`mon-${e}.pid`)},{arcname:`sup-${e}.pid`,rel:Jt.join("run",`sup-${e}.pid`)},{arcname:`relay-${e}.pid`,rel:Jt.join("run",`relay-${e}.pid`)},{arcname:`cursor-openclaw-${e}`,rel:Jt.join("cursors",`openclaw-${e}`)},{arcname:`cursor-stdout-${e}`,rel:Jt.join("cursors",`stdout-${e}`)}].map(({arcname:n,rel:s})=>{let i=Jt.join(t,s);return{arcname:n,absPath:i,present:l1.existsSync(i)}})}p();function eA(e){let t=e.artifacts.filter(o=>o.present).map(o=>o.arcname),r=e.artifacts.filter(o=>!o.present).map(o=>o.arcname),n={ride_id:e.rideId,created_at:e.createdAt,version:e.version,ride_row:e.rideRow,liveness:e.liveness,collected:t,missing:r},s=e.rideRow===null?["_No local DB record for this request_id \u2014 confirm it is the id from `amb ride request` output (the local request_id, not the upstream ride id)._"]:["```json",JSON.stringify(e.rideRow,null,2),"```"],i=o=>o.length?o.map(c=>`- ${c}`):["- (none)"];return{markdown:[`# amb debug \u2014 ${e.rideId}`,"",`- created_at: ${e.createdAt}`,`- version: ${e.version.version} / git_sha ${e.version.git_sha} / branch ${e.version.branch} / install ${e.version.install_mode}`,"","## ride_requests row","",...s,"","## liveness (locks held-alive at collection time)","",`- monitor (mon-): ${e.liveness.monitor}`,`- supervisor (sup-): ${e.liveness.supervisor}`,`- relay (relay-): ${e.liveness.relay}`,"> The relay lock is held only by the OpenClaw delivery flavor; the stdout flavor (Claude Code / Hermes / codex) runs without it, so `relay: false` there is normal, not a failure.","","## collected","",...i(t),"","## missing","",...i(r),""].join(`
605
+ `),manifest:n}}p();import{spawn as u1}from"child_process";import d1 from"path";var $s=class extends Error{constructor(){super("zip binary not found on PATH"),this.name="ZipUnavailableError"}},Ws=class extends Error{constructor(t){super(`zip exited ${t}`),this.name="ZipFailedError"}},p1=(e,t,r)=>new Promise((n,s)=>{let i=u1(e,t,{cwd:r,stdio:"ignore"});i.on("error",s),i.on("exit",a=>n(a??1))});async function tA(e){if(!d1.isAbsolute(e.outZipPath))throw new Error("outZipPath must be absolute");let t=e.run??p1,r;try{r=await t("zip",["-r","-q",e.outZipPath,"."],e.stagingDir)}catch(n){throw n.code==="ENOENT"?new $s:n}if(r!==0)throw new Ws(r)}function rA(e){let t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}var m1=async e=>{let t=e[0];if(!t||t.startsWith("--")){b({error:"USAGE",message:"amb debug <request_id>"}),process.exit(1);return}if(/[/\\]/.test(t)||t.includes("..")||t.includes("\0")){b({error:"INVALID_RIDE_ID",message:'rideId must not contain path separators or ".."'}),process.exit(1);return}O(rn());let r=ge(),n=new Date,s=Hn.join(r,"debug"),i=Hn.join(s,`.staging-${rA(n)}-${process.pid}`);Gn.mkdirSync(i,{recursive:!0});let a=Hn.join(s,`tada-debug-${t.slice(0,8)}-${rA(n)}.zip`);try{let o=ZR(t,r);for(let d of o)if(d.present)try{Gn.copyFileSync(d.absPath,Hn.join(i,d.arcname))}catch{d.present=!1}let c=Do(),u=De(),l=eA({rideId:t,createdAt:n.toISOString(),version:{version:c.version,git_sha:c.git_sha,branch:u.install.repoBranch,install_mode:u.install.mode},rideRow:Ae(t)??null,liveness:{monitor:Ln(r,`mon-${t}`),supervisor:Ln(r,`sup-${t}`),relay:Ln(r,`relay-${t}`)},artifacts:o.map(d=>({arcname:d.arcname,present:d.present}))});Gn.writeFileSync(Hn.join(i,"summary.md"),l.markdown),Gn.writeFileSync(Hn.join(i,"manifest.json"),JSON.stringify(l.manifest,null,2)),await tA({stagingDir:i,outZipPath:a}),Gn.rmSync(i,{recursive:!0,force:!0}),w({ok:!0,zipPath:a,rideId:t,collected:o.filter(d=>d.present).map(d=>d.arcname),missing:o.filter(d=>!d.present).map(d=>d.arcname)})}catch(o){if(Gn.rmSync(i,{recursive:!0,force:!0}),o instanceof $s){b({error:"ZIP_UNAVAILABLE",message:"zip binary not found on PATH"}),process.exit(1);return}if(o instanceof Ws){b({error:"ZIP_FAILED",message:o.message}),process.exit(1);return}b({error:"DEBUG_FAILED",message:o.message}),process.exit(1);return}},nA={debug:m1};p();p();async function Js(e,t,r,n,s,i){if(!e)throw new Error("TADA coupon API: host required");let a=await fetch(`${e.replace(/\/$/,"")}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...i?{"Accept-Language":i}:{}},body:s===void 0?void 0:JSON.stringify(s)});if(!a.ok)throw dt(a.status,await a.text().catch(()=>""));return a.json()}function sA(e){let t=new URLSearchParams;e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.pageSize!==void 0&&t.set("pageSize",String(e.pageSize)),e.sort!==void 0&&t.set("sort",e.sort);let r=t.toString();return r?`?${r}`:""}function iA(e,t,r={}){return Js(e,"GET",`/v1/coupons/current${sA(r)}`,t)}function aA(e,t,r={}){return Js(e,"GET",`/v1/coupons/past${sA(r)}`,t)}function oA(e,t,r){return Js(e,"GET",`/v1/coupons/${encodeURIComponent(r)}`,t)}function cA(e,t,r){return Js(e,"POST","/v1/coupons/register",t,{code:r})}function f1(e,t,r,n){return Js(e,"POST","/v1/coupons/available",t,r,n)}async function lA(e,t,r,n){let i=(await Fs(e,t,{locations:r.locations,payment_item_uuid:r.payment_item_uuid,product_ids:[r.product_id]})).products.find(a=>a.id===r.product_id&&!a.na&&a.price_entry);if(!i?.car_type||!i.price_entry)throw new Error("Selected product is not available for coupon lookup. Re-run ride-search.");return f1(e,t,{locations:r.locations,payment_item_uuid:r.payment_item_uuid,product_id:i.id,car_type:i.car_type,ride_price:i.price_entry.ride_price},n)}function Mt(e){b({error:"INVALID_ARGUMENT",message:e}),process.exit(1)}function uA(e,t=!1){let r={};for(let n=0;n<e.length;n++){let s=e[n],i=e[++n];if(!i)throw new Error(`${s} requires a value.`);if(s==="--page"){let a=Number(i);if(!/^\d+$/.test(i)||!Number.isSafeInteger(a)||a>2147483647)throw new Error("--page must be a non-negative 32-bit integer.");r.page=a}else if(s==="--page-size"){if(!/^\d+$/.test(i)||Number(i)<1||Number(i)>100)throw new Error("--page-size must be between 1 and 100.");r.pageSize=Number(i)}else if(s==="--sort"){if(!/^(createdAt|validUntil)(,(asc|desc))?$/.test(i))throw new Error("--sort must be createdAt or validUntil, optionally followed by ,asc or ,desc.");r.sort=i}else if(t&&s==="--status"){if(i!=="used"&&i!=="expired")throw new Error("--status must be used or expired.");r.status=i}else throw new Error(`Unknown option: ${s}`)}return r}function Ks(e){let t=typeof e.status=="string"&&["READY","USED","EXPIRED"].includes(e.status),r=typeof e.discount_type=="string"&&["RATE","AMOUNT","TARGET"].includes(e.discount_type),n=!t||!r,s=n?"This coupon uses an unsupported status or discount type and cannot be used by this CLI.":e.unavailable_reason??null;return{code:e.code,title:e.title,...e.description!=null?{description:e.description}:{},status:e.status,discount_type:e.discount_type,amount:e.amount,max_amount:e.max_amount,min_spend_amount:e.min_spend_amount,currency:e.currency,valid_from:e.valid_from,valid_until:e.valid_until,expired:e.expired,payment_methods:e.payment_methods,...e.promotion_code!=null?{campaign_promotion_code:e.promotion_code}:{},...e.used_ride_id!=null?{used_ride_id:e.used_ride_id}:{},...e.used_at!=null?{used_at:e.used_at}:{},available:n?!1:e.available??null,unavailable_reason:s}}function dA(e){let t=e.code,r=e.detail,n=t==="invalid_parameter"||t==="coupon_cannot_apply"||t==="coupon_not_usable"||t==="coupon_issue_not_allowed",s={unauthorized:"Your TADA/Throo session expired. Run `amb login` again.",invalid_parameter:"Invalid coupon request parameters."};b({error:t?.toUpperCase()??"COUPON_REQUEST_FAILED",message:(n?r:void 0)??Ta(t)??s[t??""]??e.message}),process.exit(1)}async function Oo(e){let t=D();O(t.dataDir);let r;try{r=await $t(t)}catch(n){b({error:"MEMBER_AUTH_FAILED",message:n.message}),process.exit(1)}try{w(await e(Ye(t.cliGatewayHosts,t.cliGatewayHost),r))}catch(n){dA(n)}}var g1=async e=>{let t;try{t=uA(e)}catch(r){Mt(r.message)}await Oo(async(r,n)=>{let s=await iA(r,n,t);return{coupons:s.coupons.map(Ks),page:s.page,has_next:s.has_next}})},h1=async e=>{let t;try{t=uA(e,!0)}catch(r){Mt(r.message)}await Oo(async(r,n)=>{let s=await aA(r,n,t);return{coupons:s.coupons.map(Ks),page:s.page,has_next:s.has_next}})},y1=async e=>{let t=e[0];(!t||e.length!==1)&&Mt("Usage: amb coupon-detail <code>"),await Oo(async(r,n)=>Ks(await oA(r,n,t)))},_1=async e=>{let t=e[0];(!t||e.length!==1)&&Mt("Usage: amb coupon-register <code>"),await Oo(async(r,n)=>Ks(await cA(r,n,t)))},E1=async e=>{let t,r=[];for(let m=0;m<e.length;m++)e[m]==="--lang"?t=e[++m]??Mt("--lang requires a value."):r.push(e[m]);r[0]||Mt("Usage: amb coupon-available '<json_params>' [--lang TAG]"),r.length!==1&&Mt("coupon-available accepts exactly one json_params argument.");let n;try{n=JSON.parse(r[0])}catch{Mt("Failed to parse json_params argument.")}let s=_o(n.locations),i=n.product_id,a=n.payment_item_uuid;(!s||s.length<2)&&Mt("locations must contain valid origin and destination coordinates."),(!Number.isSafeInteger(i)||i<=0)&&Mt("product_id must be a positive integer."),a!==void 0&&(typeof a!="string"||!a)&&Mt("payment_item_uuid must be a non-empty string.");let o=D();O(o.dataDir);let c;try{c=await Yr(o)}catch(m){b({error:"MEMBER_AUTH_FAILED",message:m.message}),process.exit(1)}let u=s[0],l=Ze(mt(u.latitude,u.longitude),o.cliGatewayHosts,o.cliGatewayHost),d=await Jr(c.backend,a,l);if(d!=null)try{let m=await lA(l,c.jwt,{locations:s,payment_item_uuid:d,product_id:i},t);w(m.map(Ks))}catch(m){dA(m)}},pA={"coupon-current":g1,"coupon-past":h1,"coupon-detail":y1,"coupon-register":_1,"coupon-available":E1};p();function mA(){let e=De().install.repoBranch;return e==="dev"||e==="staging"}var fA={...LT,...QT,...jb,...Ax,...Px,...Ox,...Vx,...Wx,...Jx,...Kx,...Xx,...wR,...NR,...GR,...HR,...XR,...pA,...mA()?nA:{}},T1=new Set(["wallet-add-external"]);function gA(e){return fA[e]}function Xu(){return Object.keys(fA).filter(e=>!T1.has(e)).sort()}var{json:hA,argv:b1}=sd(process.argv.slice(2));nd(hA?"json":"plain");var Qu;try{let e=Ov(b1);Pv(e.account),Qu=e.argv}catch(e){b({error:"USAGE",message:e.message}),process.exit(1)}var ir=Qu[0];if(ir==="--version"||ir==="-v"){let e=Do();console.log(hA?JSON.stringify(e):QR(e)),process.exit(0)}(!ir||ir==="--help"||ir==="-h")&&(b({error:"USAGE",message:"amb <command> [args]",commands:Xu()}),process.exit(ir?0:1));var yA=gA(ir);yA||(b({error:"UNKNOWN_COMMAND",message:`Unknown command: ${ir}`,commands:Xu()}),process.exit(1));var Co=Cv(ir);if(Co){let e=ze();e.mode&&e.mode!==Co&&(b({error:"MODE_MISMATCH",message:Nv(Co,e.mode),required_mode:Co,active_mode:e.mode,active_reason:e.reason}),process.exit(1))}try{await yA(Qu.slice(1))}catch(e){b({error:"CLI_ERROR",message:e.message??String(e)}),process.exit(1)}
606
+ /*! Bundled license information:
607
+
608
+ mime-db/index.js:
609
+ (*!
610
+ * mime-db
611
+ * Copyright(c) 2014 Jonathan Ong
612
+ * Copyright(c) 2015-2022 Douglas Christopher Wilson
613
+ * MIT Licensed
614
+ *)
615
+
616
+ mime-types/index.js:
617
+ (*!
618
+ * mime-types
619
+ * Copyright(c) 2014 Jonathan Ong
620
+ * Copyright(c) 2015 Douglas Christopher Wilson
621
+ * MIT Licensed
622
+ *)
623
+
624
+ axios/dist/node/axios.cjs:
625
+ (*! Axios v1.19.0 Copyright (c) 2026 Matt Zabriskie and contributors *)
626
+ */